在pytest中,我如何判断测试是否失败?(来自"请求")

Nac*_*cht 13 python testing selenium pytest

我正在使用Selenium和PYTEST来测试网站.我想在测试失败时(并且仅在失败时)截取页面的屏幕截图.

有没有办法可以做到这一点?对于这个(或者我找不到),文档很安静.我会认为它会是这样的

request.function.failed
Run Code Online (Sandbox Code Playgroud)

它会返回一个布尔值或其他东西.

这就是我想要做的:

@pytest.fixture()
def something(request):
    if request.function.failed:
        print "I failed"
Run Code Online (Sandbox Code Playgroud)

当然,这将被添加到终结器中.可以吗?使用pytest 2.3.3

谢谢.

hpk*_*k42 9

它可以完成,但不能直接完成.我刚刚在文档中添加了一个示例.默认情况下使这更容易,这可能是有意义的,即不需要使用conftest.py钩子.如果您同意,请提出问题.


Vla*_*lad 5

我必须在每个模块级别上执行类似的操作。在检查了现有解决方案之后,我对它们的复杂性感到惊讶。这是我想出的一种解决此问题的方法:

import pytest


@pytest.fixture(scope="module", autouse=True)
def failure_tracking_fixture(request):
    tests_failed_before_module = request.session.testsfailed
    yield
    tests_failed_during_module = request.session.testsfailed - tests_failed_before_module
Run Code Online (Sandbox Code Playgroud)

通过将灯具变成功能级别的灯具,可以对其进行调整以执行所需的操作。

希望这可以帮助!