test_args.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. # -*- coding: utf-8 -*-
  2. # Import python libs
  3. from __future__ import absolute_import, print_function, unicode_literals
  4. from collections import namedtuple
  5. import logging
  6. # Import Salt Libs
  7. from salt.exceptions import SaltInvocationError
  8. from salt.ext import six
  9. import salt.utils.args
  10. # Import Salt Testing Libs
  11. from tests.support.unit import TestCase
  12. from tests.support.mock import (
  13. DEFAULT,
  14. patch
  15. )
  16. log = logging.getLogger(__name__)
  17. class ArgsTestCase(TestCase):
  18. '''
  19. TestCase for salt.utils.args module
  20. '''
  21. def test_condition_input_string(self):
  22. '''
  23. Test passing a jid on the command line
  24. '''
  25. cmd = salt.utils.args.condition_input(['*', 'foo.bar', 20141020201325675584], None)
  26. self.assertIsInstance(cmd[2], six.text_type)
  27. def test_clean_kwargs(self):
  28. self.assertDictEqual(salt.utils.args.clean_kwargs(foo='bar'), {'foo': 'bar'})
  29. self.assertDictEqual(salt.utils.args.clean_kwargs(__pub_foo='bar'), {})
  30. self.assertDictEqual(salt.utils.args.clean_kwargs(__foo_bar='gwar'), {})
  31. self.assertDictEqual(salt.utils.args.clean_kwargs(foo_bar='gwar'), {'foo_bar': 'gwar'})
  32. def test_get_function_argspec(self):
  33. def dummy_func(first, second, third, fourth='fifth'):
  34. pass
  35. expected_argspec = namedtuple('ArgSpec', 'args varargs keywords defaults')(
  36. args=['first', 'second', 'third', 'fourth'], varargs=None, keywords=None, defaults=('fifth',))
  37. ret = salt.utils.args.get_function_argspec(dummy_func)
  38. self.assertEqual(ret, expected_argspec)
  39. def test_parse_kwarg(self):
  40. ret = salt.utils.args.parse_kwarg('foo=bar')
  41. self.assertEqual(ret, ('foo', 'bar'))
  42. ret = salt.utils.args.parse_kwarg('foobar')
  43. self.assertEqual(ret, (None, None))
  44. def test_arg_lookup(self):
  45. def dummy_func(first, second, third, fourth='fifth'):
  46. pass
  47. expected_dict = {'args': ['first', 'second', 'third'], 'kwargs': {'fourth': 'fifth'}}
  48. ret = salt.utils.args.arg_lookup(dummy_func)
  49. self.assertEqual(expected_dict, ret)
  50. def test_format_call(self):
  51. with patch('salt.utils.args.arg_lookup') as arg_lookup:
  52. def dummy_func(first=None, second=None, third=None):
  53. pass
  54. arg_lookup.return_value = {'args': ['first', 'second', 'third'], 'kwargs': {}}
  55. get_function_argspec = DEFAULT
  56. get_function_argspec.return_value = namedtuple('ArgSpec', 'args varargs keywords defaults')(
  57. args=['first', 'second', 'third', 'fourth'], varargs=None, keywords=None, defaults=('fifth',))
  58. # Make sure we raise an error if we don't pass in the requisite number of arguments
  59. self.assertRaises(SaltInvocationError, salt.utils.args.format_call, dummy_func, {'1': 2})
  60. # Make sure we warn on invalid kwargs
  61. self.assertRaises(SaltInvocationError, salt.utils.args.format_call, dummy_func, {'first': 2, 'seconds': 2, 'third': 3})
  62. ret = salt.utils.args.format_call(dummy_func, {'first': 2, 'second': 2, 'third': 3},
  63. expected_extra_kws=('first', 'second', 'third'))
  64. self.assertDictEqual(ret, {'args': [], 'kwargs': {}})
  65. def test_format_call_simple_args(self):
  66. def foo(one, two=2, three=3):
  67. pass
  68. self.assertEqual(
  69. salt.utils.args.format_call(foo, dict(one=10, two=20, three=30)),
  70. {'args': [10], 'kwargs': dict(two=20, three=30)}
  71. )
  72. self.assertEqual(
  73. salt.utils.args.format_call(foo, dict(one=10, two=20)),
  74. {'args': [10], 'kwargs': dict(two=20, three=3)}
  75. )
  76. self.assertEqual(
  77. salt.utils.args.format_call(foo, dict(one=2)),
  78. {'args': [2], 'kwargs': dict(two=2, three=3)}
  79. )
  80. def test_format_call_mimic_typeerror_exceptions(self):
  81. def foo(one, two=2, three=3):
  82. pass
  83. def foo2(one, two, three=3):
  84. pass
  85. with self.assertRaisesRegex(
  86. SaltInvocationError,
  87. r'foo takes at least 1 argument \(0 given\)'):
  88. salt.utils.args.format_call(foo, dict(two=3))
  89. with self.assertRaisesRegex(
  90. TypeError,
  91. r'foo2 takes at least 2 arguments \(1 given\)'):
  92. salt.utils.args.format_call(foo2, dict(one=1))
  93. def test_argspec_report(self):
  94. def _test_spec(arg1, arg2, kwarg1=None):
  95. pass
  96. test_functions = {'test_module.test_spec': _test_spec}
  97. ret = salt.utils.args.argspec_report(test_functions, 'test_module.test_spec')
  98. self.assertDictEqual(ret, {'test_module.test_spec':
  99. {'kwargs': None,
  100. 'args': ['arg1', 'arg2', 'kwarg1'],
  101. 'defaults': (None, ),
  102. 'varargs': None}})
  103. def test_test_mode(self):
  104. self.assertTrue(salt.utils.args.test_mode(test=True))
  105. self.assertTrue(salt.utils.args.test_mode(Test=True))
  106. self.assertTrue(salt.utils.args.test_mode(tEsT=True))
  107. def test_parse_function_no_args(self):
  108. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc()')
  109. self.assertEqual(fun, 'amod.afunc')
  110. self.assertEqual(args, [])
  111. self.assertEqual(kwargs, {})
  112. def test_parse_function_args_only(self):
  113. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc(str1, str2)')
  114. self.assertEqual(fun, 'amod.afunc')
  115. self.assertEqual(args, ['str1', 'str2'])
  116. self.assertEqual(kwargs, {})
  117. def test_parse_function_kwargs_only(self):
  118. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc(kw1=val1, kw2=val2)')
  119. self.assertEqual(fun, 'amod.afunc')
  120. self.assertEqual(args, [])
  121. self.assertEqual(kwargs, {'kw1': 'val1', 'kw2': 'val2'})
  122. def test_parse_function_args_kwargs(self):
  123. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc(str1, str2, kw1=val1, kw2=val2)')
  124. self.assertEqual(fun, 'amod.afunc')
  125. self.assertEqual(args, ['str1', 'str2'])
  126. self.assertEqual(kwargs, {'kw1': 'val1', 'kw2': 'val2'})
  127. def test_parse_function_malformed_no_name(self):
  128. fun, args, kwargs = salt.utils.args.parse_function('(str1, str2, kw1=val1, kw2=val2)')
  129. self.assertIsNone(fun)
  130. self.assertIsNone(args)
  131. self.assertIsNone(kwargs)
  132. def test_parse_function_malformed_not_fun_def(self):
  133. fun, args, kwargs = salt.utils.args.parse_function('foo bar, some=text')
  134. self.assertIsNone(fun)
  135. self.assertIsNone(args)
  136. self.assertIsNone(kwargs)
  137. def test_parse_function_wrong_bracket_style(self):
  138. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc[str1, str2, kw1=val1, kw2=val2]')
  139. self.assertIsNone(fun)
  140. self.assertIsNone(args)
  141. self.assertIsNone(kwargs)
  142. def test_parse_function_brackets_unballanced(self):
  143. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc(str1, str2, kw1=val1, kw2=val2')
  144. self.assertIsNone(fun)
  145. self.assertIsNone(args)
  146. self.assertIsNone(kwargs)
  147. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc(str1, str2, kw1=val1, kw2=val2]')
  148. self.assertIsNone(fun)
  149. self.assertIsNone(args)
  150. self.assertIsNone(kwargs)
  151. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc(str1, str2, kw1=(val1[val2)], kw2=val2)')
  152. self.assertIsNone(fun)
  153. self.assertIsNone(args)
  154. self.assertIsNone(kwargs)
  155. def test_parse_function_brackets_in_quotes(self):
  156. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc(str1, str2, kw1="(val1[val2)]", kw2=val2)')
  157. self.assertEqual(fun, 'amod.afunc')
  158. self.assertEqual(args, ['str1', 'str2'])
  159. self.assertEqual(kwargs, {'kw1': '(val1[val2)]', 'kw2': 'val2'})
  160. def test_parse_function_quotes(self):
  161. fun, args, kwargs = salt.utils.args.parse_function('amod.afunc("double \\" single \'", \'double " single \\\'\', kw1="equal=equal", kw2=val2)')
  162. self.assertEqual(fun, 'amod.afunc')
  163. self.assertEqual(args, ['double " single \'', 'double " single \''])
  164. self.assertEqual(kwargs, {'kw1': 'equal=equal', 'kw2': 'val2'})
  165. def test_yamlify_arg(self):
  166. '''
  167. Test that we properly yamlify CLI input. In several of the tests below
  168. assertIs is used instead of assertEqual. This is because we want to
  169. confirm that the return value is not a copy of the original, but the
  170. same instance as the original.
  171. '''
  172. def _yamlify_arg(item):
  173. log.debug('Testing yamlify_arg with %r', item)
  174. return salt.utils.args.yamlify_arg(item)
  175. # Make sure non-strings are just returned back
  176. for item in (True, False, None, 123, 45.67, ['foo'], {'foo': 'bar'}):
  177. self.assertIs(_yamlify_arg(item), item)
  178. # Make sure whitespace-only isn't loaded as None
  179. for item in ('', '\t', ' '):
  180. self.assertIs(_yamlify_arg(item), item)
  181. # This value would be loaded as an int (123), the underscores would be
  182. # ignored. Test that we identify this case and return the original
  183. # value.
  184. item = '1_2_3'
  185. self.assertIs(_yamlify_arg(item), item)
  186. # The '#' is treated as a comment when not part of a data structure, we
  187. # don't want that behavior
  188. for item in ('# hash at beginning', 'Hello world! # hash elsewhere'):
  189. self.assertIs(_yamlify_arg(item), item)
  190. # However we _do_ want the # to be intact if it _is_ within a data
  191. # structure.
  192. item = '["foo", "bar", "###"]'
  193. self.assertEqual(_yamlify_arg(item), ["foo", "bar", "###"])
  194. item = '{"foo": "###"}'
  195. self.assertEqual(_yamlify_arg(item), {"foo": "###"})
  196. # The string "None" should load _as_ None
  197. self.assertIs(_yamlify_arg('None'), None)
  198. # Leading dashes, or strings containing colons, will result in lists
  199. # and dicts, and we only want to load lists and dicts when the strings
  200. # look like data structures.
  201. for item in ('- foo', 'foo: bar'):
  202. self.assertIs(_yamlify_arg(item), item)
  203. # Make sure we don't load '|' as ''
  204. item = '|'
  205. self.assertIs(_yamlify_arg(item), item)
  206. # Make sure we don't load '!' as something else (None in 2018.3, '' in newer)
  207. item = '!'
  208. self.assertIs(_yamlify_arg(item), item)
  209. # Make sure we load ints, floats, and strings correctly
  210. self.assertEqual(_yamlify_arg('123'), 123)
  211. self.assertEqual(_yamlify_arg('45.67'), 45.67)
  212. self.assertEqual(_yamlify_arg('foo'), 'foo')
  213. # We tested list/dict loading above, but there is separate logic when
  214. # the string contains a '#', so we need to test again here.
  215. self.assertEqual(_yamlify_arg('["foo", "bar"]'), ["foo", "bar"])
  216. self.assertEqual(_yamlify_arg('{"foo": "bar"}'), {"foo": "bar"})
  217. class KwargRegexTest(TestCase):
  218. def test_arguments_regex(self):
  219. argument_matches = (
  220. ('pip=1.1', ('pip', '1.1')),
  221. ('pip==1.1', None),
  222. ('pip=1.2=1', ('pip', '1.2=1')),
  223. )
  224. for argument, match in argument_matches:
  225. if match is None:
  226. self.assertIsNone(salt.utils.args.KWARG_REGEX.match(argument))
  227. else:
  228. self.assertEqual(
  229. salt.utils.args.KWARG_REGEX.match(argument).groups(), match
  230. )