How to parameterize unittests

Antoon Pardon antoon.pardon at rece.vub.ac.be
Fri Apr 15 08:48:11 EDT 2016


Op 15-04-16 om 13:43 schreef Antoon Pardon:
> Op 15-04-16 om 11:10 schreef Steven D'Aprano:
>> If you have code which is not parameterized, and you want to parameterize
>> it, you have to refactor. Unit tests are no different from anything else.
> I don't agree with that. If I have a piece of code that I want to parameterize,
> Often enough all I need to do is shift the code to the right. Prepend a def
> line and use a parameter with the same name as the more global variable I
> was using before. I don't need to change access to the variable in the code.

Some prelimary tests seems to suggest this idea might work here too.

Starting from this:

    class Test_AVLTree(unittest.TestCase):
 
        def test_empty_tree_is_false(self):
            instance = avltree()
            self.assertFalse(instance)

Changing it into this:

    def MakeAVLTest(avltree):
        class Test_AVLTree(unittest.TestCase):

            def test_empty_tree_is_false(self):
                instance = avltree()
                self.assertFalse(instance)

        return Test_AVLTree

    AVLTest = MakeAVLTest(avltree)
    MyTreeTest = MakeAVLTest(mytree)

Seems to work





More information about the Python-list mailing list