Peter Hoffmann Peter Hoffmann - 2 years ago 219
Python Question

How to generate dynamic (parametrized) unit tests in python?

I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:

import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", name

if __name__ == '__main__':

The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?

Answer Source

i use something like this:

import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequense(unittest.TestCase):

def test_generator(a, b):
    def test(self):
    return test

if __name__ == '__main__':
    for t in l:
        test_name = 'test_%s' % t[0]
        test = test_generator(t[1], t[2])
        setattr(TestSequense, test_name, test)

The nose-parameterized package can be used to automate this process:

from nose_parameterized import parameterized

class TestSequence(unittest.TestCase):
        ["foo", "a", "a",],
        ["bar", "a", "b"],
        ["lee", "b", "b"],
    def test_sequence(self, name, a, b):

Which will generate the tests:

test_sequence_0_foo (__main__.TestSequence) ... ok
test_sequence_1_bar (__main__.TestSequence) ... FAIL
test_sequence_2_lee (__main__.TestSequence) ... ok

FAIL: test_sequence_1_bar (__main__.TestSequence)
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/nose_parameterized/", line 233, in <lambda>
    standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)
  File "", line 12, in test_sequence
AssertionError: 'a' != 'b'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download