How to parameterize unittests

Chris Angelico rosuav at gmail.com
Fri Apr 15 03:42:16 EDT 2016


On Fri, Apr 15, 2016 at 4:52 PM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
> Op 14-04-16 om 17:05 schreef Steven D'Aprano:
>> On Fri, 15 Apr 2016 12:08 am, Antoon Pardon wrote:
>>
>>> I have a unittest for my avltree module.
>>>
>>> Now I want this unittest to also run on a subclass of avltree.
>>> How can I organise this, so that I can largely reuse the
>>> original TestCase?
>>
>> class Test_AVLTree(unittest.TestCase):
>>     tree = avltree
>>
>>     def test_empty_tree_is_false(self):
>>         instance = self.tree()
>>         self.assertFalse(instance)
>>
>>
>> class Test_MySubclassTree(Test_AVLTree):
>>     tree = My_Subclass_Tree
>
> I see, that's going to be a lot of cut & pastes.
> Thanks.

Not really; the first class has all the tests, and the second one is
literally just those two lines. It overrides 'tree' (accessed inside
methods as 'self.tree'), and since all the tests are written to
instantiate self.tree, they are effectively parameterized.

ChrisA



More information about the Python-list mailing list