Python : generating unittests on the fly

When creating python unit tests you need to create a method in a unittest class. The problem however is when you don’t know until the code is running what these tests will be. In my particular case I need to run a series of tests against a number of Solaris packages. But I won’t know what the packages will be in advance.

Thankfully python allows to to add a method to a class on the fly:

>>> class test:
...     pass
...
>>> def foo(self):
...     print "hello, world"
...
>>> dir(test)
['__doc__', '__module__']
>>> test.foo=foo
>>> dir(test)
['__doc__', '__module__', 'foo']
>>> bar=test()
>>> bar.foo()
hello, world
>>>

Here we initially create an empty class ‘test’ and a function ‘foo’. Then add the function ‘foo’ to the class ‘test’, so that when we create a ‘test’ object, we can call the ‘foo’ method in it.

We use the same trick to add a unittest test to a unittest class:


>>> import unittest
>>> class mytest(unittest.TestCase):
...     pass
...
>>> def test_testcase(self):
...     self.assertEqual("hello","hello")
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(mytest)
>>> unittest.TextTestRunner(verbosity=2).run(suite)

----------------------------------------------------------------------
Ran 0 tests in 0.015s

OK
<unittest.runner.TextTestResult run=0 errors=0 failures=0>
>>> mytest.test_testcase=test_testcase
>>> unittest.TextTestRunner(verbosity=2).run(suite)

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
<unittest.runner.TextTestResult run=0 errors=0 failures=0>
>>> suite = unittest.TestLoader().loadTestsFromTestCase(mytest)
>>> unittest.TextTestRunner(verbosity=2).run(suite)
test_testcase (__main__.mytest) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
<unittest.runner.TextTestResult run=1 errors=0 failures=0>
>>>

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top