WEB自动化-Allure报告-使用钩子函数 进行失败截图

发布时间 2023-08-10 22:24:04作者: 琉璃星眸

Allure报告中 支持使用钩子函数进行失败截图

 

 

 

使用pytest_runtest_makereport钩子函数实现allure报告添加用例失败截图(函数名固定的)
 
Hook函数又称为钩子函数,它的作用可以理解成钩住自己喜欢的东西(在window中,喜欢的东西可理解为消息),然后对自己喜欢的东西单独做处理
 
1、先创建conftest文件,
  1)定义浏览器的driver,
  2)写@pytest.hookimpl(hookwrapper=True);判断返回的result中有错误,就进行截图。

它的作用和装饰器@pytest.mark.hookwrapper是一样的,当pytest调用钩子函数时,它首先执行钩子函数装饰器并传递与常规钩子函数相同的参数(个人理解是当用该装饰器@pytest.hookimpl(hookwrapper=True)装饰时,他会把其他常规钩子函数的参数都传递给当前被装饰的钩子函数)

在钩子函数装饰器的yield处,Pytest将执行下一个钩子函数实现,并以Result对象的形式,封装结果或异常信息的实例的形式将其结果返回到yield处。因此,yield处通常本身不会抛出异常(除非存在错误)

总结如下:
@pytest.hookimpl(hookwrapper=True)装饰的钩子函数,有以下两个作用:
(1)可以获取到测试用例不同执行阶段的结果(setup,call,teardown)
(2)可以获取钩子方法的调用结果(yield返回一个result对象)和调用结果的测试报告(返回一个report对象)
————————————————
版权声明:本文为CSDN博主「Bug 挖掘机」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011035397/article/details/109546814

import allure
import pytest
from selenium import webdriver


@pytest.fixture()
def browser():
    global driver
    driver = webdriver.Chrome()

    yield driver

    driver.quit()


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport():
    # 获取到用例执行之后的result对象
    out = yield
    """
        setup:
        call: 测试执行中
        teardown:
        wasxfail: 标记失败的用例
    """
    report = out.get_result()

    # 判断call阶段(测试用例的执行阶段),如果你的用例被标记为失败,那么就完成截图
    if report.when == "call":
        xfail = hasattr(report, "wasxfail")
        # report.skipped: 用例跳过
        # report.failed:用例失败
        if (report.skipped and xfail) or (report.failed and not xfail):
            with allure.step("添加失败截图... ..."):
                allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)

 

2、创建测试用例文件

 3、创建main文件,进行执行

import os

import pytest


def run():
    pytest.main(['--alluredir', './result', '--clean-alluredir'])
    os.system('allure generate ./result/ -o ./report/ --clean')


if __name__ == '__main__':
    run()

4、查看报告