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

如何在pytest+Selenium中仅为失败测试用例收集浏览器控制台日志

仅为失败测试用例收集浏览器控制台日志的实现方案

问题背景

使用Python Selenium + Pytest做Web应用自动化测试时,希望仅针对失败的测试用例下载浏览器控制台日志并保存到文件,用于故障调试。当前conftest.py中的代码会为所有测试用例(无论成功/失败)收集日志,需要调整逻辑。

解决思路

核心是在fixture的销毁阶段(yield之后)判断当前测试类的执行状态:

  • 通过Pytest的request对象获取测试节点的执行结果
  • 仅当测试用例失败时,执行日志收集和保存逻辑
  • 借助pytest_runtest_makereport钩子函数,将测试执行结果附加到测试节点上,供fixture调用

修改后的完整代码

conftest.py

import pytest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import chromedriver_autoinstaller
from your_module import Constants  # 替换为你的Constants模块实际路径

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # 捕获测试执行结果,附加到测试节点对象
    outcome = yield
    rep = outcome.get_result()
    setattr(item, "rep_" + rep.when, rep)

@pytest.fixture(scope="class")
def setup(request, browser):
    options = webdriver.ChromeOptions()
    options.add_argument("--allow-running-insecure-content")
    options.add_argument("--ignore-certificate-errors")
    options.set_capability("acceptInsecureCerts", True)

    preferences = {
        "profile.default_content_settings.popups": 0,
        "download.default_directory": Constants.path,
        "directory_upgrade": True
    }
    options.add_experimental_option("prefs", preferences)
    
    capabilities = DesiredCapabilities.CHROME.copy()
    capabilities["goog:loggingPrefs"] = {"browser": "ALL"}
    
    driver = webdriver.Chrome(
        executable_path=chromedriver_autoinstaller.install(), 
        options=options, 
        desired_capabilities=capabilities
    )

    yield driver

    # 仅在测试失败时执行日志收集逻辑
    if request.node.rep_call.failed:
        log_path = "../Logs/browser_console.log"
        class_name = request.cls.__name__
        with open(log_path, "a", encoding="utf-8") as f:
            f.write(f"\n\n{'=' * 20} {class_name} 测试失败 {'=' * 20}\n")
            for entry in driver.get_log("browser"):
                f.write(f"[{entry['level']}] {entry['message']}\n")

    # 关闭浏览器
    driver.close()
    driver.quit()

关键说明

  • pytest_runtest_makereport钩子:捕获测试执行的全阶段结果,将测试用例执行阶段(call)的结果赋值给request.node.rep_call
  • 日志收集逻辑通过request.node.rep_call.failed判断触发,仅为失败用例生成日志
  • 日志以追加模式写入,每个失败用例的日志用类名做分隔标识,便于快速定位问题

内容的提问来源于stack exchange,提问作者AnilD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:10:03