How do you generate dynamic (parameterized) unit tests in python?

后端 未结 25 2456
面向向阳花
面向向阳花 2020-11-22 07:09

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

import unittest

l = [[\"foo\", \"a\", \"a\         


        
25条回答
  •  别那么骄傲
    2020-11-22 07:26

    Using unittest (since 3.4)

    Since Python 3.4, the standard library unittest package has the subTest context manager.

    See the documentation:

    • 26.4.7. Distinguishing test iterations using subtests
    • subTest

    Example:

    from unittest import TestCase
    
    param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]
    
    class TestDemonstrateSubtest(TestCase):
        def test_works_as_expected(self):
            for p1, p2 in param_list:
                with self.subTest():
                    self.assertEqual(p1, p2)
    

    You can also specify a custom message and parameter values to subTest():

    with self.subTest(msg="Checking if p1 equals p2", p1=p1, p2=p2):
    

    Using nose

    The nose testing framework supports this.

    Example (the code below is the entire contents of the file containing the test):

    param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]
    
    def test_generator():
        for params in param_list:
            yield check_em, params[0], params[1]
    
    def check_em(a, b):
        assert a == b
    

    The output of the nosetests command:

    > nosetests -v
    testgen.test_generator('a', 'a') ... ok
    testgen.test_generator('a', 'b') ... FAIL
    testgen.test_generator('b', 'b') ... ok
    
    ======================================================================
    FAIL: testgen.test_generator('a', 'b')
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py", line 203, in runTest
        self.test(*self.arg)
      File "testgen.py", line 7, in check_em
        assert a == b
    AssertionError
    
    ----------------------------------------------------------------------
    Ran 3 tests in 0.006s
    
    FAILED (failures=1)
    

提交回复
热议问题