返回

如何忽略 Pytest 参数化测试中的某些参数?

python

如何让 Pytest 忽略参数化测试中的某些参数

简介

Pytest 的 pytest.mark.parametrize 装饰器非常适合为测试函数提供多个参数组合。然而,有时你可能需要跳过某些特定参数组合。本文将探讨使用 Pytest 忽略参数化测试中的某些参数的多种方法。

使用 indirect 参数

indirect=True 参数允许你在函数外部定义参数化值,而不是直接传递它们。这提供了更大的灵活性,让你可以动态地确定要跳过的参数组合。

import pytest

@pytest.fixture(params=[1, 2, 3], ids=["one", "two", "three"])
def foo(request):
    if request.param == 3:
        pytest.skip("Skipping 'three' for all bar values")
    return request.param

@pytest.mark.parametrize("bar", [4, 5, 6], indirect=True)
def test_something(foo, bar):
    # ...

在上面的示例中,foo 参数化值是通过 pytest.fixture 定义的。如果 foo 参数的值为 3,pytest.skip 会跳过所有与之对应的 bar 值。

使用 pytest-filter-markers 插件

pytest-filter-markers 是一个 Pytest 插件,它允许你使用标记来过滤测试用例。你可以使用它创建自定义标记来指示要跳过的参数组合。

pytest_plugins = ["pytest-filter-markers"]

@pytest.mark.parametrize("foo", [1, 2, 3])
@pytest.mark.parametrize("bar", [4, 5, 6])
@pytest.mark.skip_if(lambda foo, bar: foo == 3 and bar == 4)
def test_something(foo, bar):
    # ...

在上面的示例中,skip_if 标记用于跳过满足特定条件的参数组合,即 foo 为 3 且 bar 为 4。

使用 pytest.param

pytest.param 允许你指定要跳过的特定参数。

import pytest

@pytest.mark.parametrize("foo", [
    pytest.param(1, marks=pytest.mark.skip),
    2,
    3
])
@pytest.mark.parametrize("bar", [4, 5, 6])
def test_something(foo, bar):
    # ...

在上面的示例中,foo 参数的值为 1 时被标记为 skip,因此它将被跳过。

总结

Pytest 提供了多种方法来忽略参数化测试中的某些参数。根据你的具体需求,选择最合适的方法。indirect 参数提供了最灵活的方式,而 pytest-filter-markers 插件允许使用自定义标记。pytest.param 则允许指定要跳过的特定参数。

常见问题解答

1. 如何确定要跳过的参数组合?

  • 使用 indirect 参数:在函数外部动态确定。
  • 使用 pytest-filter-markers 插件:使用自定义标记指定。
  • 使用 pytest.param:指定要跳过的特定参数。

2. 我可以跳过整个参数化函数吗?

是的,你可以使用 pytest.mark.skip 装饰器跳过整个参数化函数。

3. 如何跳过单个参数值?

使用 pytest.param 指定要跳过的特定参数。

4. 我应该使用哪种方法?

根据你的具体需求选择最合适的方法:

  • indirect 参数:最大灵活性
  • pytest-filter-markers 插件:使用自定义标记
  • pytest.param:指定特定参数

5. 是否可以使用其他方法?

你可以使用其他方法,如自定义标记和动态条件,但这需要更多的自定义和代码维护。