1 # -*- encoding: utf-8 -*-
6 class MockTclObj(object):
9 def __init__(self, val):
13 return unicode(self.val)
16 class MockStateSpec(object):
17 typename = 'StateSpec'
19 def __init__(self, *args):
23 return ' '.join(self.val)
26 class InternalFunctionsTest(unittest.TestCase):
28 def test_format_optdict(self):
29 def check_against(fmt_opts, result):
30 for i in range(0, len(fmt_opts), 2):
31 self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1])
33 self.fail("result still got elements: %s" % result)
35 # passing an empty dict should return an empty object (tuple here)
36 self.assertFalse(ttk._format_optdict({}))
38 # check list formatting
40 ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),
41 {'-fg': 'blue', '-padding': '1 2 3 4'})
43 # check tuple formatting (same as list)
45 ttk._format_optdict({'test': (1, 2, '', 0)}),
46 {'-test': '1 2 {} 0'})
48 # check untouched values
50 ttk._format_optdict({'test': {'left': 'as is'}}),
51 {'-test': {'left': 'as is'}})
53 # check script formatting and untouched value(s)
56 {'test': [1, -1, '', '2m', 0], 'nochange1': 3,
57 'nochange2': 'abc def'}, script=True),
58 {'-test': '{1 -1 {} 2m 0}', '-nochange1': 3,
59 '-nochange2': 'abc def' })
61 opts = {u'αβγ': True, u'á': False}
62 orig_opts = opts.copy()
63 # check if giving unicode keys is fine
64 check_against(ttk._format_optdict(opts), {u'-αβγ': True, u'-á': False})
65 # opts should remain unchanged
66 self.assertEqual(opts, orig_opts)
68 # passing values with spaces inside a tuple/list
71 {'option': ('one two', 'three')}),
72 {'-option': '{one two} three'})
75 amount_opts = len(ttk._format_optdict(opts, ignore=(u'á'))) // 2
76 self.assertEqual(amount_opts, len(opts) - 1)
78 # ignore non-existing options
79 amount_opts = len(ttk._format_optdict(opts, ignore=(u'á', 'b'))) // 2
80 self.assertEqual(amount_opts, len(opts) - 1)
83 self.assertFalse(ttk._format_optdict(opts, ignore=opts.keys()))
86 def test_format_mapdict(self):
87 opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]}
88 result = ttk._format_mapdict(opts)
89 self.assertEqual(len(result), len(opts.keys()) * 2)
90 self.assertEqual(result, ('-a', '{b c} val d otherval {} single'))
91 self.assertEqual(ttk._format_mapdict(opts, script=True),
92 ('-a', '{{b c} val d otherval {} single}'))
94 self.assertEqual(ttk._format_mapdict({2: []}), ('-2', ''))
96 opts = {u'üñíćódè': [(u'á', u'vãl')]}
97 result = ttk._format_mapdict(opts)
98 self.assertEqual(result, (u'-üñíćódè', u'á vãl'))
101 valid = {'opt': [('', u'', 'hi')]}
102 self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))
104 # when passing multiple states, they all must be strings
105 invalid = {'opt': [(1, 2, 'valid val')]}
106 self.assertRaises(TypeError, ttk._format_mapdict, invalid)
107 invalid = {'opt': [([1], '2', 'valid val')]}
108 self.assertRaises(TypeError, ttk._format_mapdict, invalid)
109 # but when passing a single state, it can be anything
110 valid = {'opt': [[1, 'value']]}
111 self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value'))
112 # special attention to single states which evalute to False
113 for stateval in (None, 0, False, '', set()): # just some samples
114 valid = {'opt': [(stateval, 'value')]}
115 self.assertEqual(ttk._format_mapdict(valid),
116 ('-opt', '{} value'))
118 # values must be iterable
120 self.assertRaises(TypeError, ttk._format_mapdict, opts)
122 # items in the value must have size >= 2
123 self.assertRaises(IndexError, ttk._format_mapdict,
124 {'a': [('invalid', )]})
127 def test_format_elemcreate(self):
128 self.assertTrue(ttk._format_elemcreate(None), (None, ()))
130 ## Testing type = image
131 # image type expects at least an image name, so this should raise
132 # IndexError since it tries to access the index 0 of an empty tuple
133 self.assertRaises(IndexError, ttk._format_elemcreate, 'image')
135 # don't format returned values as a tcl script
136 # minimum acceptable for image type
137 self.assertEqual(ttk._format_elemcreate('image', False, 'test'),
139 # specifiyng a state spec
140 self.assertEqual(ttk._format_elemcreate('image', False, 'test',
141 ('', 'a')), ("test {} a", ()))
142 # state spec with multiple states
143 self.assertEqual(ttk._format_elemcreate('image', False, 'test',
144 ('a', 'b', 'c')), ("test {a b} c", ()))
145 # state spec and options
146 self.assertEqual(ttk._format_elemcreate('image', False, 'test',
147 ('a', 'b'), a='x', b='y'), ("test a b", ("-a", "x", "-b", "y")))
148 # format returned values as a tcl script
149 # state spec with multiple states and an option with a multivalue
150 self.assertEqual(ttk._format_elemcreate('image', True, 'test',
151 ('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 an ValueError since it tries to get two elements from
157 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'),
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"))
174 # Testing type = from
175 # from type expects at least a type name
176 self.assertRaises(IndexError, ttk._format_elemcreate, 'from')
178 self.assertEqual(ttk._format_elemcreate('from', False, 'a'),
180 self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'),
182 self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'),
186 def test_format_layoutlist(self):
187 def sample(indent=0, indent_size=2):
188 return ttk._format_layoutlist(
189 [('a', {'other': [1, 2, 3], 'children':
192 [('d', {'nice': 'opt'})], 'something': (1, 2)
195 })], indent=indent, indent_size=indent_size)[0]
197 def sample_expected(indent=0, indent_size=2):
198 spaces = lambda amount=0: ' ' * (amount + indent)
200 "%sa -other {1 2 3} -children {\n"
202 "%sc -something {1 2} -children {\n"
206 "%s}" % (spaces(), spaces(indent_size),
207 spaces(2 * indent_size), spaces(3 * indent_size),
208 spaces(2 * indent_size), spaces(indent_size), spaces()))
211 self.assertEqual(ttk._format_layoutlist([])[0], '')
213 # smallest (after an empty one) acceptable layout
214 smallest = ttk._format_layoutlist([('a', None)], indent=0)
215 self.assertEqual(smallest,
216 ttk._format_layoutlist([('a', '')], indent=0))
217 self.assertEqual(smallest[0], 'a')
219 # testing indentation levels
220 self.assertEqual(sample(), sample_expected())
222 self.assertEqual(sample(i), sample_expected(i))
223 self.assertEqual(sample(i, i), sample_expected(i, i))
225 # invalid layout format, different kind of exceptions will be
229 self.assertRaises(ValueError, ttk._format_layoutlist,
231 self.assertRaises(TypeError, ttk._format_layoutlist, None)
232 # _format_layoutlist always expects the second item (in every item)
233 # to act like a dict (except when the value evalutes to False).
234 self.assertRaises(AttributeError,
235 ttk._format_layoutlist, [('a', 'b')])
236 # bad children formatting
237 self.assertRaises(ValueError, ttk._format_layoutlist,
238 [('name', {'children': {'a': None}})])
241 def test_script_from_settings(self):
243 self.assertFalse(ttk._script_from_settings({'name':
244 {'configure': None, 'map': None, 'element create': None}}))
248 ttk._script_from_settings({'name': {'layout': None}}),
249 "ttk::style layout name {\nnull\n}")
251 configdict = {u'αβγ': True, u'á': False}
253 ttk._script_from_settings({'name': {'configure': configdict}}))
255 mapdict = {u'üñíćódè': [(u'á', u'vãl')]}
257 ttk._script_from_settings({'name': {'map': mapdict}}))
259 # invalid image element
260 self.assertRaises(IndexError,
261 ttk._script_from_settings, {'name': {'element create': ['image']}})
263 # minimal valid image
264 self.assertTrue(ttk._script_from_settings({'name':
265 {'element create': ['image', 'name']}}))
267 image = {'thing': {'element create':
268 ['image', 'name', ('state1', 'state2', 'val')]}}
269 self.assertEqual(ttk._script_from_settings(image),
270 "ttk::style element create thing image {name {state1 state2} val} ")
272 image['thing']['element create'].append({'opt': 30})
273 self.assertEqual(ttk._script_from_settings(image),
274 "ttk::style element create thing image {name {state1 state2} val} "
277 image['thing']['element create'][-1]['opt'] = [MockTclObj(3),
279 self.assertEqual(ttk._script_from_settings(image),
280 "ttk::style element create thing image {name {state1 state2} val} "
284 def test_dict_from_tcltuple(self):
285 fakettuple = ('-a', '{1 2 3}', '-something', 'foo')
287 self.assertEqual(ttk._dict_from_tcltuple(fakettuple, False),
288 {'-a': '{1 2 3}', '-something': 'foo'})
290 self.assertEqual(ttk._dict_from_tcltuple(fakettuple),
291 {'a': '{1 2 3}', 'something': 'foo'})
293 # passing a tuple with a single item should return an empty dict,
294 # since it tries to break the tuple by pairs.
295 self.assertFalse(ttk._dict_from_tcltuple(('single', )))
297 sspec = MockStateSpec('a', 'b')
298 self.assertEqual(ttk._dict_from_tcltuple(('-a', (sspec, 'val'))),
299 {'a': [('a', 'b', 'val')]})
301 self.assertEqual(ttk._dict_from_tcltuple((MockTclObj('-padding'),
302 [MockTclObj('1'), 2, MockTclObj('3m')])),
303 {'padding': [1, 2, '3m']})
306 def test_list_from_statespec(self):
307 def test_it(sspec, value, res_value, states):
308 self.assertEqual(ttk._list_from_statespec(
309 (sspec, value)), [states + (res_value, )])
311 states_even = tuple('state%d' % i for i in range(6))
312 statespec = MockStateSpec(*states_even)
313 test_it(statespec, 'val', 'val', states_even)
314 test_it(statespec, MockTclObj('val'), 'val', states_even)
316 states_odd = tuple('state%d' % i for i in range(5))
317 statespec = MockStateSpec(*states_odd)
318 test_it(statespec, 'val', 'val', states_odd)
320 test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))
323 def test_list_from_layouttuple(self):
325 self.assertFalse(ttk._list_from_layouttuple(()))
327 # shortest layout tuple
328 self.assertEqual(ttk._list_from_layouttuple(('name', )),
331 # not so interesting ltuple
332 sample_ltuple = ('name', '-option', 'value')
333 self.assertEqual(ttk._list_from_layouttuple(sample_ltuple),
334 [('name', {'option': 'value'})])
337 self.assertEqual(ttk._list_from_layouttuple(
338 ('something', '-children', ())),
339 [('something', {'children': []})]
342 # more interesting ltuple
344 'name', '-option', 'niceone', '-children', (
345 ('otherone', '-children', (
346 ('child', )), '-otheropt', 'othervalue'
350 self.assertEqual(ttk._list_from_layouttuple(ltuple),
351 [('name', {'option': 'niceone', 'children':
352 [('otherone', {'otheropt': 'othervalue', 'children':
359 self.assertRaises(ValueError, ttk._list_from_layouttuple,
360 ('name', 'no_minus'))
361 self.assertRaises(ValueError, ttk._list_from_layouttuple,
362 ('name', 'no_minus', 'value'))
363 self.assertRaises(ValueError, ttk._list_from_layouttuple,
364 ('something', '-children')) # no children
365 self.assertRaises(ValueError, ttk._list_from_layouttuple,
366 ('something', '-children', 'value')) # invalid children
369 def test_val_or_dict(self):
370 def func(opt, val=None):
375 options = {'test': None}
376 self.assertEqual(ttk._val_or_dict(options, func), "test val")
378 options = {'test': 3}
379 self.assertEqual(ttk._val_or_dict(options, func), options)
382 def test_convert_stringval(self):
384 (0, 0), ('09', 9), ('a', 'a'), (u'áÚ', u'áÚ'), ([], '[]'),
387 for orig, expected in tests:
388 self.assertEqual(ttk._convert_stringval(orig), expected)
390 if sys.getdefaultencoding() == 'ascii':
391 self.assertRaises(UnicodeDecodeError,
392 ttk._convert_stringval, 'á')
395 class TclObjsToPyTest(unittest.TestCase):
397 def test_unicode(self):
398 adict = {'opt': u'välúè'}
399 self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
401 adict['opt'] = MockTclObj(adict['opt'])
402 self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
404 def test_multivalues(self):
405 adict = {'opt': [1, 2, 3, 4]}
406 self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]})
408 adict['opt'] = [1, 'xm', 3]
409 self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})
411 adict['opt'] = (MockStateSpec('a', 'b'), u'válũè')
412 self.assertEqual(ttk.tclobjs_to_py(adict),
413 {'opt': [('a', 'b', u'válũè')]})
415 self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}),
418 def test_nosplit(self):
419 self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}),
420 {'text': 'some text'})
422 tests_nogui = (InternalFunctionsTest, TclObjsToPyTest)
424 if __name__ == "__main__":
425 from test.test_support import run_unittest
426 run_unittest(*tests_nogui)