如何使用pytest和限定符测试运行多个测试

2024-09-28 18:14:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pytest测试文件的目录,有一个需要测试的限定符测试,如果它失败了,那么停止执行任何进一步的测试,但是如果它通过了,那么执行所有测试,无论是否通过。 我有一个具有以下结构的目录:

tests/
test_qualifier.py
test_one.py
test_two.py
...

现在,当我使用pytest test/ -x运行测试时,它运行所有的测试,假设它在第一次失败时停止。 我希望pytest运行test_qualifier.py,如果失败,则停止进一步执行,但如果通过,则无论任何测试是否失败,都不要停止


Tags: 文件pytest目录pytesttests结构one
2条回答

您可以使用pytest插件。将其他测试标记为“取决于测试”限定符

plugin page开始:

This pytest plugin allows you to declare dependencies between pytest tests, where dependent tests will not run if the tests they depend on did not succeed.

Of course, tests should be self contained whenever possible, but that doesn't mean this doesn't have good uses.

This can be useful for when the failing of a test means that another test cannot possibly succeed either, especially with slower tests. This isn't a dependency in the sense of test A sets up stuff for test B, but more in the sense of if test A failed there's no reason to bother with test B either.

代码示例:

BUILD_PATH = 'build'

def test_build_exists():
    assert os.path.exists(BUILD_PATH)

@pytest.depends(on=['test_build_exists'])
def test_build_version():
    result = subprocess.run([BUILD_PATH, ' version', stdout=subprocess.PIPE)
    assert result.returncode == 0
    assert '1.2.3' in result.stdout

您可以通过使用pytest挂钩编写自己的pytest插件来实现这一点

一般来说,这不是一个很有意义的特性,所以我认为pytest不支持它

但是,您可能可以自己展开它:在test_qualifier中,创建一个autousefixture,如果其中一个测试失败,它checks the result of the test并调用类似pytest.exit的东西。如果您想要正确的报告,也许可以检查一下 exitfirst的工作方式,我不知道直接调用pytest.exit是否会生成正常的故障报告,因此这可能不太好

除了pytest.exit之外,您还可以设置一个内部标志,a test running hook将使用该标志自动跳过所有后续测试

您可能还想编写一个连接到pytest_collection_modifyitemsconftest插件,以确保您的资格测试始终首先运行,并且不会受到direntry迭代或字母顺序的影响

相关问题 更多 >