Pytest:如果一个失败,如何跳过课堂上的其他测试?

Ale*_*hko 26 python automated-tests pytest selenium-webdriver

我正在使用Jenkins,Python,Selenium2(webdriver)和Py.test框架为Web测试创建测试用例.

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

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

当一切正常时,这个设置很有效,但当一步崩溃时,其余的"测试步骤"变得疯狂.我可以借助于包含类(测试用例)中的失败teardown_class(),但是我正在研究如何改进它.

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

谢谢!

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

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

hpk*_*k42 27

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

这是一个不依赖于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)
Run Code Online (Sandbox Code Playgroud)

如果您现在有这样的"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
Run Code Online (Sandbox Code Playgroud)

然后运行它看起来像这样(使用-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 =================
Run Code Online (Sandbox Code Playgroud)

我在这里使用"xfail",因为跳过是错误的环境或缺少依赖,错误的解释器版本.

编辑:请注意,您的示例和我的示例都不会直接用于分布式测试.为此,pytest-xdist插件需要增加一种方法来定义要将整个销售发送到一个测试从站的组/类,而不是通常将类的测试功能发送到不同从站的当前模式.

  • @ hpk42:这很好知道;)这是pytest文档吗?:) (2认同)

gbo*_*tti 7


小智 5

pytest -x选项将在第一次失败后停止测试: pytest -vs -x test_sample.py