Subclassing unittest.TestCase?
Roy Smith
roy at panix.com
Wed Nov 3 08:48:38 EDT 2010
I'm using Python 2.6, with unittest2 imported as unittest.
I'm writing a test suite for a web application. There is a subclass of
TestCase for each basic page type. One thing that's in common between
all the pages is that every page must have a valid copyright notice. It
seems like the logical thing would be to put the common test(s) in a
subclass unittest.TestCase and have all my real test cases derive from
that:
class CommonTestCase(unittest.TestCase):
def test_copyright(self):
self.assert_(find copyright notice in DOM tree)
class HomepageTestCase(CommonTestCase):
def setUp(self):
self.url = "http://site.com"
def test_whatever(self):
self.assert_(whatever)
This works fine as far as HomepageTestCase running test_copyright() and
test_whatever(). The problem is that CommonTestCase *also* runs
test_copyright(), which fails because there's no setUp(), and thus no
retrieved page for it to work on.
The hack that I came up with is:
class CommonTestCase(unittest.TestCase):
def test_copyright(self):
if self.__class__.__name__ == 'CommonTestCase':
return
self.assert_(find copyright notice in DOM tree)
which works, but it's ugly. It also counts
CommonTestCase.test_copyright() as passing, which messes up the
statistics. Is there a cleaner way to define some common test methods
which all of my test cases can inherit, without having them be run in
the base class?
More information about the Python-list
mailing list