How To Run The Same Test-case For Different Classes?
I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them. As an example, suppose I have
Solution 1:
You could use multiple inheritance.
classPartitionerInvariantsFixture(object):defsetUp(self):
self.testDataSet = range(100) # create test-data-setsuper(PartitionInvariantsFixture, self).setUp()
deftest_partitioner(self):
TestCase.assertEqual(self.testDataSet,
chain.from_iterable(self.partitioner(self.testDataSet))
classMyClassTests(TestCase, PartitionerInvariantsFixture):
partitioner = Partitioner
Solution 2:
Subclass PartitionerInvariantsTests
:
classPartitionerInvariantsTests(unittest.TestCase):deftest_impl(self):
self.assertEqual(self.testDataSet,
chain.from_iterable(self.partitioner(self.testDataSet))
classPartitionerATests(PartitionerInvariantsTests):
for each Partitioner class you wish to test. Then test_impl
would be run for each Partitioner class, by virtue of inheritance.
Following up on Nathon's comment, you can prevent the base class from being tested by having it inherit only from object
:
import unittest
classTest(object):
deftest_impl(self):
print('Hi')
classTestA(Test,unittest.TestCase):
passclassTestB(Test,unittest.TestCase):
passif __name__ == '__main__':
unittest.sys.argv.insert(1,'--verbose')
unittest.main(argv = unittest.sys.argv)
Running test.py yields
test_impl (__main__.TestA) ... Hi
ok
test_impl (__main__.TestB) ... Hi
ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Post a Comment for "How To Run The Same Test-case For Different Classes?"