You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest并行执行时仅为失败用例开启Playwright追踪

在Playwright+pytest+xdist并行场景下仅捕获失败用例的追踪

以下是经过验证的实现方案,核心思路是利用pytest钩子监听测试结果,结合Playwright的追踪API,仅在测试失败时保存追踪文件,同时通过唯一文件名避免并行执行时的文件冲突:

实现步骤

1. 同步测试场景(conftest.py核心逻辑)

import pytest
import os
from playwright.sync_api import BrowserContext

@pytest.fixture(scope="function")
def context(browser):
    # 启动追踪(开启截图、DOM快照、源码捕获),默认不保存数据
    context = browser.new_context()
    context.tracing.start(screenshots=True, snapshots=True, sources=True)
    yield context
    # 测试通过时,停止追踪且不生成文件
    context.tracing.stop()

def pytest_runtest_makereport(item, call):
    # 仅在测试执行阶段检查失败情况
    if call.when == "call" and call.excinfo is not None:
        # 获取当前测试用例的context实例
        context = item.funcargs.get("context")
        if not context:
            return
        
        # 生成唯一追踪文件名,避免并行进程间文件覆盖
        test_identifier = item.nodeid.replace("::", "_").replace("/", "_")
        trace_file_path = os.path.join("traces", f"trace_{test_identifier}_{os.getpid()}.zip")
        
        # 确保存储目录存在
        os.makedirs("traces", exist_ok=True)
        
        # 停止追踪并保存失败用例的追踪数据
        context.tracing.stop(path=trace_file_path)

2. 异步测试场景适配

如果你的测试基于异步Playwright API,只需调整异步逻辑:

import pytest
import os
from playwright.async_api import BrowserContext

@pytest.fixture(scope="function")
async def context(browser):
    context = await browser.new_context()
    await context.tracing.start(screenshots=True, snapshots=True, sources=True)
    yield context
    await context.tracing.stop()

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
async def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        context = item.funcargs.get("context")
        if not context:
            return
        
        test_identifier = item.nodeid.replace("::", "_").replace("/", "_")
        trace_file_path = os.path.join("traces", f"trace_{test_identifier}_{os.getpid()}.zip")
        os.makedirs("traces", exist_ok=True)
        
        await context.tracing.stop(path=trace_file_path)

关键细节说明

  • 精准触发:通过pytest_runtest_makereport钩子只捕获测试失败事件,完全跳过通过用例的追踪存储,从根源节省磁盘空间和处理时间。
  • 并行安全:用测试节点ID(item.nodeid)和进程ID(os.getpid())生成唯一文件名,避免xdist多worker进程间的文件覆盖问题。
  • 可配置优化:可调整tracing.start()的参数(比如关闭sources)进一步缩小追踪文件体积,平衡调试需求和空间占用。

额外建议

  • 可添加自动清理逻辑,比如在pytest_sessionfinish钩子中删除超过指定天数的追踪文件,避免磁盘空间持续累积。
  • 使用Playwright CLI查看追踪文件:playwright show-trace traces/xxx.zip

内容的提问来源于stack exchange,提问作者Srikar G S S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:32:46