test_ttk_textonly.py 17 KB

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