如果一个失败了,如何跳过课堂上的其余测试?

新手上路,请多包涵

我正在使用 Jenkins、Python、Selenium2(webdriver) 和 Py.test 框架为网络测试创建测试用例。

到目前为止,我正在按照以下结构组织我的测试:

每个 都是 测试用例,每个 test_ 方法 是一个 测试步骤

当一切正常时,此设置效果很好,但是当一个步骤崩溃时,其余的“测试步骤”就会变得疯狂。在 teardown_class() 的帮助下,我能够将故障包含在类(测试用例)中,但是我正在研究如何改进它。

我需要的是以某种方式跳过(或 xfail)其余的 test_ 一个类中的方法,如果其中一个失败,这样其余的测试用例就不会运行并标记为失败(因为将是误报)

谢谢!

更新: 我没有在寻找或回答“这是不好的做法”,因为这样称呼它是非常有争议的。 (每个测试类都是独立的 - 这应该足够了)。

更新 2: 在每个测试方法中放置“if”条件不是一个选项 - 是很多重复的工作。我正在寻找的是(也许)有人知道如何使用类方法的 挂钩

原文由 Alex Okrushko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 425
2 个回答

我喜欢一般的“测试步骤”想法。我将其称为“增量”测试,恕我直言,它在功能测试场景中最有意义。

这是一个不依赖于 pytest 内部细节的实现(官方挂钩扩展除外)。将此复制到您的 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):
    previousfailed = getattr(item.parent, "_previousfailed", None)
    if previousfailed is not None:
        pytest.xfail("previous test failed (%s)" % previousfailed.name)

如果你现在有一个像这样的“test_step.py”:

 import pytest

@pytest.mark.incremental
class TestUserHandling:
    def test_login(self):
        pass
    def test_modification(self):
        assert 0
    def test_deletion(self):
        pass

然后运行它看起来像这样(使用 -rx 报告 xfail 原因):

 (1)hpk@t2:~/p/pytest/doc/en/example/teststep$ py.test -rx
============================= test session starts ==============================
platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev17
plugins: xdist, bugzilla, cache, oejskit, cli, pep8, cov, timeout
collected 3 items

test_step.py .Fx

=================================== FAILURES ===================================
______________________ TestUserHandling.test_modification ______________________

self = <test_step.TestUserHandling instance at 0x1e0d9e0>

    def test_modification(self):
>       assert 0
E       assert 0

test_step.py:8: AssertionError
=========================== short test summary info ============================
XFAIL test_step.py::TestUserHandling::()::test_deletion
  reason: previous test failed (test_modification)
================ 1 failed, 1 passed, 1 xfailed in 0.02 seconds =================

我在这里使用“xfail”是因为跳过是针对错误的环境或缺少依赖项、错误的解释器版本。

编辑:请注意,您的示例和我的示例都不能直接用于分布式测试。为此,pytest-xdist 插件需要开发一种方法来定义组/类,以将其全部发送给一个测试从机,而不是当前通常将一个类的测试函数发送到不同从机的模式。

原文由 hpk42 发布,翻译遵循 CC BY-SA 4.0 许可协议

原文由 gbonetti 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题