[Python-ideas] Minor suggestion for unittest

Collin Winter collinw at gmail.com
Sun Apr 29 06:44:29 CEST 2007

On 4/28/07, Terry Jones <terry at jon.es> wrote:
> | It sounds like what you're looking for is FunctionTestCase
> | (http://docs.python.org/lib/unittest-contents.html). Using that, your
> | loop above becomes something like
> |
> | for testFunc, expectedResult in MyTestData:
> |          def tester():
> |              self.assertEqual(testFunc(), expectedResult)
> |          suite.addTest(FunctionTestCase(tester))
> I had read about FunctionTestCase but it didn't seem to be what I was
> looking for - though it's the closest. FunctionTestCase is intended to
> allow people to easily bring a set of pre-existing tests under the umbrella
> of unittest. It overrides setUp and tearDown, and doesn't result in the
> test being a first-class test like those you get when you write tests for
> unittest from scratch (using TestCase directly, or something you write
> based on it).

I'm not sure why you think the tests produced FunctionTestCase are
somehow second-class citizens: unittest treats all test objects
equally, so long as they conform to the expected API. If the objection
to using FunctionTestCase is that the test names don't conform to the
same pattern as the statically-defined tests, that's easily solved
with a subclass.

> I want to dynamically (i.e. at run time) add functions that are treated
> equally with those that are added statically in python code. That could be
> really simple (and I can hack around it to achieve it), but the current
> method unittest uses to set its self._testMethodName prevents me from doing
> this in a nice way (because TestCase.__init__ immediately does a hasattr to
> look for the named method, and fails if it's absent).

If FunctionTestCase is undesirable, you might look at creating your
own TestSuite subclass. The API is pretty simple, and that would give
you all the control in the world over pulling in tests dynamically.

Hope that helps,
Collin Winter

More information about the Python-ideas mailing list