»Core Development>Code coverage>Lib/lib-tk/test/test_ttk/test_functions.py

Python code coverage for Lib/lib-tk/test/test_ttk/test_functions.py

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