pytest有哪些参数化方式
在 pytest 中,参数化测试是一种常见的测试方法,可以通过多种方式实现。以下是几种主要的参数化方式:
1. @pytest.mark.parametrize 装饰器
这是最常用的参数化方式。你可以使用 @pytest.mark.parametrize 装饰器为测试函数提供多组参数。
@pytest.mark.parametrize("input, expected", [
def test_multiply_by_two(input, expected):
在这个例子中,test_multiply_by_two 函数会被执行三次,每次使用不同的 input 和 expected 值。
你可以使用 pytest.fixture 来参数化 fixture,然后在测试函数中使用这些 fixture。
@pytest.fixture(params=[1, 2, 3])
def test_multiply_by_two(input_value):
assert input_value * 2 == input_value * 2
在这个例子中,input_value fixture 会返回不同的值(1, 2, 3),test_multiply_by_two 函数会针对每个值执行一次。
你可以使用 pytest_generate_tests 钩子函数来动态生成参数化测试。
def pytest_generate_tests(metafunc):
if "input" in metafunc.fixturenames:
metafunc.parametrize("input", [1, 2, 3])
def test_multiply_by_two(input):
在这个例子中,pytest_generate_tests 钩子函数会为 input 参数生成不同的值(1, 2, 3),test_multiply_by_two 函数会针对每个值执行一次。
你可以从外部数据源(如 CSV 文件、数据库、JSON 文件等)读取数据,并将其用于参数化测试。
with open('test_data.csv') as f:
@pytest.mark.parametrize("input, expected", load_test_data())
def test_multiply_by_two(input, expected):
assert int(input) * 2 == int(expected)
在这个例子中,load_test_data 函数从 CSV 文件中读取数据,并将其用于参数化测试。
5. 使用 pytest.mark.parametrize 与 pytest.fixture 结合
你可以将 @pytest.mark.parametrize 和 pytest.fixture 结合使用,以实现更复杂的参数化场景。
@pytest.mark.parametrize("input, expected", [
def test_multiply(input, expected, multiplier):
assert input * multiplier == expected
在这个例子中,multiplier fixture 返回一个固定的值(2),而 input 和 expected 通过 @pytest.mark.parametrize 参数化。
6. 使用 pytest.mark.parametrize 与 pytest.mark.parametrize 嵌套
你可以嵌套使用多个 @pytest.mark.parametrize 装饰器,以实现多维参数化。
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
在这个例子中,test_multiply 函数会执行四次,分别对应 x 和 y 的所有组合。
pytest 提供了多种参数化方式,可以根据具体的测试需求选择合适的方式。@pytest.mark.parametrize 是最常用的方式,而 pytest.fixture 和 pytest_generate_tests 则提供了更灵活的选项。通过组合这些方法,你可以实现复杂的参数化测试场景。

浙公网安备 33010602011771号