Menu Close

How to generate dynamic (parameterized) unit tests in Python?

Sometimes, we want to generate dynamic (parameterized) unit tests in Python.

In this article, we’ll look at how to generate dynamic (parameterized) unit tests in Python.

How to generate dynamic (parameterized) unit tests in Python?

To generate dynamic (parameterized) unit tests in Python, we can use the parameterized module.

To install it, we run

pip install parameterized

Then we can use it by writing

from parameterized import parameterized

class TestSequence(unittest.TestCase):
    @parameterized.expand([
        ["foo", "a", "a",],
        ["bar", "a", "b"],
        ["lee", "b", "b"],
    ])
    def test_sequence(self, name, a, b):
        self.assertEqual(a, b)

to call parameterized.exapnd decorator method with a list of lists of values to create our test with.

We use it to modify the test_sequence to create the parameterized tests.

The first value in each list is appended to the test name.

The rest of the arguments are used in our tests.

Conclusion

To generate dynamic (parameterized) unit tests in Python, we can use the parameterized module.

Posted in Python, Python Answers