[TIP] How do I run the same test on many different classes?

Michał Kwiatkowski constant.beta at gmail.com
Sun Dec 13 12:23:30 PST 2009

On Sun, Dec 13, 2009 at 9:07 PM, Matthew Wilson <matt at tplus1.com> wrote:
> Copy and paste my TestTask for each Task1, Task2, etc, like this:
> class TestTask1(TestTask):
>    def setUp(self):
>        self.t = Task1()
> class TestTask2(TestTask):
>     def setUp(self):
>        self.t = Task2()

Try this:

import types
import sys

# TestTask...

for task in [Task1, Task2]:
    name = "TestTask%s" % Task1.__name__
    def setUp(self):
        self.t = task
    setattr(sys.modules[__name__], name, types.ClassType(name,
(TestTask,), {'setUp': setUp}))

A bit crude, I know, but should save you from copy&paste.


More information about the testing-in-python mailing list