Subclassing unittest.TestCase?

Peter Otten __peter__ at
Wed Nov 3 15:16:36 CET 2010

Roy Smith wrote:

> 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 = ""
>    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?

Remove the base class from the module with

del CommonTestCase

before you invoke unittest.main().


More information about the Python-list mailing list