【问题标题】:How to skip a test in pytest based on command-line option / fixture如何根据命令行选项/夹具跳过pytest中的测试
【发布时间】:2019-10-20 09:19:47
【问题描述】:

我有一个 pytest 套件,其中包含多个测试 Web 服务的文件。测试可以在不同的类型上运行,将它们称为 A 型和 B 型,用户可以指定应该为哪种类型运行测试。虽然大多数测试适用于 A 型和 B 型,但有些不适用于 B 型。当使用 --type=B 标志运行 pytest 时,我需要能够跳过某些测试。

这是我的 conftest.py 文件,我在其中根据类型设置了夹具

import pytest

#Enable type argument
def pytest_addoption(parser):
    parser.addoption("--type", action="store", default="A", help = "Specify a content type, allowed values: A, B")

@pytest.fixture(scope="session", autouse=True)
def type(request):
    if request.node.get_closest_marker('skipb') and request.config.getoption('--type') == 'B': 
        pytest.skip('This test is not valid for type B so it was skipped')
        print("Is type B")
    return request.config.getoption("--type")

然后,在我的测试函数被跳过之前,我添加如下标记:

class TestService1(object):

    @pytest.mark.skipb()
    def test_status(self, getResponse):
        assert_that(getResponse.ok, "HTTP Request OK").is_true()
        printResponse(getResponse)

class TestService2(object):

    @pytest.mark.skipb()
    def test_status(self, getResponse):
        assert_that(getResponse.ok, "HTTP Request OK").is_true()
        printResponse(getResponse)

我能够运行 pytest 并且没有收到任何解释器错误,但它不会跳过我的测试。这是我用来运行测试的命令:

pytest -s --type=B

更新:我需要澄清一下,我的测试分布在多个类中。更新了我的代码示例以使其更加清晰。

【问题讨论】:

  • if request.node.get_closest_marker('mymark') and request.config.getoption('--type') == 'B': pytest.skip('cannot run') in type 夹具。
  • 仍然不会跳过测试,我更新了我上面的conftest并分享了测试功能
  • 从夹具中删除 scope="session"。它应该为每个测试执行一次,而不是每个测试会话一次。
  • 这并不完全有效,但确实让我找到了自己的解决方案。我是 pytest 的新手,所以如果你能帮助我更好地理解这一点,那就太好了。基本上我的项目有多个文件,每个文件都是它自己的测试休息服务的类。命令行选项适用于所有这些类,这就是为什么我的类型夹具有 scope=session 似乎是必要的。我在功能级别添加了一个名为“skip_by_type”的新夹具,但仍然无法正确找到制造商。我将这个夹具更改为具有 scope="class" 并且可以通过这种方式跳过一个完整的课程。
  • 我刚刚在我的机器上尝试了你的代码,它正在工作。如果它不适用于您的,请将相关代码更新为minimal reproducible example

标签: pytest fixtures


【解决方案1】:

我们使用非常相似的东西来运行“扩展参数集”。为此,您可以使用以下代码:

在 conftest.py 中:

def pytest_addoption(parser):
    parser.addoption(
        "--extended-parameter-set",
        action="store_true",
        default=False,
        help="Run an extended set of parameters.")

def pytest_collection_modifyitems(config, items):
    extended_parameter_set = config.getoption("--extended-parameter-set")

    skip_extended_parameters = pytest.mark.skip(
        reason="This parameter combination is part of the extended parameter "
        "set.")

    for item in items:
        if (not extended_parameter_set
                and "extended_parameter_set" in item.keywords):
            item.add_marker(skip_extended_parameters)

现在,您可以使用“extended_pa​​rameter_set”简单地标记完整测试或仅标记测试的某些参数化,并且只有在使用 --extended-parameter-set 选项调用 pytest 时才会运行它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-25
    • 2019-03-22
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多