我有三个测试用例,其中两个测试用例对第三个测试用例有一定的依赖性。也就是说,测试 test_inner_1
和 test_inner_2
彼此独立,但如果 test_outher
失败,它们的执行就没有意义。如果测试 test_outher
通过,则应运行它们;如果 test_outher
失败,则应跳过它们。
pytest
手册 https://pytest.org/latest/example/simple.html
提供了一些如何实现增量测试的简单示例
测试步骤。我正在尝试将这种方法应用于我的情况
实现类似的东西:
conftest.py的内容:
import pytest
def pytest_runtest_makereport(item, call):
if "incremental" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item
def pytest_runtest_setup(item):
if "incremental" in item.keywords:
previousfailed = getattr(item.parent, "_previousfailed", None)
if previousfailed is not None:
pytest.xfail("previous test failed (%s)" % previousfailed.name)
test_example.py的内容:
import pytest
@pytest.mark.incremental
class TestUserHandling:
def test_outher(self):
assert 0
class TestInner:
def test_inner_1(self):
assert 0
def test_inner_2(self):
pass
不幸的是,我得到了输出
==================== 2 次失败,1 次在 0.03 秒内通过 ================ ====
预计会得到输出
==================== 1 次失败,2 次在 0.03 秒内失败 ================= ===
如何更正 conftest.py
以获得所需的行为?
最佳答案
有一个 pytest 插件,名为 pytest-dependency在这种情况下,这就是您想要做的。
您的代码可能如下所示:
import pytest
import pytest_dependency
@pytest.mark.dependency()
def test_outher():
assert 0
@pytest.mark.dependency(depends=["test_outher"])
def test_inner_1():
assert 0
@pytest.mark.dependency(depends=["test_outher"])
def test_inner_2():
pass
输出是:
=================================== FAILURES ===================================
_________________________________ test_outher __________________________________
@pytest.mark.dependency()
def test_outher():
> assert 0
E assert 0
test_example.py:6: AssertionError
===================== 1 failed, 2 skipped in 0.02 seconds ======================
您当然可以使用类,但对于本例来说,这不是必需的。如果您需要类示例,请告诉我。
关于python - 使用 pytest 时如何组织多个测试函数的步骤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309691/