【问题标题】:In pytest, how can I figure out if a test failed? (from "request")在 pytest 中,如何确定测试是否失败? (来自“请求”)
【发布时间】:2012-11-13 16:43:03
【问题描述】:

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

有没有办法可以做到这一点?文档对此很安静(或者我找不到)。我会假设它会像

request.function.failed

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

这就是我想做的:

@pytest.fixture()
def something(request):
    if request.function.failed:
        print "I failed"

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

谢谢。

【问题讨论】:

    标签: python testing selenium pytest


    【解决方案1】:

    可以做,但不能直接做。我只是added an example to the docs。默认情况下使这更容易可能是有意义的,即不需要使用 conftest.py 钩子。如果您同意,请file an issue

    【讨论】:

    【解决方案2】:

    我必须在每个模块级别上做类似的事情。在检查了现有的解决方案后,我对它们的复杂性感到有些惊讶。这是我想出的解决这个问题的方法:

    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
    

    可以通过将夹具设置为功能级来调整它以执行您想要的操作。

    希望这会有所帮助!

    【讨论】:

    • 这个解决方案不处理并行运行的测试,它的行为将是不可预测的。
    • 我没有太多关于如何在 pytest 中并行运行测试的上下文,但我怀疑有一种简单的方法可以以类似的方式在并行运行之间安全地共享状态。不过好点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2015-02-03
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    相关资源
    最近更新 更多