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.

241 lines
10 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_textinput_with_list_default_mapped_to_cli_friendly_value(self):
  129. """
  130. Issue: #500
  131. Using nargs and a `default` value with a list causes the literal list string
  132. to be put into the UI.
  133. """
  134. testcases = [
  135. {'nargs': '+', 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  136. {'nargs': '*', 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  137. {'nargs': '...', 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  138. {'nargs': 2, 'default': ['a b', 'c'], 'gooey_default': '"a b" "c"', 'w': 'TextField'},
  139. # TODO: this demos the current nargs behavior for string defaults, but
  140. # TODO: it is wrong! These should be wrapped in quotes so spaces aren't
  141. # TODO: interpreted as unique arguments.
  142. {'nargs': '+', 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  143. {'nargs': '*', 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  144. {'nargs': '...', 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  145. {'nargs': 1, 'default': 'a b', 'gooey_default': 'a b', 'w': 'TextField'},
  146. # Listbox has special nargs handling which keeps the list in tact.
  147. {'nargs': '+', 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'], 'w': 'Listbox'},
  148. {'nargs': '*', 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'], 'w': 'Listbox'},
  149. {'nargs': '...', 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'],'w': 'Listbox'},
  150. {'nargs': 2, 'default': ['a b', 'c'], 'gooey_default': ['a b', 'c'], 'w': 'Listbox'},
  151. {'nargs': '+', 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  152. {'nargs': '*', 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  153. {'nargs': '...', 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  154. {'nargs': 1, 'default': 'a b', 'gooey_default': ['a b'], 'w': 'Listbox'},
  155. ]
  156. for case in testcases:
  157. with self.subTest(case):
  158. parser = ArgumentParser(prog='test_program')
  159. parser.add_argument('--foo', nargs=case['nargs'], default=case['default'])
  160. action = parser._actions[-1]
  161. result = argparse_to_json.handle_default(action, case['w'])
  162. self.assertEqual(result, case['gooey_default'])
  163. def test_nargs(self):
  164. """
  165. so there are just a few simple rules here:
  166. if nargs in [*, N, +, remainder]:
  167. default MUST be a list OR we must map it to one
  168. action:_StoreAction
  169. - nargs '?'
  170. - default:validate list is invalid
  171. - default:coerce stringify
  172. - nargs #{*, N, +, REMAINDER}
  173. - default:validate None
  174. - default:coerce
  175. if string: stringify
  176. if list: convert from list to cli style input string
  177. action:_StoreConstAction
  178. - nargs: invalid
  179. - defaults:stringify
  180. action:{_StoreFalseAction, _StoreTrueAction}
  181. - nargs: invalid
  182. - defaults:validate: require bool
  183. - defaults:coerce: no stringify; leave bool
  184. action:_CountAction
  185. - nargs: invalid
  186. - default:validate: must be numeric index within range OR None
  187. - default:coerce: integer or None
  188. action:_AppendAction
  189. TODO: NOT CURRENTLY SUPPORTED BY GOOEY
  190. nargs behavior is weird and needs to be understood.
  191. - nargs
  192. action:CustomUserAction:
  193. - nargs: no way to know expected behavior. Ignore
  194. - default: jsonify type if possible.
  195. """
  196. parser = ArgumentParser()
  197. parser.add_argument(
  198. '--bar',
  199. nargs='+',
  200. choices=["one", "two"],
  201. default="one",
  202. )