How to parameterize unittests

Serhiy Storchaka storchaka at gmail.com
Fri Apr 15 04:24:53 EDT 2016


On 14.04.16 18:05, Steven D'Aprano wrote:
> 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

Yes, this is common approach.

If there tests specific for original class or tests that there is no 
need to run for subclasses, you should define common tests in mixin 
class that is not test class itself:


class AbstractTest_AVLTree: # note, there is no TestCase!

     def test_common(self):
         ...


class Test_AVLTree(AbstractTest_AVLTree, unittest.TestCase):
      tree = avltree

      def test_base_class_specific(self):
          ...


class Test_MySubclassTree(AbstractTest_AVLTree, unittest.TestCase):
     tree = My_Subclass_Tree

     def test_sub_class_specific(self):
         ...

Complex tests can have a DAG of test classes.




More information about the Python-list mailing list