picardo picardo - 1 year ago 76
Python Question

How do I run multiple Python test cases in a loop?

I am new to Python and trying to do something I do often in Ruby. Namely, iterating over a set of indices, using them as argument to function and comparing its results with an array of fixture outputs.

So I wrote it up like I normally do in Ruby, but this resulted in just one test case.

def test_output(self):
for i in range(1,11):

I'm trying to get the test for every item in the range. How can I do that?

Answer Source

Using unittest you can show the difference between two sequences all in one test case.

seq1 = range(1, 11)
seq2 = (fn(j) for j in seq1)
assertSequenceEqual(seq1, seq2)

If that's not flexible enough, using unittest, it is possible to generate multiple tests, but it's a bit tricky.

def fn(i): ...
output = ...

class TestSequence(unittest.TestCase):

if __name__ == '__main__':
    for i in range(1,11):
        testmethodname = 'test_fn_{0}'.format(i)
        testmethod = lambda self: self.assertEqual(fn(i), output[i])
        setattr(TestSequence, testmethodname, testmethod)

Nose makes the above easier through test generators.

import nose.tools

def test_fn():
    for i in range(1, 11):
        yield nose.tools.assert_equals, output[i], fn(i)

Similar questions: