我正在使用 Jenkins、Python、Selenium2(webdriver) 和 Py.test 框架为 Web 测试创建测试用例。
到目前为止,我按以下结构组织测试:
每个Class都是Test Case,每个test_
方法都是Test Step强>。
当一切正常时,此设置效果很好,但是当一个步骤崩溃时,其余的“测试步骤”就会变得疯狂。在 teardown_class()
的帮助下,我能够将失败包含在类(测试用例)中,但是我正在研究如何改进它。
如果其中一个失败了,我需要以某种方式跳过(或 xfail)一个类中的其余 test_
方法,以便其余测试用例不会运行并标记为失败(因为那会是误报)
谢谢!
更新:我没有寻找或回答“这是不好的做法”,因为这样调用它是非常有争议的。 (每个测试类都是独立的——这就足够了)。
更新 2: 在每个测试方法中添加“if”条件不是一种选择 - 需要大量重复工作。我正在寻找的是(也许)有人知道如何使用 hooks到类方法。
最佳答案
我喜欢一般的“测试步骤”想法。我将其称为“增量”测试,恕我直言,它在功能测试场景中最有意义。
这是一个不依赖于 pytest 内部细节的实现(除了官方的钩子(Hook)扩展)。将此复制到您的 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 插件需要开发一种方法来定义组/类,以将其整体发送到一个测试从属设备,而不是当前通常将一个类的测试功能发送到不同从属设备的模式。
关于python - 如果一个失败了,如何跳过类里面的其余测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12411431/