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