Python Class Generator

The following code is an example of a class generator which sets the name of the class dynamically as well.

This is useful because dynamically generated classes can be identified by meaningful names. It's also useful (as per the example) for generating named classes for unittest.TestCase.

This is an example of a test class generator:

   1 def test_class_generator(name, test_func):
   2   """ Generates a unittest.TestCase based test class """
   3 
   4   # The name "DummyClass" will be overridden
   5   class DummyClass(unittest.TestCase):
   6     def runTest(self, *args, **kwargs):
   7       # In this example just pass arguments through to a
   8       # contrived test function
   9       test_func(self, *args, **kwargs)
  10 
  11   # Rename the class based on the name
  12   DummyClass.__name__ = name
  13 
  14   return DummyClass

Using this sort of generator it's possible to create a bunch of unit tests and then run them:

   1 test_1 = test_class_generator("TestClass_One", some_test_func)
   2 test_2 = test_class_generator("TestClass_Two", some_other_test_func)
   3 if __name__ == '__main__':
   4   unittest.main()

And end up with informative output:

runTest (__main__.TestClass_One) ... ok
runTest (__main__.TestClass_Two) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.002s

OK

NB - the test function is very much contrived, and if just wrapping a test function the correct approach is to use unittest.FunctionTestCase.

BradsWiki: Programming Notes/PythonClassGenerator (last edited 2011-05-30 12:36:22 by BradleyDean)