[Python-checkins] r65931 - in sandbox/trunk/ttk-gsoc/src: 2.x/test_ttk.py 2.x/ttk.py 3.x/test_ttk.py 3.x/ttk.py

guilherme.polo python-checkins at python.org
Thu Aug 21 18:31:11 CEST 2008


Author: guilherme.polo
Date: Thu Aug 21 18:31:10 2008
New Revision: 65931

Log:
Moving to v0.1.7

Minor change in _format_layoutlist to start at indentation level 0;
Added initial unit tests.


Added:
   sandbox/trunk/ttk-gsoc/src/2.x/test_ttk.py
   sandbox/trunk/ttk-gsoc/src/3.x/test_ttk.py
Modified:
   sandbox/trunk/ttk-gsoc/src/2.x/ttk.py
   sandbox/trunk/ttk-gsoc/src/3.x/ttk.py

Added: sandbox/trunk/ttk-gsoc/src/2.x/test_ttk.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/ttk-gsoc/src/2.x/test_ttk.py	Thu Aug 21 18:31:10 2008
@@ -0,0 +1,316 @@
+# -*- encoding: utf-8 -*-
+import unittest
+
+import ttk
+
+class MockTclObj(object):
+    typename = 'test'
+
+    def __init__(self, val):
+        self.val = val
+
+    def __str__(self):
+        return unicode(self.val)
+
+
+class MockStateSpec(object):
+    typename = 'StateSpec'
+
+    def __init__(self, *args):
+        self.val = args
+
+    def __str__(self):
+        return ' '.join(self.val)
+
+
+class InternalFunctionsTest(unittest.TestCase):
+
+    def test_format_optdict(self):
+        def check_against(fmt_opts, result):
+            for i in range(0, len(fmt_opts), 2):
+                self.failUnlessEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1])
+            if result:
+                self.fail("result still got elements: %s" % result)
+
+        # passing an empty dict should return an empty object (tuple here)
+        self.failIf(ttk._format_optdict({}))
+
+        # check list formatting
+        check_against(
+            ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),
+            {'-fg': 'blue', '-padding': '1 2 3 4'})
+
+        # check tuple formatting (same as list)
+        check_against(
+            ttk._format_optdict({'test': (1, 2, '', 0)}),
+            {'-test': '1 2 {} 0'})
+
+        # check untouched values
+        check_against(
+            ttk._format_optdict({'test': {'left': 'as is'}}),
+            {'-test': {'left': 'as is'}})
+
+        # check script formatting and untouched value(s)
+        check_against(
+            ttk._format_optdict(
+                {'test': [1, -1, '', '2m', 0], 'nochange1': 3,
+                 'nochange2': 'abc def'}, script=True),
+            {'-test': '{1 -1 {} 2m 0}', '-nochange1': 3,
+             '-nochange2': 'abc def' })
+
+        opts = {u'αβγ': True, u'á': False}
+        orig_opts = opts.copy()
+        # check if giving unicode keys is fine
+        check_against(ttk._format_optdict(opts), {u'-αβγ': True, u'-á': False})
+        # opts should remain unchanged
+        self.failUnlessEqual(opts, orig_opts)
+
+        # ignore an option
+        amount_opts = len(ttk._format_optdict(opts, ignore=(u'á'))) / 2
+        self.failUnlessEqual(amount_opts, len(opts) - 1)
+
+        # ignore non-existing options
+        amount_opts = len(ttk._format_optdict(opts, ignore=(u'á', 'b'))) / 2
+        self.failUnlessEqual(amount_opts, len(opts) - 1)
+
+        # ignore every option
+        self.failIf(ttk._format_optdict(opts, ignore=opts.keys()))
+
+
+    def test_format_mapdict(self):
+        opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]}
+        result = ttk._format_mapdict(opts)
+        self.failUnlessEqual(len(result), len(opts.keys()) * 2)
+        self.failUnlessEqual(result, ('-a', '{b c} val d otherval {} single'))
+        self.failUnlessEqual(ttk._format_mapdict(opts, script=True),
+            ('-a', '{{b c} val d otherval {} single}'))
+
+        self.failUnlessEqual(ttk._format_mapdict({2: []}), ('-2', ''))
+
+        opts = {u'üñíćódè': [(u'á', u'vãl')]}
+        result = ttk._format_mapdict(opts)
+        self.failUnlessEqual(result, (u'-üñíćódè', u'á vãl'))
+
+        # empty states
+        valid = {'opt': [('', u'', 'hi')]}
+        self.failUnlessEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))
+
+        # when passing multiple states, they all must be strings
+        invalid = {'opt': [(1, 2, 'valid val')]}
+        self.failUnlessRaises(TypeError, ttk._format_mapdict, invalid)
+        invalid = {'opt': [([1], '2', 'valid val')]}
+        self.failUnlessRaises(TypeError, ttk._format_mapdict, invalid)
+        # but when passing a single state, it can be anything
+        valid = {'opt': [[1, 'value']]}
+        self.failUnlessEqual(ttk._format_mapdict(valid), ('-opt', '1 value'))
+        # special attention to single states which evalute to False
+        for stateval in (None, 0, False, '', set()): # just some samples
+            valid = {'opt': [(stateval, 'value')]}
+            self.failUnlessEqual(ttk._format_mapdict(valid),
+                ('-opt', '{} value'))
+
+        # values must be iterable
+        opts = {'a': None}
+        self.failUnlessRaises(TypeError, ttk._format_mapdict, opts)
+
+        # items in the value must have size >= 2
+        self.failUnlessRaises(IndexError, ttk._format_mapdict,
+            {'a': [('invalid', )]})
+
+
+    def test_format_elemcreate(self):
+        self.failUnless(ttk._format_elemcreate(None), (None, ()))
+
+        ## Testing type = image
+        # image type expects at least an image name, so this should raise
+        # IndexError since it tries to access the index 0 of an empty tuple
+        self.failUnlessRaises(IndexError, ttk._format_elemcreate, 'image')
+        
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test'),
+            ("test ", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test',
+            ('', 'a')), ("test {} a", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test',
+            ('a', 'b', 'c')), ("test {a b} c", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test',
+            ('a', 'b'), a='x'), ("test a b", ("-a", "x")))
+        self.failUnlessEqual(ttk._format_elemcreate('image', True, 'test',
+            ('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}"))
+
+        ## Testing type = vsapi
+        # vsapi type expects at least a class name and a part_id, so this
+        # should raise an ValueError since it tries to get two elements from
+        # an empty tuple
+        self.failUnlessRaises(ValueError, ttk._format_elemcreate, 'vsapi')
+
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'),
+            ("a b ", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
+            ('a', 'b', 'c')), ("a b {a b} c", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
+            ('a', 'b'), opt='x'), ("a b a b", ("-opt", "x")))
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b',
+            ('a', 'b', [1, 2]), opt='x'), ("{a b {a b} {1 2}}", "-opt x"))
+
+        # Testing type = from
+        # from type expects at least a type name
+        self.failUnlessRaises(IndexError, ttk._format_elemcreate, 'from')
+
+        self.failUnlessEqual(ttk._format_elemcreate('from', False, 'a'),
+            ('a', ()))
+        self.failUnlessEqual(ttk._format_elemcreate('from', False, 'a', 'b'),
+            ('a', ('b', )))
+        self.failUnlessEqual(ttk._format_elemcreate('from', True, 'a', 'b'),
+            ('{a}', 'b'))
+
+
+    def test_format_layoutlist(self):
+        def sample(indent=0, indent_size=2):
+            return ttk._format_layoutlist(
+            [('a', {'other': [1, 2, 3], 'children':
+                [('b', {'children':
+                    [('c', {'children':
+                        [('d', {'nice': 'opt'})], 'something': (1, 2)
+                    })]
+                })]
+            })], indent=indent, indent_size=indent_size)[0]
+
+        def sample_expected(indent=0, indent_size=2):
+            spaces = lambda amount=0: ' ' * (amount + indent)
+            return (
+                "%sa -other {1 2 3} -children {\n"
+                "%sb -children {\n"
+                "%sc -something {1 2} -children {\n"
+                "%sd -nice opt\n"
+                "%s}\n"
+                "%s}\n"
+                "%s}" % (spaces(), spaces(indent_size),
+                    spaces(2 * indent_size), spaces(3 * indent_size),
+                    spaces(2 * indent_size), spaces(indent_size), spaces()))
+
+        # empty layout
+        self.failUnlessEqual(ttk._format_layoutlist([])[0], '')
+
+        # _format_layoutlist always expects the second item (in every item)
+        # to act like a dict (except when the value evalutes to False).
+        self.failUnlessRaises(AttributeError,
+            ttk._format_layoutlist, [('a', 'b')])
+
+        smallest = ttk._format_layoutlist([('a', None)], indent=0)
+        self.failUnlessEqual(smallest,
+            ttk._format_layoutlist([('a', '')], indent=0))
+        self.failUnlessEqual(smallest[0], 'a')
+
+        # testing indentation levels
+        self.failUnlessEqual(sample(), sample_expected())
+        for i in range(4):
+            self.failUnlessEqual(sample(i), sample_expected(i))
+            self.failUnlessEqual(sample(i, i), sample_expected(i, i))
+
+
+    def test_script_from_settings(self):
+        # XXX ToDo
+        pass
+
+
+    def test_dict_from_tcltuple(self):
+        fakettuple = ('-a', '{1 2 3}', '-something', 'foo')
+
+        self.failUnlessEqual(ttk._dict_from_tcltuple(fakettuple, False),
+            {'-a': '{1 2 3}', '-something': 'foo'})
+
+        self.failUnlessEqual(ttk._dict_from_tcltuple(fakettuple),
+            {'a': '{1 2 3}', 'something': 'foo'})
+
+        # passing a tuple with a single item should return an empty dict,
+        # since it tries to break the tuple by pairs.
+        self.failIf(ttk._dict_from_tcltuple(('single', )))
+
+        sspec = MockStateSpec('a', 'b')
+        self.failUnlessEqual(ttk._dict_from_tcltuple(('-a', (sspec, 'val'))),
+            {'a': [('a', 'b', 'val')]})
+
+        self.failUnlessEqual(ttk._dict_from_tcltuple((MockTclObj('-padding'),
+            [MockTclObj('1'), 2, MockTclObj('3m')])),
+            {'padding': [1, 2, '3m']})
+
+
+    def test_list_from_statespec(self):
+        def test_it(sspec, value, res_value, states):
+            self.failUnlessEqual(ttk._list_from_statespec(
+                (sspec, value)), [states + (res_value, )])
+
+        states_even = tuple('state%d' % i for i in range(6))
+        statespec = MockStateSpec(*states_even)
+        test_it(statespec, 'val', 'val', states_even)
+        test_it(statespec, MockTclObj('val'), 'val', states_even)
+
+        states_odd = tuple('state%d' % i for i in range(5))
+        statespec = MockStateSpec(*states_odd)
+        test_it(statespec, 'val', 'val', states_odd)
+
+        test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))
+
+
+    def test_list_from_layouttuple(self):
+        # XXX ToDo
+        pass
+
+
+    def test_val_or_dict(self):
+        def func(opt, val=None):
+            if val is None:
+                return "test val"
+            return (opt, val)
+
+        options = {'test': None}
+        self.failUnlessEqual(ttk._val_or_dict(options, func), "test val")
+
+        options = {'test': 3}
+        self.failUnlessEqual(ttk._val_or_dict(options, func), options)
+
+
+    def test_convert_stringval(self):
+        tests = (
+            (0, 0), ('09', 9), ('a', 'a'), (u'áÚ', u'áÚ'), ([], '[]'),
+            (None, 'None')
+        )
+        for orig, expected in tests:
+            self.failUnlessEqual(ttk._convert_stringval(orig), expected)
+
+        self.failUnlessRaises(UnicodeDecodeError, ttk._convert_stringval, 'á')
+
+
+class TclObjsToPyTest(unittest.TestCase):
+
+    def test_unicode(self):
+        adict = {'opt': u'välúè'}
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
+
+        adict['opt'] = MockTclObj(adict['opt'])
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
+
+    def test_multivalues(self):
+        adict = {'opt': [1, 2, 3, 4]}
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]})
+
+        adict['opt'] = [1, 'xm', 3]
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})
+
+        adict['opt'] = (MockStateSpec('a', 'b'), u'válũè')
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict),
+            {'opt': [('a', 'b', u'válũè')]})
+
+        self.failUnlessEqual(ttk.tclobjs_to_py({'x': ['y z']}),
+            {'x': ['y z']})
+
+    def test_nosplit(self):
+        self.failUnlessEqual(ttk.tclobjs_to_py({'text': 'some text'}),
+            {'text': 'some text'})
+
+
+def test_main():
+    unittest.main()
+
+if __name__ == "__main__":
+    test_main()

Modified: sandbox/trunk/ttk-gsoc/src/2.x/ttk.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/src/2.x/ttk.py	(original)
+++ sandbox/trunk/ttk-gsoc/src/2.x/ttk.py	Thu Aug 21 18:31:10 2008
@@ -12,7 +12,7 @@
 of the widgets appearance lies at Themes.
 """
 
-__version__ = "0.1.6"
+__version__ = "0.1.7"
 
 __author__ = "Guilherme Polo <ggpolo at gmail.com>"
 
@@ -54,7 +54,7 @@
 Tkinter.Tk._loadtk = _loadttk(Tkinter.Tk._loadtk)
 
 def _format_optdict(optdict, script=False, ignore=None):
-    """Formats optdict to pass it to tk.call.
+    """Formats optdict to a tuple to pass it to tk.call.
     
     E.g. (script=False):
       {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
@@ -157,7 +157,7 @@
 
     return spec, opts
 
-def _format_layoutlist(layout, indent=2, indent_size=2):
+def _format_layoutlist(layout, indent=0, indent_size=2):
     """Formats a layout list so we can pass the result to ttk::style
     layout and ttk::style settings. Note that the layout doesn't has to
     be a list necessarily.
@@ -196,7 +196,8 @@
         if "children" in opts:
             script.append(head + " -children {")
             indent += indent_size
-            newscript, indent  = _format_layoutlist(opts['children'], indent)
+            newscript, indent = _format_layoutlist(opts['children'], indent,
+                indent_size)
             script.append(newscript)
             indent -= indent_size
             script.append('%s}' % (' ' * indent))

Added: sandbox/trunk/ttk-gsoc/src/3.x/test_ttk.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/ttk-gsoc/src/3.x/test_ttk.py	Thu Aug 21 18:31:10 2008
@@ -0,0 +1,314 @@
+# -*- encoding: utf-8 -*-
+import unittest
+
+import ttk
+
+class MockTclObj(object):
+    typename = 'test'
+
+    def __init__(self, val):
+        self.val = val
+
+    def __str__(self):
+        return self.val
+
+
+class MockStateSpec(object):
+    typename = 'StateSpec'
+
+    def __init__(self, *args):
+        self.val = args
+
+    def __str__(self):
+        return ' '.join(self.val)
+
+
+class InternalFunctionsTest(unittest.TestCase):
+
+    def test_format_optdict(self):
+        def check_against(fmt_opts, result):
+            for i in range(0, len(fmt_opts), 2):
+                self.failUnlessEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1])
+            if result:
+                self.fail("result still got elements: %s" % result)
+
+        # passing an empty dict should return an empty object (tuple here)
+        self.failIf(ttk._format_optdict({}))
+
+        # check list formatting
+        check_against(
+            ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),
+            {'-fg': 'blue', '-padding': '1 2 3 4'})
+
+        # check tuple formatting (same as list)
+        check_against(
+            ttk._format_optdict({'test': (1, 2, '', 0)}),
+            {'-test': '1 2 {} 0'})
+
+        # check untouched values
+        check_against(
+            ttk._format_optdict({'test': {'left': 'as is'}}),
+            {'-test': {'left': 'as is'}})
+
+        # check script formatting and untouched value(s)
+        check_against(
+            ttk._format_optdict(
+                {'test': [1, -1, '', '2m', 0], 'nochange1': 3,
+                 'nochange2': 'abc def'}, script=True),
+            {'-test': '{1 -1 {} 2m 0}', '-nochange1': 3,
+             '-nochange2': 'abc def' })
+
+        opts = {'αβγ': True, 'á': False}
+        orig_opts = opts.copy()
+        # check if giving unicode keys is fine
+        check_against(ttk._format_optdict(opts), {'-αβγ': True, '-á': False})
+        # opts should remain unchanged
+        self.failUnlessEqual(opts, orig_opts)
+
+        # ignore an option
+        amount_opts = len(ttk._format_optdict(opts, ignore=('á'))) / 2
+        self.failUnlessEqual(amount_opts, len(opts) - 1)
+
+        # ignore non-existing options
+        amount_opts = len(ttk._format_optdict(opts, ignore=('á', 'b'))) / 2
+        self.failUnlessEqual(amount_opts, len(opts) - 1)
+
+        # ignore every option
+        self.failIf(ttk._format_optdict(opts, ignore=opts.keys()))
+
+
+    def test_format_mapdict(self):
+        opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]}
+        result = ttk._format_mapdict(opts)
+        self.failUnlessEqual(len(result), len(opts.keys()) * 2)
+        self.failUnlessEqual(result, ('-a', '{b c} val d otherval {} single'))
+        self.failUnlessEqual(ttk._format_mapdict(opts, script=True),
+            ('-a', '{{b c} val d otherval {} single}'))
+
+        self.failUnlessEqual(ttk._format_mapdict({2: []}), ('-2', ''))
+
+        opts = {'üñíćódè': [('á', 'vãl')]}
+        result = ttk._format_mapdict(opts)
+        self.failUnlessEqual(result, ('-üñíćódè', 'á vãl'))
+
+        # empty states
+        valid = {'opt': [('', '', 'hi')]}
+        self.failUnlessEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))
+
+        # when passing multiple states, they all must be strings
+        invalid = {'opt': [(1, 2, 'valid val')]}
+        self.failUnlessRaises(TypeError, ttk._format_mapdict, invalid)
+        invalid = {'opt': [([1], '2', 'valid val')]}
+        self.failUnlessRaises(TypeError, ttk._format_mapdict, invalid)
+        # but when passing a single state, it can be anything
+        valid = {'opt': [[1, 'value']]}
+        self.failUnlessEqual(ttk._format_mapdict(valid), ('-opt', '1 value'))
+        # special attention to single states which evalute to False
+        for stateval in (None, 0, False, '', set()): # just some samples
+            valid = {'opt': [(stateval, 'value')]}
+            self.failUnlessEqual(ttk._format_mapdict(valid),
+                ('-opt', '{} value'))
+
+        # values must be iterable
+        opts = {'a': None}
+        self.failUnlessRaises(TypeError, ttk._format_mapdict, opts)
+
+        # items in the value must have size >= 2
+        self.failUnlessRaises(IndexError, ttk._format_mapdict,
+            {'a': [('invalid', )]})
+
+
+    def test_format_elemcreate(self):
+        self.failUnless(ttk._format_elemcreate(None), (None, ()))
+
+        ## Testing type = image
+        # image type expects at least an image name, so this should raise
+        # IndexError since it tries to access the index 0 of an empty tuple
+        self.failUnlessRaises(IndexError, ttk._format_elemcreate, 'image')
+        
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test'),
+            ("test ", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test',
+            ('', 'a')), ("test {} a", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test',
+            ('a', 'b', 'c')), ("test {a b} c", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('image', False, 'test',
+            ('a', 'b'), a='x'), ("test a b", ("-a", "x")))
+        self.failUnlessEqual(ttk._format_elemcreate('image', True, 'test',
+            ('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}"))
+
+        ## Testing type = vsapi
+        # vsapi type expects at least a class name and a part_id, so this
+        # should raise an ValueError since it tries to get two elements from
+        # an empty tuple
+        self.failUnlessRaises(ValueError, ttk._format_elemcreate, 'vsapi')
+
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'),
+            ("a b ", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
+            ('a', 'b', 'c')), ("a b {a b} c", ()))
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
+            ('a', 'b'), opt='x'), ("a b a b", ("-opt", "x")))
+        self.failUnlessEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b',
+            ('a', 'b', [1, 2]), opt='x'), ("{a b {a b} {1 2}}", "-opt x"))
+
+        # Testing type = from
+        # from type expects at least a type name
+        self.failUnlessRaises(IndexError, ttk._format_elemcreate, 'from')
+
+        self.failUnlessEqual(ttk._format_elemcreate('from', False, 'a'),
+            ('a', ()))
+        self.failUnlessEqual(ttk._format_elemcreate('from', False, 'a', 'b'),
+            ('a', ('b', )))
+        self.failUnlessEqual(ttk._format_elemcreate('from', True, 'a', 'b'),
+            ('{a}', 'b'))
+
+
+    def test_format_layoutlist(self):
+        def sample(indent=0, indent_size=2):
+            return ttk._format_layoutlist(
+            [('a', {'other': [1, 2, 3], 'children':
+                [('b', {'children':
+                    [('c', {'children':
+                        [('d', {'nice': 'opt'})], 'something': (1, 2)
+                    })]
+                })]
+            })], indent=indent, indent_size=indent_size)[0]
+
+        def sample_expected(indent=0, indent_size=2):
+            spaces = lambda amount=0: ' ' * (amount + indent)
+            return (
+                "%sa -other {1 2 3} -children {\n"
+                "%sb -children {\n"
+                "%sc -something {1 2} -children {\n"
+                "%sd -nice opt\n"
+                "%s}\n"
+                "%s}\n"
+                "%s}" % (spaces(), spaces(indent_size),
+                    spaces(2 * indent_size), spaces(3 * indent_size),
+                    spaces(2 * indent_size), spaces(indent_size), spaces()))
+
+        # empty layout
+        self.failUnlessEqual(ttk._format_layoutlist([])[0], '')
+
+        # _format_layoutlist always expects the second item (in every item)
+        # to act like a dict (except when the value evalutes to False).
+        self.failUnlessRaises(AttributeError,
+            ttk._format_layoutlist, [('a', 'b')])
+
+        smallest = ttk._format_layoutlist([('a', None)], indent=0)
+        self.failUnlessEqual(smallest,
+            ttk._format_layoutlist([('a', '')], indent=0))
+        self.failUnlessEqual(smallest[0], 'a')
+
+        # testing indentation levels
+        self.failUnlessEqual(sample(), sample_expected())
+        for i in range(4):
+            self.failUnlessEqual(sample(i), sample_expected(i))
+            self.failUnlessEqual(sample(i, i), sample_expected(i, i))
+
+
+    def test_script_from_settings(self):
+        # XXX ToDo
+        pass
+
+
+    def test_dict_from_tcltuple(self):
+        fakettuple = ('-a', '{1 2 3}', '-something', 'foo')
+
+        self.failUnlessEqual(ttk._dict_from_tcltuple(fakettuple, False),
+            {'-a': '{1 2 3}', '-something': 'foo'})
+
+        self.failUnlessEqual(ttk._dict_from_tcltuple(fakettuple),
+            {'a': '{1 2 3}', 'something': 'foo'})
+
+        # passing a tuple with a single item should return an empty dict,
+        # since it tries to break the tuple by pairs.
+        self.failIf(ttk._dict_from_tcltuple(('single', )))
+
+        sspec = MockStateSpec('a', 'b')
+        self.failUnlessEqual(ttk._dict_from_tcltuple(('-a', (sspec, 'val'))),
+            {'a': [('a', 'b', 'val')]})
+
+        self.failUnlessEqual(ttk._dict_from_tcltuple((MockTclObj('-padding'),
+            [MockTclObj('1'), 2, MockTclObj('3m')])),
+            {'padding': [1, 2, '3m']})
+
+
+    def test_list_from_statespec(self):
+        def test_it(sspec, value, res_value, states):
+            self.failUnlessEqual(ttk._list_from_statespec(
+                (sspec, value)), [states + (res_value, )])
+
+        states_even = tuple('state%d' % i for i in range(6))
+        statespec = MockStateSpec(*states_even)
+        test_it(statespec, 'val', 'val', states_even)
+        test_it(statespec, MockTclObj('val'), 'val', states_even)
+
+        states_odd = tuple('state%d' % i for i in range(5))
+        statespec = MockStateSpec(*states_odd)
+        test_it(statespec, 'val', 'val', states_odd)
+
+        test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))
+
+
+    def test_list_from_layouttuple(self):
+        # XXX ToDo
+        pass
+
+
+    def test_val_or_dict(self):
+        def func(opt, val=None):
+            if val is None:
+                return "test val"
+            return (opt, val)
+
+        options = {'test': None}
+        self.failUnlessEqual(ttk._val_or_dict(options, func), "test val")
+
+        options = {'test': 3}
+        self.failUnlessEqual(ttk._val_or_dict(options, func), options)
+
+
+    def test_convert_stringval(self):
+        tests = (
+            (0, 0), ('09', 9), ('a', 'a'), ('áÚ', 'áÚ'), ([], '[]'),
+            (None, 'None')
+        )
+        for orig, expected in tests:
+            self.failUnlessEqual(ttk._convert_stringval(orig), expected)
+
+
+class TclObjsToPyTest(unittest.TestCase):
+
+    def test_unicode(self):
+        adict = {'opt': 'välúè'}
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'})
+
+        adict['opt'] = MockTclObj(adict['opt'])
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'})
+
+    def test_multivalues(self):
+        adict = {'opt': [1, 2, 3, 4]}
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]})
+
+        adict['opt'] = [1, 'xm', 3]
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})
+
+        adict['opt'] = (MockStateSpec('a', 'b'), 'válũè')
+        self.failUnlessEqual(ttk.tclobjs_to_py(adict),
+            {'opt': [('a', 'b', 'válũè')]})
+
+        self.failUnlessEqual(ttk.tclobjs_to_py({'x': ['y z']}),
+            {'x': ['y z']})
+
+    def test_nosplit(self):
+        self.failUnlessEqual(ttk.tclobjs_to_py({'text': 'some text'}),
+            {'text': 'some text'})
+
+
+def test_main():
+    unittest.main()
+
+if __name__ == "__main__":
+    test_main()

Modified: sandbox/trunk/ttk-gsoc/src/3.x/ttk.py
==============================================================================
--- sandbox/trunk/ttk-gsoc/src/3.x/ttk.py	(original)
+++ sandbox/trunk/ttk-gsoc/src/3.x/ttk.py	Thu Aug 21 18:31:10 2008
@@ -12,7 +12,7 @@
 of the widgets appearance lies at Themes.
 """
 
-__version__ = "0.1.6"
+__version__ = "0.1.7"
 
 __author__ = "Guilherme Polo <ggpolo at gmail.com>"
 
@@ -54,7 +54,7 @@
 tkinter.Tk._loadtk = _loadttk(tkinter.Tk._loadtk)
 
 def _format_optdict(optdict, script=False, ignore=None):
-    """Formats optdict to pass it to tk.call.
+    """Formats optdict to a tuple to pass it to tk.call.
     
     E.g. (script=False):
       {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
@@ -157,7 +157,7 @@
 
     return spec, opts
 
-def _format_layoutlist(layout, indent=2, indent_size=2):
+def _format_layoutlist(layout, indent=0, indent_size=2):
     """Formats a layout list so we can pass the result to ttk::style
     layout and ttk::style settings. Note that the layout doesn't has to
     be a list necessarily.
@@ -196,7 +196,8 @@
         if "children" in opts:
             script.append(head + " -children {")
             indent += indent_size
-            newscript, indent  = _format_layoutlist(opts['children'], indent)
+            newscript, indent = _format_layoutlist(opts['children'], indent,
+                indent_size)
             script.append(newscript)
             indent -= indent_size
             script.append('%s}' % (' ' * indent))


More information about the Python-checkins mailing list