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

Skip parametrized tests generated by pytest_generate_tests at module level

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

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

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.testpython -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 所需的夹具。

知道如何实现吗?

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