How to parameterize unittests

Ben Finney ben+python at benfinney.id.au
Fri Apr 15 04:35:04 EDT 2016


Antoon Pardon <antoon.pardon at rece.vub.ac.be> writes:

> But the tests, at this moment, are not written to instantiate
> self.tree but to call avltree directly.

That is exactly what the ‘TestCase.setUp’ method is for: to have the
test case class specify how its test cases will customise themselves.

    class AVLTree_TestCase(unittest.TestCase):
        tree = AVLTree

        def setUp(self):
            super().setUp()
            self.test_instance = self.tree()

        def test_empty_tree_is_false(self):
            self.assertFalse(self.test_instance)


    class LoremIpsumAVLTree_TestCase(AVLTree_TestCase):
        tree = LoremIpsumAVLTree


    class DolorSitAmetAVLTree_TestCase(AVLTree_TestCase):
        tree = DolorSitAmetAVLTree


By not overriding ‘setUp’, the same routine will be called in the
subclass's instance also.

> So I have to rewrite these tests.

Yes, you'll need to consider inheritance and how the ‘unittest’ API
supports it.

-- 
 \       “Faith, n. Belief without evidence in what is told by one who |
  `\   speaks without knowledge, of things without parallel.” —Ambrose |
_o__)                           Bierce, _The Devil's Dictionary_, 1906 |
Ben Finney




More information about the Python-list mailing list