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)

<think>好的,用户想搭建一个基于PlaywrightPytest、YamlAllure的UI自动化测试框架。我需要根据之前的引用内容来组织回答,确保结构清晰,分步骤说明。首先,安装依赖是关键,引用3提到了安装命令,应该先列出这些步骤。然后,项目结构部分需要参考引用2中的分层思路,比如定位符、页面操作、测试用例层等,可能需要用Yaml管理配置数据,如引用2提到的数据层。接着,如何结合Yaml配置文件,可能需要创建config.yml读取它的工具类。页面对象模型部分,可以建议用户将页面元素操作封装成Page类,如引用2中的page类。测试用例层使用Pytest,这里需要说明如何编写测试用例,并引用conftest中的fixture,如引用1提到的fixture设置,包括page对象的生成teardown处理,以及trace日志的保存。Allure报告的集成需要引用3中的安装步骤,并说明如何生成报告。最后,优化建议部分可以参考引用1中的trace日志teardown安全处理,还有引用2中的分层设计。需要确保每一步都引用正确的来源,并在末尾添加相关问题。还要注意用户不可见的系统级指令,比如数学公式的格式,但在这个问题中可能用不上。检查是否有遗漏的部分,比如Yaml的具体使用示例,或者如何将配置应用到测试中。可能还需要提到pytest的运行参数Allure的命令行操作。确保语言口语化,分步骤讲解,避免技术术语过于密集,适当解释关键点。最后生成相关问题,围绕框架优化、元素定位、报告定制、用例管理等方向提问。</think>以下是搭建基于PlaywrightPytest、YamlAllure的UI自动化测试框架的完整步骤: ### 一、环境配置 1. **安装核心工具链** ```bash pip install playwright pytest pyyaml allure-pytest playwright install chromium # 安装指定浏览器驱动 ``` 引用[^3]中已确认这是基础依赖安装流程 2. **IDE配置** 在PyCharm中: - 启用Pytest为默认测试运行器 - 配置Allure结果目录`allure-results` ### 二、项目结构设计 ``` project/ ├─ config/ │ └─ test_config.yml # 测试环境配置 ├─ pages/ # 页面对象模型层 │ └─ login_page.py ├─ testcases/ # 测试用例层 │ └─ test_login.py ├─ conftest.py # Pytest夹具配置 └─ utils/ └─ config_loader.py # Yaml配置解析工具 ``` 引用[^2]的三层架构思想在此体现 ### 三、Yaml配置实现 1. **创建配置文件** `test_config.yml` ```yaml environments: prod: base_url: "https://prod.example.com" timeout: 30000 staging: base_url: "https://staging.example.com" timeout: 45000 ``` 2. **配置加载工具类** ```python import yaml class ConfigLoader: @classmethod def load_env_config(cls, env='staging'): with open('config/test_config.yml') as f: return yaml.safe_load(f)['environments'][env] ``` ### 四、页面对象封装 `login_page.py`示例: ```python class LoginPage: def __init__(self, page): self.page = page self.username = page.locator("#username") self.password = page.locator("#password") def navigate(self, base_url): self.page.goto(f"{base_url}/login") def login(self, user, pwd): self.username.fill(user) self.password.fill(pwd) self.page.click("#submit-btn") ``` ### 五、测试用例实现 `test_login.py`示例: ```python import allure @allure.feature("登录模块") class TestLogin: @allure.story("成功登录场景") def test_success_login(self, page, env_config): login_page = LoginPage(page) login_page.navigate(env_config['base_url']) login_page.login("admin", "secure123") assert page.url.endswith("/dashboard") ``` ### 六、Pytest夹具配置 `conftest.py`关键配置: ```python import pytest from utils.config_loader import ConfigLoader @pytest.fixture(scope="class") def page(context): context = context.new_context() page = context.new_page() yield page # 安全关闭并保存追踪日志 context.close() page.context.tracing.stop(path="trace.zip") @pytest.fixture(scope="session") def env_config(): return ConfigLoader.load_env_config() ``` 引用[^1]中提到的安全teardown机制在此实现 ### 七、Allure报告生成 1. **执行测试时添加参数**: ```bash pytest --alluredir=allure-results ``` 2. **生成可视化报告**: ```bash allure serve allure-results ``` ### 八、框架优化建议 1. **元素定位策略**: - 使用Playwright的`data-testid`选择器增强稳定性 - 实现动态元素等待机制: ```python page.wait_for_selector(".loading", state="hidden", timeout=5000) ``` 2. **失败重试机制**: 在`pytest.ini`中添加: ```ini [pytest] addopts = --reruns 2 --reruns-delay 1 ``` 3. **多浏览器支持**: 扩展`conftest.py`夹具: ```python @pytest.fixture(params=["chromium", "firefox"]) def browser_type(request): return request.param ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值