You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

261 lines
11 KiB

9 years ago
  1. import argparse
  2. import sys
  3. import unittest
  4. from argparse import ArgumentParser
  5. from gooey import GooeyParser
  6. from gooey.python_bindings import argparse_to_json
  7. from gooey.util.functional import getin
  8. from gooey.tests import *
  9. class TestArgparse(unittest.TestCase):
  10. def test_mutex_groups_conversion(self):
  11. """
  12. Ensure multiple mutex groups are processed correctly.
  13. """
  14. parser = ArgumentParser()
  15. g1 = parser.add_mutually_exclusive_group(required=True)
  16. g1.add_argument('--choose1')
  17. g1.add_argument('--choose2')
  18. g2 = parser.add_mutually_exclusive_group(required=True)
  19. g2.add_argument('--choose3')
  20. g2.add_argument('--choose4')
  21. output = argparse_to_json.process(parser, {}, {}, {})
  22. # assert that we get two groups of two choices back
  23. items = output[0]['items']
  24. self.assertTrue(len(items) == 2)
  25. group1 = items[0]
  26. group2 = items[1]
  27. self.assertTrue(['--choose1'] in group1['data']['commands'])
  28. self.assertTrue(['--choose2'] in group1['data']['commands'])
  29. self.assertTrue(['--choose3'] in group2['data']['commands'])
  30. self.assertTrue(['--choose4'] in group2['data']['commands'])
  31. self.assertTrue(group1['type'] == 'RadioGroup')
  32. self.assertTrue(group2['type'] == 'RadioGroup')
  33. def test_json_iterable_conversion(self):
  34. """
  35. Issue #312 - tuples weren't being coerced to list during argparse
  36. conversion causing downstream issues when concatenating
  37. """
  38. # our original functionality accepted only lists as the choices arg
  39. parser = ArgumentParser()
  40. parser.add_argument("-foo", choices=['foo','bar', 'baz'])
  41. result = argparse_to_json.action_to_json(parser._actions[-1], "Dropdown", {})
  42. choices = result['data']['choices']
  43. self.assertTrue(isinstance(choices, list))
  44. self.assertEqual(choices, ['foo','bar', 'baz'])
  45. # Now we allow tuples as well.
  46. parser = ArgumentParser()
  47. parser.add_argument("-foo", choices=('foo','bar', 'baz'))
  48. result = argparse_to_json.action_to_json(parser._actions[-1], "Dropdown", {})
  49. choices = result['data']['choices']
  50. self.assertTrue(isinstance(choices, list))
  51. self.assertEqual(choices, ['foo','bar', 'baz'])
  52. def test_choice_string_cooersion(self):
  53. """
  54. Issue 321 - must coerce choice types to string to support wx.ComboBox
  55. """
  56. parser = ArgumentParser()
  57. parser.add_argument('--foo', default=1, choices=[1, 2, 3])
  58. choice_action = parser._actions[-1]
  59. result = argparse_to_json.action_to_json(choice_action, 'Dropdown', {})
  60. self.assertEqual(getin(result, ['data', 'choices']), ['1', '2', '3'])
  61. # default value is also converted to a string type
  62. self.assertEqual(getin(result, ['data', 'default']), '1')
  63. def test_choice_string_cooersion_no_default(self):
  64. """
  65. Make sure that choice types without a default don't create
  66. the literal string "None" but stick with the value None
  67. """
  68. parser = ArgumentParser()
  69. parser.add_argument('--foo', choices=[1, 2, 3])
  70. choice_action = parser._actions[-1]
  71. result = argparse_to_json.action_to_json(choice_action, 'Dropdown', {})
  72. self.assertEqual(getin(result, ['data', 'default']), None)
  73. def test_listbox_defaults_cast_correctly(self):
  74. """
  75. Issue XXX - defaults supplied in a list were turned into a string
  76. wholesale (list and all). The defaults should be stored as a list
  77. proper with only the _internal_ values coerced to strings.
  78. """
  79. parser = GooeyParser()
  80. parser.add_argument('--foo', widget="Listbox", nargs="*", choices=[1, 2, 3], default=[1, 2])
  81. choice_action = parser._actions[-1]
  82. result = argparse_to_json.action_to_json(choice_action, 'Listbox', {})
  83. self.assertEqual(getin(result, ['data', 'default']), ['1', '2'])
  84. def test_listbox_single_default_cast_correctly(self):
  85. """
  86. Single arg defaults to listbox should be wrapped in a list and
  87. their contents coerced as usual.
  88. """
  89. parser = GooeyParser()
  90. parser.add_argument('--foo', widget="Listbox",
  91. nargs="*", choices=[1, 2, 3], default="sup")
  92. choice_action = parser._actions[-1]
  93. result = argparse_to_json.action_to_json(choice_action, 'Listbox', {})
  94. self.assertEqual(getin(result, ['data', 'default']), ['sup'])
  95. def test_non_data_defaults_are_dropped_entirely(self):
  96. """
  97. This is a refinement in understanding of Issue #147
  98. Caused by Issue 377 - passing arbitrary objects as defaults
  99. causes failures.
  100. """
  101. # passing plain data to cleaning function results in plain data
  102. # being returned
  103. data = ['abc',
  104. 123,
  105. ['a', 'b'],
  106. [1, 2, 3]]
  107. for datum in data:
  108. result = argparse_to_json.clean_default(datum)
  109. self.assertEqual(result, datum)
  110. # passing in complex objects results in None
  111. objects = [sys.stdout, sys.stdin, object(), max, min]
  112. for obj in objects:
  113. result = argparse_to_json.clean_default(obj)
  114. self.assertEqual(result, None)
  115. def test_suppress_is_removed_as_default_value(self):
  116. """
  117. Issue #469
  118. Argparse uses the literal string ==SUPPRESS== as an internal flag.
  119. When encountered in Gooey, these should be dropped and mapped to `None`.
  120. """
  121. parser = ArgumentParser(prog='test_program')
  122. parser.add_argument("--foo", default=argparse.SUPPRESS)
  123. parser.add_argument('--version', action='version', version='1.0')
  124. result = argparse_to_json.convert(parser, num_required_cols=2, num_optional_cols=2)
  125. groups = getin(result, ['widgets', 'test_program', 'contents'])
  126. for item in groups[0]['items']:
  127. self.assertEqual(getin(item, ['data', 'default']), None)
  128. def test_version_maps_to_checkbox(self):
  129. testcases = [
  130. [['--version'], {}, 'TextField'],
  131. # we only remap if the action is version
  132. # i.e. we don't care about the argument name itself
  133. [['--version'], {'action': 'store'}, 'TextField'],
  134. # should get mapped to CheckBox becuase of the action
  135. [['--version'], {'action': 'version'}, 'CheckBox'],
  136. # ditto, even through the 'name' isn't 'version'
  137. [['--foobar'], {'action': 'version'}, 'CheckBox'],
  138. ]
  139. for args, kwargs, expectedType in testcases:
  140. with self.subTest([args, kwargs]):
  141. parser = argparse.ArgumentParser(prog='test')
  142. parser.add_argument(*args, **kwargs)
  143. result = argparse_to_json.convert(parser, num_required_cols=2, num_optional_cols=2)
  144. contents = getin(result, ['widgets', 'test', 'contents'])[0]
  145. self.assertEqual(contents['items'][0]['type'], expectedType)
  146. def test_textinput_with_list_default_mapped_to_cli_friendly_value(self):
  147. """
  148. Issue: #500
  149. Using nargs and a `default` value with a list causes the literal list string
  150. to be put into the UI.
  151. """
  152. testcases = [
  153. {'nargs': '+', 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  154. {'nargs': '*', 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  155. {'nargs': '...', 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  156. {'nargs': 2, 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  157. # TODO: this demos the current nargs behavior for string defaults, but
  158. # TODO: it is wrong! These should be wrapped in quotes so spaces aren't
  159. # TODO: interpreted as unique arguments.
  160. {'nargs': '+', 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  161. {'nargs': '*', 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  162. {'nargs': '...', 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  163. {'nargs': 1, 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  164. # Listbox has special nargs handling which keeps the list in tact.
  165. {'nargs': '+', 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'], 'w': 'Listbox'},
  166. {'nargs': '*', 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'], 'w': 'Listbox'},
  167. {'nargs': '...', 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'],'w': 'Listbox'},
  168. {'nargs': 2, 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'], 'w': 'Listbox'},
  169. {'nargs': '+', 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  170. {'nargs': '*', 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  171. {'nargs': '...', 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  172. {'nargs': 1, 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  173. ]
  174. for case in testcases:
  175. with self.subTest(case):
  176. parser = ArgumentParser(prog='test_program')
  177. parser.add_argument('--foo', nargs=case['nargs'], default=case['default'])
  178. action = parser._actions[-1]
  179. result = argparse_to_json.handle_initial_values(action, case['w'], action.default)
  180. self.assertEqual(result, case['gooey_default'])
  181. def test_nargs(self):
  182. """
  183. so there are just a few simple rules here:
  184. if nargs in [*, N, +, remainder]:
  185. default MUST be a list OR we must map it to one
  186. action:_StoreAction
  187. - nargs '?'
  188. - default:validate list is invalid
  189. - default:coerce stringify
  190. - nargs #{*, N, +, REMAINDER}
  191. - default:validate None
  192. - default:coerce
  193. if string: stringify
  194. if list: convert from list to cli style input string
  195. action:_StoreConstAction
  196. - nargs: invalid
  197. - defaults:stringify
  198. action:{_StoreFalseAction, _StoreTrueAction}
  199. - nargs: invalid
  200. - defaults:validate: require bool
  201. - defaults:coerce: no stringify; leave bool
  202. action:_CountAction
  203. - nargs: invalid
  204. - default:validate: must be numeric index within range OR None
  205. - default:coerce: integer or None
  206. action:_AppendAction
  207. TODO: NOT CURRENTLY SUPPORTED BY GOOEY
  208. nargs behavior is weird and needs to be understood.
  209. - nargs
  210. action:CustomUserAction:
  211. - nargs: no way to know expected behavior. Ignore
  212. - default: jsonify type if possible.
  213. """
  214. parser = ArgumentParser()
  215. parser.add_argument(
  216. '--bar',
  217. nargs='+',
  218. choices=["one", "two"],
  219. default="one",
  220. )