[파이썬] pytest 동적으로 테스트 추가하기

In this blog post, we will explore how to dynamically add tests to pytest in Python. Pytest is a popular testing framework that makes writing and running tests easier and more convenient.

Sometimes, you may need to generate tests dynamically at runtime based on certain conditions or data inputs. This can be useful when you have multiple test cases with varying inputs and you want to avoid writing repetitive test functions.

Using pytest-dynamic

To dynamically add tests in pytest, we can make use of a plugin called pytest-dynamic. This plugin provides the necessary functionality to generate tests dynamically.

To install pytest-dynamic, run the following command:

pip install pytest-dynamic

Once installed, we can start generating tests dynamically. Let’s look at an example.

import pytest

@pytest.mark.parametrize("input", [1, 2, 3])
def test_dynamic(input):
    assert input > 0

In the above example, we have a test function called test_dynamic that takes an input parameter. We use the @pytest.mark.parametrize decorator to specify multiple values for the input parameter.

Now, let’s say we want to generate additional test cases dynamically based on a condition. We can do this using the pytest_generate_tests hook provided by pytest-dynamic.

from typing import List
import pytest

def generate_dynamic_tests(metafunc):
    if "dynamic_input" in metafunc.fixturenames:
        inputs = [4, 5, 6]
        metafunc.parametrize("dynamic_input", inputs)

@pytest.mark.parametrize("input", [1, 2, 3])
def test_dynamic(input, dynamic_input):
    assert input > 0
    assert dynamic_input > 0

In the above example, we have added a new fixture called dynamic_input and included it as a parameter in the test_dynamic test function. Inside the generate_dynamic_tests function, we define the dynamic test inputs and use the metafunc.parametrize method to generate tests with these inputs.

To activate the dynamic test generation, we need to register the generate_dynamic_tests function using the pytest hook:

def pytest_generate_tests(metafunc):
    generate_dynamic_tests(metafunc)

Now, when we run pytest, it will dynamically generate additional test cases based on the dynamic_input fixture.

Conclusion

In this blog post, we explored how to dynamically generate tests in pytest using the pytest-dynamic plugin. This can be a powerful technique when you need to generate tests based on conditions or data inputs. With pytest-dynamic, you can save time and avoid repetitive test function creation.

I hope you found this blog post helpful in understanding dynamic test generation in pytest. Happy testing!