Skip to content Skip to sidebar Skip to footer

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.

class PartitionerInvariantsFixture(object):
    def setUp(self):
        self.testDataSet = range(100) # create test-data-set
        super(PartitionInvariantsFixture, self).setUp()

    def test_partitioner(self):
        TestCase.assertEqual(self.testDataSet, 
                     chain.from_iterable(self.partitioner(self.testDataSet))

class MyClassTests(TestCase, PartitionerInvariantsFixture):
    partitioner = Partitioner

Solution 2:

Subclass PartitionerInvariantsTests:

class PartitionerInvariantsTests(unittest.TestCase):
    def test_impl(self):
        self.assertEqual(self.testDataSet, 
                         chain.from_iterable(self.partitioner(self.testDataSet))

class PartitionerATests(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

class Test(object):
    def test_impl(self):
        print('Hi')

class TestA(Test,unittest.TestCase):
    pass

class TestB(Test,unittest.TestCase):
    pass

if __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?"