[TIP] adding custom tests to a unittest test run
Chris Jerdonek
chris.jerdonek at gmail.com
Tue May 15 21:25:28 PDT 2012
Hi, I was curious what others do in the following situation.
I often have the need to add extra tests to my unittest.main() test
runs. The tests I need to add are tests that depend on data obtained
at run-time, e.g. user-provided command-line options. I would like to
add these tests to unittest.main() in a way that doesn't depend on
"global state."
So far, the best I've come up with is the below. Is there a better
solution? What do others recommend?
[Also see: https://gist.github.com/2707352 ]
import unittest
def make_test_program_class(extra_tests):
"""
Return a unittest.TestProgram subclass that adds a list of custom tests.
Arguments:
extra_tests: an iterable of TestCase and TestSuite instances to add in
addition to the usual tests loaded when calling createTests().
cf. http://docs.python.org/py3k/library/unittest.html#unittest.TestSuite.addTests
"""
class MyTestProgram(unittest.TestProgram):
def createTests(self):
super(PystacheTestProgram, self).createTests()
self.test.addTests(extra_tests)
return MyTestProgram
extra_tests = create_extra_tests(data)
make_test_program_class(extra_tests)
test_program_class = make_test_program_class(extra_tests)
# In this constructor call you can include any of the arguments supported
# by unittest.main().
test_program_class() # runs tests.
Thanks,
--Chris
More information about the testing-in-python
mailing list