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

前端 未结 4 1601
忘了有多久
忘了有多久 2021-02-03 21:50

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 a

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-03 22:16

    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):
        pass
    
    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:

    • Python unittest: Generate multiple tests programmatically?
    • How to generate dynamic (parametrized) unit tests in python?

提交回复
热议问题