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

后端 未结 25 2668
面向向阳花
面向向阳花 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:29

    As of Python 3.4 subtests have been introduced to unittest for this purpose. See the documentation for details. TestCase.subTest is a context manager which allows one to isolate asserts in a test so that a failure will be reported with parameter information but does not stop the test execution. Here's the example from the documentation:

    class NumbersTest(unittest.TestCase):
    
    def test_even(self):
        """
        Test that numbers between 0 and 5 are all even.
        """
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)
    

    The output of a test run would be:

    ======================================================================
    FAIL: test_even (__main__.NumbersTest) (i=1)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "subtests.py", line 32, in test_even
        self.assertEqual(i % 2, 0)
    AssertionError: 1 != 0
    
    ======================================================================
    FAIL: test_even (__main__.NumbersTest) (i=3)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "subtests.py", line 32, in test_even
        self.assertEqual(i % 2, 0)
    AssertionError: 1 != 0
    
    ======================================================================
    FAIL: test_even (__main__.NumbersTest) (i=5)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "subtests.py", line 32, in test_even
        self.assertEqual(i % 2, 0)
    AssertionError: 1 != 0
    

    This is also part of unittest2, so it is available for earlier versions of Python.

提交回复
热议问题