f8800ce46204a57af1be88d2dc6832e5a670d3c8
[profile/ivi/python.git] / Lib / lib-tk / test / test_ttk / test_functions.py
1 # -*- encoding: utf-8 -*-
2 import sys
3 import unittest
4 import ttk
5
6 class MockTclObj(object):
7     typename = 'test'
8
9     def __init__(self, val):
10         self.val = val
11
12     def __str__(self):
13         return unicode(self.val)
14
15
16 class MockStateSpec(object):
17     typename = 'StateSpec'
18
19     def __init__(self, *args):
20         self.val = args
21
22     def __str__(self):
23         return ' '.join(self.val)
24
25
26 class InternalFunctionsTest(unittest.TestCase):
27
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])
32             if result:
33                 self.fail("result still got elements: %s" % result)
34
35         # passing an empty dict should return an empty object (tuple here)
36         self.assertFalse(ttk._format_optdict({}))
37
38         # check list formatting
39         check_against(
40             ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),
41             {'-fg': 'blue', '-padding': '1 2 3 4'})
42
43         # check tuple formatting (same as list)
44         check_against(
45             ttk._format_optdict({'test': (1, 2, '', 0)}),
46             {'-test': '1 2 {} 0'})
47
48         # check untouched values
49         check_against(
50             ttk._format_optdict({'test': {'left': 'as is'}}),
51             {'-test': {'left': 'as is'}})
52
53         # check script formatting and untouched value(s)
54         check_against(
55             ttk._format_optdict(
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' })
60
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)
67
68         # passing values with spaces inside a tuple/list
69         check_against(
70             ttk._format_optdict(
71                 {'option': ('one two', 'three')}),
72             {'-option': '{one two} three'})
73
74         # ignore an option
75         amount_opts = len(ttk._format_optdict(opts, ignore=(u'á'))) // 2
76         self.assertEqual(amount_opts, len(opts) - 1)
77
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)
81
82         # ignore every option
83         self.assertFalse(ttk._format_optdict(opts, ignore=opts.keys()))
84
85
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}'))
93
94         self.assertEqual(ttk._format_mapdict({2: []}), ('-2', ''))
95
96         opts = {u'üñíćódè': [(u'á', u'vãl')]}
97         result = ttk._format_mapdict(opts)
98         self.assertEqual(result, (u'-üñíćódè', u'á vãl'))
99
100         # empty states
101         valid = {'opt': [('', u'', 'hi')]}
102         self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))
103
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'))
117
118         # values must be iterable
119         opts = {'a': None}
120         self.assertRaises(TypeError, ttk._format_mapdict, opts)
121
122         # items in the value must have size >= 2
123         self.assertRaises(IndexError, ttk._format_mapdict,
124             {'a': [('invalid', )]})
125
126
127     def test_format_elemcreate(self):
128         self.assertTrue(ttk._format_elemcreate(None), (None, ()))
129
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')
134
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'),
138             ("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}"))
152
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
156         # an empty tuple
157         self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi')
158
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
174         # Testing type = from
175         # from type expects at least a type name
176         self.assertRaises(IndexError, ttk._format_elemcreate, 'from')
177
178         self.assertEqual(ttk._format_elemcreate('from', False, 'a'),
179             ('a', ()))
180         self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'),
181             ('a', ('b', )))
182         self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'),
183             ('{a}', 'b'))
184
185
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':
190                 [('b', {'children':
191                     [('c', {'children':
192                         [('d', {'nice': 'opt'})], 'something': (1, 2)
193                     })]
194                 })]
195             })], indent=indent, indent_size=indent_size)[0]
196
197         def sample_expected(indent=0, indent_size=2):
198             spaces = lambda amount=0: ' ' * (amount + indent)
199             return (
200                 "%sa -other {1 2 3} -children {\n"
201                 "%sb -children {\n"
202                 "%sc -something {1 2} -children {\n"
203                 "%sd -nice opt\n"
204                 "%s}\n"
205                 "%s}\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()))
209
210         # empty layout
211         self.assertEqual(ttk._format_layoutlist([])[0], '')
212
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')
218
219         # testing indentation levels
220         self.assertEqual(sample(), sample_expected())
221         for i in range(4):
222             self.assertEqual(sample(i), sample_expected(i))
223             self.assertEqual(sample(i, i), sample_expected(i, i))
224
225         # invalid layout format, different kind of exceptions will be
226         # raised
227
228         # plain wrong format
229         self.assertRaises(ValueError, ttk._format_layoutlist,
230             ['bad', 'format'])
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}})])
239
240
241     def test_script_from_settings(self):
242         # empty options
243         self.assertFalse(ttk._script_from_settings({'name':
244             {'configure': None, 'map': None, 'element create': None}}))
245
246         # empty layout
247         self.assertEqual(
248             ttk._script_from_settings({'name': {'layout': None}}),
249             "ttk::style layout name {\nnull\n}")
250
251         configdict = {u'αβγ': True, u'á': False}
252         self.assertTrue(
253             ttk._script_from_settings({'name': {'configure': configdict}}))
254
255         mapdict = {u'üñíćódè': [(u'á', u'vãl')]}
256         self.assertTrue(
257             ttk._script_from_settings({'name': {'map': mapdict}}))
258
259         # invalid image element
260         self.assertRaises(IndexError,
261             ttk._script_from_settings, {'name': {'element create': ['image']}})
262
263         # minimal valid image
264         self.assertTrue(ttk._script_from_settings({'name':
265             {'element create': ['image', 'name']}}))
266
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} ")
271
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} "
275             "-opt 30")
276
277         image['thing']['element create'][-1]['opt'] = [MockTclObj(3),
278             MockTclObj('2m')]
279         self.assertEqual(ttk._script_from_settings(image),
280             "ttk::style element create thing image {name {state1 state2} val} "
281             "-opt {3 2m}")
282
283
284     def test_dict_from_tcltuple(self):
285         fakettuple = ('-a', '{1 2 3}', '-something', 'foo')
286
287         self.assertEqual(ttk._dict_from_tcltuple(fakettuple, False),
288             {'-a': '{1 2 3}', '-something': 'foo'})
289
290         self.assertEqual(ttk._dict_from_tcltuple(fakettuple),
291             {'a': '{1 2 3}', 'something': 'foo'})
292
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', )))
296
297         sspec = MockStateSpec('a', 'b')
298         self.assertEqual(ttk._dict_from_tcltuple(('-a', (sspec, 'val'))),
299             {'a': [('a', 'b', 'val')]})
300
301         self.assertEqual(ttk._dict_from_tcltuple((MockTclObj('-padding'),
302             [MockTclObj('1'), 2, MockTclObj('3m')])),
303             {'padding': [1, 2, '3m']})
304
305
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, )])
310
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)
315
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)
319
320         test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))
321
322
323     def test_list_from_layouttuple(self):
324         # empty layout tuple
325         self.assertFalse(ttk._list_from_layouttuple(()))
326
327         # shortest layout tuple
328         self.assertEqual(ttk._list_from_layouttuple(('name', )),
329             [('name', {})])
330
331         # not so interesting ltuple
332         sample_ltuple = ('name', '-option', 'value')
333         self.assertEqual(ttk._list_from_layouttuple(sample_ltuple),
334             [('name', {'option': 'value'})])
335
336         # empty children
337         self.assertEqual(ttk._list_from_layouttuple(
338             ('something', '-children', ())),
339             [('something', {'children': []})]
340         )
341
342         # more interesting ltuple
343         ltuple = (
344             'name', '-option', 'niceone', '-children', (
345                 ('otherone', '-children', (
346                     ('child', )), '-otheropt', 'othervalue'
347                 )
348             )
349         )
350         self.assertEqual(ttk._list_from_layouttuple(ltuple),
351             [('name', {'option': 'niceone', 'children':
352                 [('otherone', {'otheropt': 'othervalue', 'children':
353                     [('child', {})]
354                 })]
355             })]
356         )
357
358         # bad tuples
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
367
368
369     def test_val_or_dict(self):
370         def func(opt, val=None):
371             if val is None:
372                 return "test val"
373             return (opt, val)
374
375         options = {'test': None}
376         self.assertEqual(ttk._val_or_dict(options, func), "test val")
377
378         options = {'test': 3}
379         self.assertEqual(ttk._val_or_dict(options, func), options)
380
381
382     def test_convert_stringval(self):
383         tests = (
384             (0, 0), ('09', 9), ('a', 'a'), (u'áÚ', u'áÚ'), ([], '[]'),
385             (None, 'None')
386         )
387         for orig, expected in tests:
388             self.assertEqual(ttk._convert_stringval(orig), expected)
389
390         if sys.getdefaultencoding() == 'ascii':
391             self.assertRaises(UnicodeDecodeError,
392                 ttk._convert_stringval, 'á')
393
394
395 class TclObjsToPyTest(unittest.TestCase):
396
397     def test_unicode(self):
398         adict = {'opt': u'välúè'}
399         self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
400
401         adict['opt'] = MockTclObj(adict['opt'])
402         self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
403
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]})
407
408         adict['opt'] = [1, 'xm', 3]
409         self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})
410
411         adict['opt'] = (MockStateSpec('a', 'b'), u'válũè')
412         self.assertEqual(ttk.tclobjs_to_py(adict),
413             {'opt': [('a', 'b', u'válũè')]})
414
415         self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}),
416             {'x': ['y z']})
417
418     def test_nosplit(self):
419         self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}),
420             {'text': 'some text'})
421
422 tests_nogui = (InternalFunctionsTest, TclObjsToPyTest)
423
424 if __name__ == "__main__":
425     from test.test_support import run_unittest
426     run_unittest(*tests_nogui)