test_functions.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # -*- encoding: utf-8 -*-
  2. import unittest
  3. from tkinter import ttk
  4. class MockTkApp:
  5. def splitlist(self, arg):
  6. if isinstance(arg, tuple):
  7. return arg
  8. return arg.split(':')
  9. def wantobjects(self):
  10. return True
  11. class MockTclObj(object):
  12. typename = 'test'
  13. def __init__(self, val):
  14. self.val = val
  15. def __str__(self):
  16. return str(self.val)
  17. class MockStateSpec(object):
  18. typename = 'StateSpec'
  19. def __init__(self, *args):
  20. self.val = args
  21. def __str__(self):
  22. return ' '.join(self.val)
  23. class InternalFunctionsTest(unittest.TestCase):
  24. def test_format_optdict(self):
  25. def check_against(fmt_opts, result):
  26. for i in range(0, len(fmt_opts), 2):
  27. self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1])
  28. if result:
  29. self.fail("result still got elements: %s" % result)
  30. # passing an empty dict should return an empty object (tuple here)
  31. self.assertFalse(ttk._format_optdict({}))
  32. # check list formatting
  33. check_against(
  34. ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),
  35. {'-fg': 'blue', '-padding': '1 2 3 4'})
  36. # check tuple formatting (same as list)
  37. check_against(
  38. ttk._format_optdict({'test': (1, 2, '', 0)}),
  39. {'-test': '1 2 {} 0'})
  40. # check untouched values
  41. check_against(
  42. ttk._format_optdict({'test': {'left': 'as is'}}),
  43. {'-test': {'left': 'as is'}})
  44. # check script formatting
  45. check_against(
  46. ttk._format_optdict(
  47. {'test': [1, -1, '', '2m', 0], 'test2': 3,
  48. 'test3': '', 'test4': 'abc def',
  49. 'test5': '"abc"', 'test6': '{}',
  50. 'test7': '} -spam {'}, script=True),
  51. {'-test': '{1 -1 {} 2m 0}', '-test2': '3',
  52. '-test3': '{}', '-test4': '{abc def}',
  53. '-test5': '{"abc"}', '-test6': r'\{\}',
  54. '-test7': r'\}\ -spam\ \{'})
  55. opts = {'αβγ': True, 'á': False}
  56. orig_opts = opts.copy()
  57. # check if giving unicode keys is fine
  58. check_against(ttk._format_optdict(opts), {'-αβγ': True, '-á': False})
  59. # opts should remain unchanged
  60. self.assertEqual(opts, orig_opts)
  61. # passing values with spaces inside a tuple/list
  62. check_against(
  63. ttk._format_optdict(
  64. {'option': ('one two', 'three')}),
  65. {'-option': '{one two} three'})
  66. check_against(
  67. ttk._format_optdict(
  68. {'option': ('one\ttwo', 'three')}),
  69. {'-option': '{one\ttwo} three'})
  70. # passing empty strings inside a tuple/list
  71. check_against(
  72. ttk._format_optdict(
  73. {'option': ('', 'one')}),
  74. {'-option': '{} one'})
  75. # passing values with braces inside a tuple/list
  76. check_against(
  77. ttk._format_optdict(
  78. {'option': ('one} {two', 'three')}),
  79. {'-option': r'one\}\ \{two three'})
  80. # passing quoted strings inside a tuple/list
  81. check_against(
  82. ttk._format_optdict(
  83. {'option': ('"one"', 'two')}),
  84. {'-option': '{"one"} two'})
  85. check_against(
  86. ttk._format_optdict(
  87. {'option': ('{one}', 'two')}),
  88. {'-option': r'\{one\} two'})
  89. # ignore an option
  90. amount_opts = len(ttk._format_optdict(opts, ignore=('á'))) / 2
  91. self.assertEqual(amount_opts, len(opts) - 1)
  92. # ignore non-existing options
  93. amount_opts = len(ttk._format_optdict(opts, ignore=('á', 'b'))) / 2
  94. self.assertEqual(amount_opts, len(opts) - 1)
  95. # ignore every option
  96. self.assertFalse(ttk._format_optdict(opts, ignore=list(opts.keys())))
  97. def test_format_mapdict(self):
  98. opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]}
  99. result = ttk._format_mapdict(opts)
  100. self.assertEqual(len(result), len(list(opts.keys())) * 2)
  101. self.assertEqual(result, ('-a', '{b c} val d otherval {} single'))
  102. self.assertEqual(ttk._format_mapdict(opts, script=True),
  103. ('-a', '{{b c} val d otherval {} single}'))
  104. self.assertEqual(ttk._format_mapdict({2: []}), ('-2', ''))
  105. opts = {'üñíćódè': [('á', 'vãl')]}
  106. result = ttk._format_mapdict(opts)
  107. self.assertEqual(result, ('-üñíćódè', 'á vãl'))
  108. # empty states
  109. valid = {'opt': [('', '', 'hi')]}
  110. self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))
  111. # when passing multiple states, they all must be strings
  112. invalid = {'opt': [(1, 2, 'valid val')]}
  113. self.assertRaises(TypeError, ttk._format_mapdict, invalid)
  114. invalid = {'opt': [([1], '2', 'valid val')]}
  115. self.assertRaises(TypeError, ttk._format_mapdict, invalid)
  116. # but when passing a single state, it can be anything
  117. valid = {'opt': [[1, 'value']]}
  118. self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value'))
  119. # special attention to single states which evaluate to False
  120. for stateval in (None, 0, False, '', set()): # just some samples
  121. valid = {'opt': [(stateval, 'value')]}
  122. self.assertEqual(ttk._format_mapdict(valid),
  123. ('-opt', '{} value'))
  124. # values must be iterable
  125. opts = {'a': None}
  126. self.assertRaises(TypeError, ttk._format_mapdict, opts)
  127. # items in the value must have size >= 2
  128. self.assertRaises(IndexError, ttk._format_mapdict,
  129. {'a': [('invalid', )]})
  130. def test_format_elemcreate(self):
  131. self.assertTrue(ttk._format_elemcreate(None), (None, ()))
  132. ## Testing type = image
  133. # image type expects at least an image name, so this should raise
  134. # IndexError since it tries to access the index 0 of an empty tuple
  135. self.assertRaises(IndexError, ttk._format_elemcreate, 'image')
  136. # don't format returned values as a tcl script
  137. # minimum acceptable for image type
  138. self.assertEqual(ttk._format_elemcreate('image', False, 'test'),
  139. ("test ", ()))
  140. # specifying a state spec
  141. self.assertEqual(ttk._format_elemcreate('image', False, 'test',
  142. ('', 'a')), ("test {} a", ()))
  143. # state spec with multiple states
  144. self.assertEqual(ttk._format_elemcreate('image', False, 'test',
  145. ('a', 'b', 'c')), ("test {a b} c", ()))
  146. # state spec and options
  147. self.assertEqual(ttk._format_elemcreate('image', False, 'test',
  148. ('a', 'b'), a='x'), ("test a b", ("-a", "x")))
  149. # format returned values as a tcl script
  150. # state spec with multiple states and an option with a multivalue
  151. self.assertEqual(ttk._format_elemcreate('image', True, 'test',
  152. ('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}"))
  153. ## Testing type = vsapi
  154. # vsapi type expects at least a class name and a part_id, so this
  155. # should raise a ValueError since it tries to get two elements from
  156. # an empty tuple
  157. self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi')
  158. # don't format returned values as a tcl script
  159. # minimum acceptable for vsapi
  160. self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'),
  161. ("a b ", ()))
  162. # now with a state spec with multiple states
  163. self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
  164. ('a', 'b', 'c')), ("a b {a b} c", ()))
  165. # state spec and option
  166. self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
  167. ('a', 'b'), opt='x'), ("a b a b", ("-opt", "x")))
  168. # format returned values as a tcl script
  169. # state spec with a multivalue and an option
  170. self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b',
  171. ('a', 'b', [1, 2]), opt='x'), ("{a b {a b} {1 2}}", "-opt x"))
  172. # Testing type = from
  173. # from type expects at least a type name
  174. self.assertRaises(IndexError, ttk._format_elemcreate, 'from')
  175. self.assertEqual(ttk._format_elemcreate('from', False, 'a'),
  176. ('a', ()))
  177. self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'),
  178. ('a', ('b', )))
  179. self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'),
  180. ('{a}', 'b'))
  181. def test_format_layoutlist(self):
  182. def sample(indent=0, indent_size=2):
  183. return ttk._format_layoutlist(
  184. [('a', {'other': [1, 2, 3], 'children':
  185. [('b', {'children':
  186. [('c', {'children':
  187. [('d', {'nice': 'opt'})], 'something': (1, 2)
  188. })]
  189. })]
  190. })], indent=indent, indent_size=indent_size)[0]
  191. def sample_expected(indent=0, indent_size=2):
  192. spaces = lambda amount=0: ' ' * (amount + indent)
  193. return (
  194. "%sa -other {1 2 3} -children {\n"
  195. "%sb -children {\n"
  196. "%sc -something {1 2} -children {\n"
  197. "%sd -nice opt\n"
  198. "%s}\n"
  199. "%s}\n"
  200. "%s}" % (spaces(), spaces(indent_size),
  201. spaces(2 * indent_size), spaces(3 * indent_size),
  202. spaces(2 * indent_size), spaces(indent_size), spaces()))
  203. # empty layout
  204. self.assertEqual(ttk._format_layoutlist([])[0], '')
  205. # _format_layoutlist always expects the second item (in every item)
  206. # to act like a dict (except when the value evaluates to False).
  207. self.assertRaises(AttributeError,
  208. ttk._format_layoutlist, [('a', 'b')])
  209. smallest = ttk._format_layoutlist([('a', None)], indent=0)
  210. self.assertEqual(smallest,
  211. ttk._format_layoutlist([('a', '')], indent=0))
  212. self.assertEqual(smallest[0], 'a')
  213. # testing indentation levels
  214. self.assertEqual(sample(), sample_expected())
  215. for i in range(4):
  216. self.assertEqual(sample(i), sample_expected(i))
  217. self.assertEqual(sample(i, i), sample_expected(i, i))
  218. # invalid layout format, different kind of exceptions will be
  219. # raised by internal functions
  220. # plain wrong format
  221. self.assertRaises(ValueError, ttk._format_layoutlist,
  222. ['bad', 'format'])
  223. # will try to use iteritems in the 'bad' string
  224. self.assertRaises(AttributeError, ttk._format_layoutlist,
  225. [('name', 'bad')])
  226. # bad children formatting
  227. self.assertRaises(ValueError, ttk._format_layoutlist,
  228. [('name', {'children': {'a': None}})])
  229. def test_script_from_settings(self):
  230. # empty options
  231. self.assertFalse(ttk._script_from_settings({'name':
  232. {'configure': None, 'map': None, 'element create': None}}))
  233. # empty layout
  234. self.assertEqual(
  235. ttk._script_from_settings({'name': {'layout': None}}),
  236. "ttk::style layout name {\nnull\n}")
  237. configdict = {'αβγ': True, 'á': False}
  238. self.assertTrue(
  239. ttk._script_from_settings({'name': {'configure': configdict}}))
  240. mapdict = {'üñíćódè': [('á', 'vãl')]}
  241. self.assertTrue(
  242. ttk._script_from_settings({'name': {'map': mapdict}}))
  243. # invalid image element
  244. self.assertRaises(IndexError,
  245. ttk._script_from_settings, {'name': {'element create': ['image']}})
  246. # minimal valid image
  247. self.assertTrue(ttk._script_from_settings({'name':
  248. {'element create': ['image', 'name']}}))
  249. image = {'thing': {'element create':
  250. ['image', 'name', ('state1', 'state2', 'val')]}}
  251. self.assertEqual(ttk._script_from_settings(image),
  252. "ttk::style element create thing image {name {state1 state2} val} ")
  253. image['thing']['element create'].append({'opt': 30})
  254. self.assertEqual(ttk._script_from_settings(image),
  255. "ttk::style element create thing image {name {state1 state2} val} "
  256. "-opt 30")
  257. image['thing']['element create'][-1]['opt'] = [MockTclObj(3),
  258. MockTclObj('2m')]
  259. self.assertEqual(ttk._script_from_settings(image),
  260. "ttk::style element create thing image {name {state1 state2} val} "
  261. "-opt {3 2m}")
  262. def test_tclobj_to_py(self):
  263. self.assertEqual(
  264. ttk._tclobj_to_py((MockStateSpec('a', 'b'), 'val')),
  265. [('a', 'b', 'val')])
  266. self.assertEqual(
  267. ttk._tclobj_to_py([MockTclObj('1'), 2, MockTclObj('3m')]),
  268. [1, 2, '3m'])
  269. def test_list_from_statespec(self):
  270. def test_it(sspec, value, res_value, states):
  271. self.assertEqual(ttk._list_from_statespec(
  272. (sspec, value)), [states + (res_value, )])
  273. states_even = tuple('state%d' % i for i in range(6))
  274. statespec = MockStateSpec(*states_even)
  275. test_it(statespec, 'val', 'val', states_even)
  276. test_it(statespec, MockTclObj('val'), 'val', states_even)
  277. states_odd = tuple('state%d' % i for i in range(5))
  278. statespec = MockStateSpec(*states_odd)
  279. test_it(statespec, 'val', 'val', states_odd)
  280. test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))
  281. def test_list_from_layouttuple(self):
  282. tk = MockTkApp()
  283. # empty layout tuple
  284. self.assertFalse(ttk._list_from_layouttuple(tk, ()))
  285. # shortest layout tuple
  286. self.assertEqual(ttk._list_from_layouttuple(tk, ('name', )),
  287. [('name', {})])
  288. # not so interesting ltuple
  289. sample_ltuple = ('name', '-option', 'value')
  290. self.assertEqual(ttk._list_from_layouttuple(tk, sample_ltuple),
  291. [('name', {'option': 'value'})])
  292. # empty children
  293. self.assertEqual(ttk._list_from_layouttuple(tk,
  294. ('something', '-children', ())),
  295. [('something', {'children': []})]
  296. )
  297. # more interesting ltuple
  298. ltuple = (
  299. 'name', '-option', 'niceone', '-children', (
  300. ('otherone', '-children', (
  301. ('child', )), '-otheropt', 'othervalue'
  302. )
  303. )
  304. )
  305. self.assertEqual(ttk._list_from_layouttuple(tk, ltuple),
  306. [('name', {'option': 'niceone', 'children':
  307. [('otherone', {'otheropt': 'othervalue', 'children':
  308. [('child', {})]
  309. })]
  310. })]
  311. )
  312. # bad tuples
  313. self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,
  314. ('name', 'no_minus'))
  315. self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,
  316. ('name', 'no_minus', 'value'))
  317. self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,
  318. ('something', '-children')) # no children
  319. def test_val_or_dict(self):
  320. def func(res, opt=None, val=None):
  321. if opt is None:
  322. return res
  323. if val is None:
  324. return "test val"
  325. return (opt, val)
  326. tk = MockTkApp()
  327. tk.call = func
  328. self.assertEqual(ttk._val_or_dict(tk, {}, '-test:3'),
  329. {'test': '3'})
  330. self.assertEqual(ttk._val_or_dict(tk, {}, ('-test', 3)),
  331. {'test': 3})
  332. self.assertEqual(ttk._val_or_dict(tk, {'test': None}, 'x:y'),
  333. 'test val')
  334. self.assertEqual(ttk._val_or_dict(tk, {'test': 3}, 'x:y'),
  335. {'test': 3})
  336. def test_convert_stringval(self):
  337. tests = (
  338. (0, 0), ('09', 9), ('a', 'a'), ('áÚ', 'áÚ'), ([], '[]'),
  339. (None, 'None')
  340. )
  341. for orig, expected in tests:
  342. self.assertEqual(ttk._convert_stringval(orig), expected)
  343. class TclObjsToPyTest(unittest.TestCase):
  344. def test_unicode(self):
  345. adict = {'opt': 'välúè'}
  346. self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'})
  347. adict['opt'] = MockTclObj(adict['opt'])
  348. self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'})
  349. def test_multivalues(self):
  350. adict = {'opt': [1, 2, 3, 4]}
  351. self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]})
  352. adict['opt'] = [1, 'xm', 3]
  353. self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})
  354. adict['opt'] = (MockStateSpec('a', 'b'), 'válũè')
  355. self.assertEqual(ttk.tclobjs_to_py(adict),
  356. {'opt': [('a', 'b', 'válũè')]})
  357. self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}),
  358. {'x': ['y z']})
  359. def test_nosplit(self):
  360. self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}),
  361. {'text': 'some text'})
  362. tests_nogui = (InternalFunctionsTest, TclObjsToPyTest)
  363. if __name__ == "__main__":
  364. from test.support import run_unittest
  365. run_unittest(*tests_nogui)