playwright+allure+pytest失败添加截图和视频到报告

这篇博客探讨了在使用pytest自动化测试时,如何在测试失败的情况下通过Playwright库捕获截图和录制视频,并将它们整合到Allure测试报告中。博主遇到了在尝试多种方法后无法成功实现的问题,最终在conftest.py文件中通过pytest_runtest_makereport方法解决了这个问题。当测试失败时,该方法能够确保截图和视频正确地添加到报告中,同时避免了因文件占用导致的空文件问题。

学自动化测试的时候,使用百度的方法不知道为啥都不生效。后面在conftest.py里面整了个蠢方法。

使用conftest.py的pytest_runtest_makereport方法,在用例失败的时候截图和把录屏放到报告里面。

关掉页面的时候,录屏文件可能还会被占用,导致加上去一个空文件,所以要等没被占用的时候再添加

import os
import sys
import time
import allure
import pytest
from allure_commons.types import AttachmentType

# 目录位置可以自己定义,我用的是父目录的父目录

dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def is_file_locked(filepath) -> bool:
    """
    检测文件是否被占用
    """
    locked = False
    try:
        with open(filepath, 'rb') as fp:
            pass
    except:
        locked = True
    finally:
        if fp and not fp.closed:
            os.close(fp.fileno())
    return locked


def wait_for_file_unlock(filepath, timeout=5):
    for i in range(timeout * 2):
        if is_file_locked(filepath):
            break
        else:
            time.sleep(0.5)


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):

    # 在测试用例执行完成之后执行该方法
    outcome = yield
    report = outcome.get_result()
    if report.when == "call" and report.failed:
        # 如果测试用例失败,则获取页面截图
        page = item.funcargs.get("page")  # 假设你在测试用例中将页面对象命名为"page"
        if page:
            if item.config.option.screenshot != 'off':
                # 截图
                screenshot = page.screenshot(path=f'{dir_path}/report/{item.name}_失败截图.png')
                # 将截图添加到 Allure 报告中
                allure.attach(screenshot, name=item.name + "_失败截图", attachment_type=AttachmentType.PNG)
            if item.config.option.video != 'off':
                # 获取录像路径
                path = page.video.path()
                # 关闭page
                page.close()
                # 等待录像文件没被占用
                wait_for_file_unlock(path)
                # 将录像添加到 Allure 报告中
                allure.attach.file(path, name=item.name + "_失败录像", attachment_type=AttachmentType.WEBM)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值