H'H*_*H'H 1 python pytest pytest-markers
我有多个测试适用于我的程序的不同版本。
例如 testA 仅适用于版本 2、3、4,不适用于 5 及更高版本。另一个测试适用于版本 4 及更高版本的测试。根据 pytest 文档,我可以创建一个类似于下面的标记:
# content of test_mymodule.py
import mymodule
minversion3 = pytest.mark.skipif(
myprogram.__versioninfo__ < 3, reason="at least version 3 is required"
)
@minversion3
def test_function():
...
Run Code Online (Sandbox Code Playgroud)
minversion3 标记要运行的测试,前提是程序至少有版本 3。我想对其进行参数化,以便我可以得到如下内容:
@minmaxversion(3.2, 6.1)
def test_function():
...
Run Code Online (Sandbox Code Playgroud)
因此该测试仅适用于版本最小为 3.2 且最大为 6.1 的程序。
您可以包装pytest.mark.skipif参数化装饰器来执行您想要的操作。以下代码提供了minversion(n)完全maxversion(n)符合您要求的装饰器;您可以将两者结合起来(请参阅 参考资料test_function_2)来设置版本范围,或者您当然可以minmaxversion按照相同的模式编写一个新的装饰:
import pytest
program_version = 6
def minversion(v):
return pytest.mark.skipif(
program_version < v, reason=f"Requires at least version {v}"
)
def maxversion(v):
return pytest.mark.skipif(
program_version > v, reason=f"Requires at most version {v}"
)
@maxversion(3)
def test_function_1():
assert True
@maxversion(5)
@minversion(3)
def test_function_2():
assert True
Run Code Online (Sandbox Code Playgroud)
使用program_version = 6,运行上面的代码会产生:
test_markers.py::test_function_1 SKIPPED (Requires at most version 3) [ 50%]
test_markers.py::test_function_2 SKIPPED (Requires at most version 5) [100%]
Run Code Online (Sandbox Code Playgroud)