gpt4 book ai didi

python - 在模块级别跳过由 pytest_generate_tests 生成的参数化测试

转载 作者:行者123 更新时间:2023-11-28 18:35:01 27 4
gpt4 key购买 nike

我希望能够从配置文件中参数化几个测试,但同时能够跳过这些测试,除非发出特定的命令选项。

我可以通过在测试模块的顶部添加以下代码来跳过测试:

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 中添加一个选项为了避免参数化,那么调用哟pytest失败是因为 conf test_that_require_conf 所需的 fixture 找不到。

关于如何实现这一点有什么想法吗?

最佳答案

我看到两个选项: (我假设你的选项存储为 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 ======================

关于python - 在模块级别跳过由 pytest_generate_tests 生成的参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33400071/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com