python - 使用 pytest 时如何组织多个测试函数的步骤?

标签 python pytest

我有三个测试用例,其中两个测试用例对第三个测试用例有一定的依赖性。也就是说,测试 test_inner_1test_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/

相关文章:

python - 当您不知道确切位置时如何在 DF 中分割字符串的一部分?

自动创建数据框的 Python Loop

python - 类和方法的一个装饰器

python - wxPython -- 如何在某些事件(例如单击)中更新 BitmapButton 的边框样式

python - 如何在 PyCharm 中运行特定测试

python - 在Python中读取文件时如何更新计数器变量?

python - 如何修改特定测试的失败报告

python - 参数化 pytest - 也将参数传递给安装和拆卸

python - 在 xdist 创建的子进程中运行安装程序

python - 检查fixture是否被执行