[Tutor] testing new style class properties using pyUnit ?

Duncan Gibson duncan at mail-gw.estec.esa.int
Wed Jun 30 12:20:13 EDT 2004


I had a class which used get and set methods to access a
class variable. I set up some unit tests using pyUnit.
After some fiddling about, I managed to get it all working.

I've just upgraded the source to use the new style classes
with properties instead of explicit get and set methods.
However, so far I've been unable to convert the unit tests.
I note the error message, but I don't understand why.

I include a simple example below, showing the working tests
with the old style classes, and the failing tests with the
new style classes. [In fact it's worse than this because my
real code uses class variables and classmethods, and I want
to test the derived classes, but the principle is the same]

Can anyone explain the magical incantation that I need
to test the property setter?

Cheers
Duncan

#--------------------------------------------------
#!/usr/bin/env python2.3
import unittest

#--------------------------------------------------
class A_Old:
    def __init__(self, x=0):
        self.x = x
    def get_x(self):
        return self.x
    def set_x(self, x):
        assert isinstance(x, int)
        self.x = x
#--------------------------------------------------
class A_New(object):
    __slots__ = ('__x',)
    def __init__(self, x=0):
        self.x = x
    def __get_x(self):
        return self.__x
    def __set_x(self, x):
        assert isinstance(x, int)
        self.__x = x
    x = property(__get_x, __set_x)
#--------------------------------------------------
class Test_A_Old(unittest.TestCase):
    def testGet(self):
        a = A_Old()
        self.assertEqual(0, a.get_x())
    def testSet(self):
        a = A_Old()
        self.assertEqual(0, a.get_x())
        self.assertEqual(None, a.set_x(1))
        self.assertEqual(1, a.get_x())
    def testSetFail(self):
        a = A_Old()
        self.assertEqual(0, a.get_x())
        self.assertRaises(AssertionError, a.set_x, 1.0)
#--------------------------------------------------
class Test_A_New(unittest.TestCase):
    def testGet(self):
        a = A_New()
        self.assertEqual(0, a.x)
    def testSet(self):
        a = A_New()
        self.assertEqual(0, a.x)
        self.assertEqual(None, a.__set_x(1))
        # AttributeError: 'A_New' object has no attribute '_Test_A_New__set_x'
        self.assertEqual(1, a.x)
    def testSetFail(self):
        a = A_New()
        self.assertEqual(0, a.x)
        self.assertRaises(AssertionError, a.__set_x, 1.0)
        # AttributeError: 'A_New' object has no attribute '_Test_A_New__set_x'
#--------------------------------------------------
unittest.main()



More information about the Tutor mailing list