pytest有哪些参数化方式

在 pytest 中,参数化测试是一种常见的测试方法,可以通过多种方式实现。以下是几种主要的参数化方式:

1. @pytest.mark.parametrize 装饰器

这是最常用的参数化方式。你可以使用 @pytest.mark.parametrize 装饰器为测试函数提供多组参数。

import pytest

@pytest.mark.parametrize("input, expected", [

(1, 2),

(2, 4),

(3, 6),

])

def test_multiply_by_two(input, expected):

assert input * 2 == expected

在这个例子中,test_multiply_by_two 函数会被执行三次,每次使用不同的 input 和 expected 值。

2. pytest.fixture 参数化

你可以使用 pytest.fixture 来参数化 fixture,然后在测试函数中使用这些 fixture。

import pytest

 

@pytest.fixture(params=[1, 2, 3])

def input_value(request):

return request.param

 

def test_multiply_by_two(input_value):

assert input_value * 2 == input_value * 2

在这个例子中,input_value fixture 会返回不同的值(1, 2, 3),test_multiply_by_two 函数会针对每个值执行一次。

3. pytest_generate_tests 钩子

你可以使用 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):

assert input * 2 == input * 2

在这个例子中,pytest_generate_tests 钩子函数会为 input 参数生成不同的值(1, 2, 3),test_multiply_by_two 函数会针对每个值执行一次。

4. 使用外部数据源

你可以从外部数据源(如 CSV 文件、数据库、JSON 文件等)读取数据,并将其用于参数化测试。

import pytest

import csv

 

def load_test_data():

with open('test_data.csv') as f:

return list(csv.reader(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 结合使用,以实现更复杂的参数化场景。

import pytest

 

@pytest.fixture

def multiplier():

return 2

 

@pytest.mark.parametrize("input, expected", [

(1, 2),

(2, 4),

(3, 6),

])

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 装饰器,以实现多维参数化。

import pytest

 

@pytest.mark.parametrize("x", [1, 2])

@pytest.mark.parametrize("y", [10, 20])

def test_multiply(x, y):

assert x * y == x * y

在这个例子中,test_multiply 函数会执行四次,分别对应 x 和 y 的所有组合。

总结

pytest 提供了多种参数化方式,可以根据具体的测试需求选择合适的方式。@pytest.mark.parametrize 是最常用的方式,而 pytest.fixture 和 pytest_generate_tests 则提供了更灵活的选项。通过组合这些方法,你可以实现复杂的参数化测试场景。

 

posted @ 2025-03-18 20:21  sealis  阅读(87)  评论(0)    收藏  举报