test_args.py 11 KB

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