首页 > 解决方案 > Pytest跳过参数化

问题描述

pytest.mark.skip与python 一起使用时,尽管函数(显然)pytest.mark.parametrize评估parametrize参数:skip

import pytest

def get_params():
    # Do super heavy and slow logic to get parameters
    print("Params function called!")
    return (1, 2)

@pytest.mark.skip()
@pytest.mark.parametrize("a, b", [get_params()])
def test_foo(a, b):
    pass

在那个例子中,我总是跳过test_foo测试函数,我调用了另一个函数get_params来获取测试函数的参数。
get_params是非常复杂的,如果我知道我将跳过测试,我不想调用它。如果我运行测试,我可以看到打印“Params function called!” 意思是get_params调用的函数。

我知道这是因为 python 评估顺序而发生的,并且get_params在跳过之前调用的函数开始处理它的事情。
因此,我尝试使用生成器:

import pytest

def get_params():
    # Do super heavy and slow logic to get parameters
    print("Params function called!")
    return (1, 2)

def get_generator():
    yield get_params()

@pytest.mark.skip()
@pytest.mark.parametrize("a, b", get_generator())
def test_foo(a, b):
    pass

但结果是一样的。
如果提供了函数,我怎样才能使get_params函数不被调用skip

标签: pythonpytest

解决方案


使用标记是不可能的mark.parametrize,它总是被评估。但是,您可以将参数化移动到pytest_generate_testshookimpl。conftest.py在您的测试或项目根目录中创建一个包含以下内容的文件:

def get_params():
    ...


def pytest_generate_tests(metafunc):
    # check if skip marker applied
    if metafunc.definition.get_closest_marker('skip') is not None:
        return
    # check if test requests a and b args
    if all(name in metafunc.definition.fixturenames for name in ('a', 'b')):
        metafunc.parametrize('a,b', [get_params()])

如果没有通过标记跳过,任何测试请求ab参数现在都将被参数化。


推荐阅读