1

I have a code structure where we have a lot of sub classes from a common base class.
I want in an automated fashion test each subclass without having a separate class definition inheriting from TestCase for each subclass.

with a classs like

class MyBaseClass:
    ...

I can get a list of all subclasses that inherits from MyBaseClass with

import all_module_that_includes_subclasses

list_of_all_subclasses = MyBaseClass.__subclasses__()

But how do I connect to this list of scubclasses to avoid manually createing TestCases for each subclass like:

class TestSubClass1(TestCase):
   def test_method_1(self):
      ...
   ...

class TestSubClass2(TestCase):
   def test_method_1(self):
      ...
   ...

etc. 

I thought of setting up an instance of all classes in setUp() method and looping through them in each def test_method_#(). This will somewhat work, I think, but it will break as soon as one single class fails. I want to be able to run through all classes and get a full report what class failed and in what tests.

Thankful for help :)

1 Answer 1

1

You can create those test cases dynamically using the load_tests protocol. For this you simply define a top-level function called load_tests which should return a TestSuite.

import unittest


class MyBaseClass:
    pass


class Foo(MyBaseClass):
    pass


class Bar(MyBaseClass):
    pass


class TestBases:
    # Wrapped into other class, so it won't be discovered by unittest.
    class TestCase(unittest.TestCase):
        subclass: MyBaseClass

        def test(self):
            self.assertIsInstance(self.subclass(), MyBaseClass)


def load_tests(loader, tests, pattern):
    for cls in MyBaseClass.__subclasses__():
        test_cls = type(f'Test{cls.__name__}', (TestBases.TestCase,), dict(subclass=cls))
        tests.addTests(loader.loadTestsFromTestCase(test_cls))
    return tests


if __name__ == '__main__':
    unittest.main()

This runs the two dynamically generated test cases TestFoo and TestBar:

$ python /tmp/test.py -v
test (__main__.TestFoo) ... ok
test (__main__.TestBar) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @a_guest, This helped me a lot and I got it working. Some key things here that you wrote is actually the type( ... ) command which dynamically creates the TestCases with correct subclass attached. Ref The way that you are using a wrapper and a base test class is a nice way as well. Thank you a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.