python - 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
?
解决方案
使用标记是不可能的mark.parametrize
,它总是被评估。但是,您可以将参数化移动到pytest_generate_tests
hookimpl。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()])
如果没有通过标记跳过,任何测试请求a
和b
参数现在都将被参数化。
推荐阅读
- spring-boot - :generateGitProperties git submodule Build FAILED in Heroku
- php - 使用 php yii migrate 命令时出现错误?
- c# - Ocelot RouteClaimsRequirement 无法识别我的声明并返回 403 Forbidden
- c# - 如何为选定的复选框值赋值
- apache - 从 :80 端口重定向
- laravel - laravel 7中的一对多关系
- android - React Native:从 createBottomTabNavigator 切换到 createMaterialBottomNavigator
- python - 在现有浏览器会话上使用 selenium
- arduino - Arduino 将浮点数转换为十六进制 IEEE754 单精度 32 位
- python - 使用writelines在Ipython的文本文件中写入数值参数行?