Python's unittest and dynamic creation of test cases [duplicate] Python's unittest and dynamic creation of test cases [duplicate] python python

Python's unittest and dynamic creation of test cases [duplicate]


In the following solution, the class Tests contains the helper method check and no test cases statically defined. Then, to dynamically add a test cases, I use setattr to define functions in the class. In the following example, I generate test cases test_<i>_<j> with i and j spanning [1,3] and [2,5] respectively, which use the helper method check with different values of i and j.

class Tests(unittest.TestCase):    def check(self, i, j):        self.assertNotEquals(0, i-j)for i in xrange(1, 4):    for j in xrange(2, 6):        def ch(i, j):            return lambda self: self.check(i, j)        setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))


For this you should use test generators in nose. All you need to do is yield a tuple, with the first being a function and the rest being the args. From the docs here is the example.

def test_evens():    for i in range(0, 5):        yield check_even, i, i*3def check_even(n, nn):    assert n % 2 == 0 or nn % 2 == 0