wim wim - 1 month ago 14
Python Question

Why do tests in derived classes rerun the parent class tests?

When there is significant overlap in test setup, it can keep things DRY to use inheritance. But this causes issues with unnecessary duplication of test execution:

from unittest import TestCase

class TestPotato(TestCase):
def test_in_parent(self):
print 'in parent'

class TestSpud(TestPotato):
def test_in_child(self):
print 'in child'


Testing this module runs the
test_in_parent
twice.

$ python -m unittest example
in parent
.in child
.in parent
.
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK


Why? Is this by design? Can it be disabled by configuring the test runner in a certain way?

I can workaround the issue by moving setup into a non-discovered class, and then use multiple inheritence, but it seems a bit hacky and unnecessary.

note: Same problem occurs in other runners such as nose (
nosetests -s example.py
) and pytest (
py.test example.py
)

Answer

Test runners look up of all methods starting with test. Inherited methods are present in child class - therefore they are detected as tests to run. To avoid that you should extract common code in parent class and do not inherit any actual tests.

from unittest import TestCase

class PotatoTestTemplate(TestCase):
    def setUp():
        pass

class PotatoTest1(PotatoTestTemplate):
    def test1(self):
        pass

class PotatoTest2(PotatoTestTemplate):
    def test1(self):
        pass
Comments