我希望能够从配置文件中对一些测试进行参数化,但同时能够跳过这些测试,除非发出特定的命令选项。
我可以通过在测试模块的顶部添加以下代码来跳过测试:
from json import loads
import pytest
@pytest.mark.skipif(pytest.config.getvalue("-k") != "smoke",
reason="Smoke tests must be explicitly launched through -k smoke option")
除非添加选项py.test
,否则在发出python -m pytest
或-k smoke
时不会执行测试。
我也可以通过以下方式从配置文件创建参数化测试:
def pytest_generate_tests(metafunc):
with open('tests/test_smoke.json','r') as fp:
confs = loads(fp.read().decode("utf-8-sig"))
for arg in metafunc.funcargnames:
if arg == "conf":
metafunc.parametrize("conf",confs)
参数化测试的例子是:
def test_that_require_conf(conf):
assert not conf
问题在于两件事情都不能很好地协同工作。使用pytest_generate_tests
时,不会跳过测试。
如果我在pytest_generate_tests
中添加一个选项以避免参数化,那么调用yo pytest
会失败,因为
无法找到conf
所需的test_that_require_conf
装置。
有关如何实现这一点的想法吗?
答案 0 :(得分:1)
我看到两个选择:
(我猜你的选项存储为smoke
)
1)在第一个选项中,您需要更改pytest_generate_tests
。测试将作为一个
def pytest_generate_tests(metafunc):
for arg in metafunc.funcargnames:
if arg == "conf":
if metafunc.config.option.keyword != 'smoke':
confs = pytest.skip("Smoke tests must....")
else:
with open('tests/test_smoke.json', 'r') as fp:
confs = loads(fp.read().decode("utf-8-sig"))
metafunc.parametrize("conf", confs)
输出将是:
collected 0 items / 1 skipped
==================== 1 skipped in 0.01 seconds ========================
2)第二个选项将单独跳过任何测试
def test_that_require_conf(request, conf):
if request.config.option.smoke != 'smoke':
pytest.skip('Smoke tests must....")
assert conf
输出
collected 3 items
tests/test_2.py::test_that_require_conf[1] SKIPPED
tests/test_2.py::test_that_require_conf[2] SKIPPED
tests/test_2.py::test_that_require_conf[3] SKIPPED
====================== 3 skipped in 0.02 seconds ======================