»Core Development>Code coverage>Lib/tkinter/test/test_ttk/test_functions.py

Python code coverage for Lib/tkinter/test/test_ttk/test_functions.py

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