From 76ee14989ffa0be5487214169a95a2f9243eabb2 Mon Sep 17 00:00:00 2001 From: James G Sack Date: Thu, 27 Mar 2008 02:36:55 +0000 Subject: [PATCH] Avert potential exception when initializing with a tuple of length 1 or 0 This fixes a side-effect of revision 10398. Also add unittest for grampstype.py, to test this fix svn: r10403 --- src/gen/lib/grampstype.py | 9 +++-- src/gen/lib/test/grampstype_test.py | 56 +++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 src/gen/lib/test/grampstype_test.py diff --git a/src/gen/lib/grampstype.py b/src/gen/lib/grampstype.py index c43ec2301..1ece5739f 100644 --- a/src/gen/lib/grampstype.py +++ b/src/gen/lib/grampstype.py @@ -82,8 +82,13 @@ class GrampsType(object): self.string = u'' def __set_tuple(self, value): - self.val = value[0] - self.string = value[1] + v,s = self._DEFAULT,u'' + if len(value) > 0: + v = value[0] + if len(value) > 1: + s = value[1] + self.val = v + self.string = s def __set_int(self, value): self.val = value diff --git a/src/gen/lib/test/grampstype_test.py b/src/gen/lib/test/grampstype_test.py new file mode 100644 index 000000000..2b07c2f35 --- /dev/null +++ b/src/gen/lib/test/grampstype_test.py @@ -0,0 +1,56 @@ +""" unittest for grampstype """ + +import unittest as U + +from test.test_util import msg +from gen.lib.grampstype import GrampsType, _init_map + +# some simple map items to test with +vals = "zz ab cd ef".split() +keys = range(len(vals)) +MAP = [ (k,v*2,v) for (k,v) in zip(keys, vals) ] + +class GT0(GrampsType): + _DEFAULT = 1 # just avoiding the pre-coded 0 + _CUSTOM = 3 # just avoiding the pre-coded 0 + _DATAMAP = MAP + +class Test1(U.TestCase): + + # some basic tests + def test1a(s): + s.gt=GT0() + s.assertTrue(isinstance(s.gt, GrampsType)) + # spot-check that MAPs get built + e= len(keys) + g= len(s.gt._E2IMAP) + s.assertEquals(g,e, msg(g,e, "expected length of E2IMAP")) + + # init sets values for int, str, tuple + # (we ignore instance here -- maybe SB tested, too?) + # this test depends on having _DEFAULT=1, _CUSTOM=3 + # NB: tuple tests w/ lengths < 2 fail before release 10403 + def test1b(s): + for i,v,u in ( + (None, 1,u''), # all DEFAULT + (0, 0,u''), + (1, 1,u''), + ('efef', 3,'efef'), # matches CUSTOM + ('zzzz', 0,u''), + (u'x', 3,u'x'), # nomatch gives CUSTOM + ('', 3,''), # nomatch gives CUSTOM + ((0,'zero'), 0,'zero'), # normal behavior + ((2,), 2,u''), # DEFAULT-string, just like int + ((), 1,u''), # DEFAULT-pair + ): + s.gt = GT0(i) + g= s.gt.val + s.assertEquals(g,v, + msg(g,v, "initialization val from '%s'" % `i`)) + g= s.gt.string + s.assertEquals(g,u, + msg(g,u, "initialization string from '%s'" % `i`)) + +if __name__ == "__main__": + U.main() +