pytest.mark.parametrize是一个非常强大的功能,它允许你使用不同的参数多次运行同一个测试函数,这对于编写简洁且易于维护的测试代码特别有帮助。以下是使用pytest.mark.parametrize的10种典型用法,展示其灵活性和实用性:

1. 基本用法

最基本的形式是直接传递参数值列表。

  1. import pytest

  2. @pytest.mark.parametrize("x, y, expected", [(1, 2, 3), (4, 5, 9)])

  3. def test_add(x, y, expected):

  4. assert x + y == expected

2. 使用命名参数

为参数指定名字,增加可读性。

  1. @pytest.mark.parametrize("x, y, expected", [

  2. pytest.param(1, 2, 3, id='positive_numbers'),

  3. pytest.param(-1, -1, -2, id='negative_numbers'),

  4. ])

  5. def test_add_named(x, y, expected):

  6. assert x + y == expected

3. 嵌套参数

支持嵌套参数列表,适用于多维度测试。

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

  2. @pytest.mark.parametrize("y", [3, 4])

  3. def test_multiply(x, y):

  4. assert x * y in [3, 4, 6, 8]

4. 参数组合

使用pytest.param显式控制参数组合及标识。

  1. @pytest.mark.parametrize("a, b, expected", [

  2. pytest.param(1, 2, 3, id="integers"),

  3. pytest.param(1.5, 2.5, 4.0, id="floats"),

  4. ])

  5. def test_add_combinations(a, b, expected):

  6. assert a + b == expected

5. 参数类型转换

在传递给测试函数之前,自动转换参数类型。

  1. @pytest.mark.parametrize("x, y", [("1", "2"), ("3", "4")], ids=["str-str", "str-str"])

  2. def test_add_str_converted(x, y):

  3. x = int(x)

  4. y = int(y)

  5. assert x + y in [3, 7]

6. 异常测试

使用pytest.raises检查特定异常。

  1. @pytest.mark.parametrize("x, y", [(1, 'a')])

  2. def test_add_exception(x, y):

  3. with pytest.raises(TypeError):

  4. x + y

7. 参数化fixture

参数化fixture,使其在每次调用时使用不同的输入。

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

  2. def number(request):

  3. return request.param

  4. def test_number(number):

  5. assert number in [1, 2]

8. 大范围数据测试

使用外部数据源(如文件、数据库)动态生成参数。

  1. import pandas as pd

  2. data = pd.read_csv('data.csv')

  3. @pytest.mark.parametrize("x, y", data.values.tolist())

  4. def test_large_dataset(x, y):

  5. assert some_complex_calculation(x) == y

9. 自定义ID生成

通过idfn函数自定义测试ID的生成方式。

  1. def idfn(val):

  2. if isinstance(val, tuple):

  3. return f"{val[0]}-{val[1]}"

  4. return str(val)

  5. @pytest.mark.parametrize("x, y", [(1, 2), (3, 4)], ids=idfn)

  6. def test_custom_id(x, y):

  7. assert x + y in [3, 7]

10. 结合marks

为特定参数组合添加额外的标记。

  1. @pytest.mark.parametrize("x, y", [

  2. (1, 2, pytest.mark.smoke),

  3. (3, 4),

  4. ], indirect=True)

  5. def test_marks(x, y):

  6. assert x + y in [3, 7]

请注意,最后一个例子中的indirect=True通常用于参数化fixture,这里是为了演示而简化了实际用法。实际上,直接在参数组合上附加mark更常见于直接参数列表中,而不是像示例所示那样。

感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取   

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐