python - 如果另一个失败,pytest 可以运行测试吗?

标签 python pytest

我有一种情况,我可以对整个对象进行非常快速的验证检查,如果该检查通过,则可以保证该对象是健康的。如果失败,我需要使用时间密集型检查来确定有问题的方面。

我希望是这样的: "@pytest.mark.dependency(depends=["test_a"])"除了不是只在成功时运行,它只会在失败时运行。

最佳答案

正如您正确指出的那样,pytest-dependency 无法处理您的情况,因为它会跳过失败测试而不是成功测试。但是,通过对该插件进行一些自定义,您可以获得所需的结果。示例:

# conftest.py

import pytest
from pytest_dependency import DependencyManager


def pytest_collection_modifyitems(session, config, items):
    modules = (item.getparent(pytest.Module) for item in items)
    marked_modules = {m for m in modules if m.get_closest_marker('depend_on_failures')}
    for module in marked_modules:
        module.dependencyManager = FailureDepManager()


class FailureDepManager(DependencyManager):

    def checkDepend(self, depends, item):
        for i in depends:
            if i in self.results:
                if self.results[i].isSuccess():
                    pytest.skip('%s depends on failures in %s' % (item.name, i))
                    break

FailureDepManagerpytest-dependencyDependencyManager 的自定义版本,仅当依赖成功时才会跳过依赖测试(结果 passedXPASS)。遗憾的是,此行为只能在每个模块的基础上触发,因为这是插件的当前限制(有关更多详细信息,请参阅 this question)。用法示例:

import pytest

pytestmark = pytest.mark.depend_on_failures


@pytest.mark.dependency()
@pytest.mark.xfail(reason='simulate failing test')
def test_foo():
    assert False


@pytest.mark.dependency(depends=['test_foo'])
def test_bar():
    assert True

由于模块级别的标记 depend_on_failures,如果 test_foo 失败,test_bar 现在将运行:

================================== test session starts ==================================
platform linux -- Python 3.7.0, pytest-4.0.1, py-1.7.0, pluggy-0.8.0
...
plugins: dependency-0.3.2
collected 2 items                                                                           

test_spam.py::test_foo xfail
test_spam.py::test_bar PASSED

========================== 1 passed, 1 xfailed in 0.08 seconds ==========================

关于python - 如果另一个失败,pytest 可以运行测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53545315/

相关文章:

python - 在 Python 中将句子更改为字典

Python - 许多方法,但差异很小

python - sklearn : Nearest Neightbour with String-Values and Custom Metric

python - 如何使用autouse=True 生成由fixture 提供的对象?

python - 参数化 pytest fixture 对象

python - 何时使用 TestClass 实例变量与 Pytest Fixtures

python - 这是在 DataFrame 中设置值的安全方法吗?为什么这有效?

Python表标题到字典

python - 如何在 Python 函数内正确地对代码进行单元测试

python - Pytest 编译时间太长