繁体   English   中英

如何检测pytest测试用例何时失败?

[英]How to detect when pytest test case failed?

我正在使用pytest和selenium来自动化网站。 我想在测试用例失败时才拍摄一些屏幕截图。 我已经普遍使用了TestNG,而使用TestNG,它使用了ITestListner。 我们在pytest中有类似的东西吗?

我试图使用teardown_method()来实现这一点但是当测试用例失败时,这个方法没有被执行。

import sys

from unittestzero import Assert
class TestPY:
    def setup_method(self, method):
        print("in setup method")
        print("executing " + method.__name__)

    def teardown_method(self, method):
        print(".....teardown")
        if sys.exc_info()[0]:
            test_method_name = method
            print test_method_name

    def test_failtest(self):
        Assert.fail("failed test")

teardown_method()仅在没有失败时执行

根据你在stackoverflow上的帖子 ,我可以分享我的想法,我希望它会有所帮助:wink:你要做的是处理可以通过assert关键字或任何断言引发的标准AssertionError异常在unittest.TestCase中实现的方法,或者任何引发自定义异常的自定义断言方法。 有3种方法可以做到这一点:

  1. 使用try-except-finally构造。 一些基本的例子:

     try: Assert.fail("failed test") except AssertionError: get_screenshot() raise 
  2. 或者使用with语句作为上下文管理器:

     class TestHandler: def __enter__(self): # maybe some set up is expected before assertion method call pass def __exit__(self, exc_type, exc_val, exc_tb): # catch whether exception was raised if isinstance(exc_val, AssertionError): get_screenshot() with TestHandler(): Assert.fail("failed test") 

    在这里,您可以深入了解如何使用它

  3. 在我看来,最后一个是最优雅的方法。 使用装饰器 有了这个装饰器,你可以装饰任何测试方法:

     def decorator_screenshot(func): def wrapper(*args, **kwargs): try: func(*args, **kwargs) except AssertionError: get_screenshot() raise return wrapper @decorator_screenshot def test_something(): Assert.fail("failed test") 

经过一番努力,最终这对我有用。

在conftest.py中:

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    setattr(item, "rep_" + rep.when, rep)
    return rep

并且,在您的代码中,在一个夹具中(例如,在用于测试的拆卸夹具中)使用它,如下所示:

def tear_down(request):
    method_name = request.node.name
    if request.node.rep_call.failed:
        print('test {} failed :('.format(method_name))
        # do more stuff like take a selenium screenshot

请注意,“request”是pytest在测试环境中提供的一个“funcarg”。 您不必自己定义它。

来源: pytest示例线程(不)使这更容易

这就是我们这样做的方法,注意__multicall__的文档非常少,我记得阅读__multicall__将被弃用,请用一点盐来实验,并根据示例尝试用' item,call '替换__multicall__

def pytest_runtest_makereport(__multicall__):
    report = __multicall__.execute()

    if report.when == 'call':
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):

           try:
              screenshot = APP_DRIVER.take_screen_shot(format="base64")


           except Exception as e:
              LOG.debug("Error saving screenshot !!")
              LOG.debug(e)

    return report
def pytest_runtest_makereport(item, call):
    if call.when == 'call':
        if call.excinfo is not None:
            # if excinfor is not None, indicate that this test item is failed test case
            error("Test Case: {}.{} Failed.".format(item.location[0], item.location[2]))
            error("Error: \n{}".format(call.excinfo))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM