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
)
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
Another workaround i have seen people use is that nested classes wont get run as part of nosetests e.g.
from unittest import TestCase
class NotTested:
class TestPotato(TestCase):
def test_in_parent(self):
print 'in parent'
class TestSpud(NotTested.TestPotato):
def test_in_child(self):
print 'in child'
A workaround I unsuccessfully tried was to use multiple inheritance so the TestPotato class extends object and TestSpud does extend from TestCase and TestPotato e.g.
from unittest import TestCase
class TestPotato(object):
def test_in_parent(self):
# still gets ran twice because
# nosetests runs anything that starts with test_* :(
print 'in parent'
class TestSpud(TestCase, TestPotato):
def test_in_child(self):
print 'in child'
But this actually didn't work for me, i wish it did because you wouldn't need the added nesting of code... but it looks like using multiple inheritance is bad anyway
If the test setUp from a different test class is all you need, you could do this:
from unittest import TestCase
class TestPotato(TestCase):
def setUp(self):
print('fixtures here')
def test_in_parent(self):
print 'in parent'
class TestSpud(TestCase):
def setUp(self):
TestPotato.setUp(self)
def test_in_child(self):
print 'in child'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With