【使用pytest记录日志并生成 HTML 报告】


在本教程中,我们将展示如何使用 pytest 记录日志信息并生成包含当前日期和时间的日志文件和 HTML 报告。我们将以 WiFi 和蓝牙功能测试为例。

步骤 1:安装必要的包

首先,确保已安装必要的 Python 包:

bash 复制代码
pip install pytest pytest-html
步骤 2:创建测试脚本

创建一个名为 test_BTWifi.py 的测试脚本,其中包含 WiFi 和蓝牙的测试用例。

python 复制代码
import subprocess
import time
import logging
import pytest

def run_adb_command(command):
    """运行 ADB 命令并返回输出。"""
    try:
        logging.info(f"执行命令: {command}")
        result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding='utf-8', errors='ignore')
        output = result.stdout.strip() if result.stdout else None
        logging.info(f"命令输出: {output}")
        return output
    except Exception as e:
        logging.error(f"执行命令 '{command}' 时出错: {e}")
        return None

def enable_wifi():
    """启用设备上的 WiFi。"""
    command = "adb shell svc wifi enable"
    run_adb_command(command)
    time.sleep(5)
    output = run_adb_command("adb shell dumpsys wifi")
    return "enabled" in output if output else False

def disable_wifi():
    """禁用设备上的 WiFi。"""
    command = "adb shell svc wifi disable"
    run_adb_command(command)
    time.sleep(3)
    output = run_adb_command("adb shell dumpsys wifi")
    return "disabled" in output if output else False

def start_wifi_scan():
    """启动 WiFi 扫描。"""
    command = "adb shell cmd wifi start-scan"
    run_adb_command(command)

def get_scan_results():
    """获取 WiFi 扫描结果。"""
    command = "adb shell cmd wifi list-scan-results"
    return run_adb_command(command)

def check_wifi_status():
    """检查 WiFi 状态。"""
    command = "adb shell dumpsys wifi"
    output = run_adb_command(command)
    if output:
        if "enabled" in output:
            return "enabled"
        elif "disabled" in output:
            return "disabled"
    return "unknown"

@pytest.fixture(scope="module", autouse=True)
def setup_and_teardown():
    """前置条件和后置清理"""
    logging.info("前置条件: 确保 WiFi 处于关闭状态。")
    status = check_wifi_status()
    if status == "enabled":
        if not disable_wifi():
            pytest.exit("前置条件失败: 无法禁用 WiFi。终止测试。")
    yield
    disable_wifi()

def test_enable_wifi():
    """用例 1: 启用 WiFi"""
    assert enable_wifi(), "用例 1: 启用 WiFi 失败"

def test_start_wifi_scan():
    """用例 2: 启动 WiFi 扫描并检查扫描结果"""
    start_wifi_scan()
    time.sleep(15)
    output = get_scan_results()
    assert output, "用例 2: WiFi 扫描结果为空"

def test_disable_wifi():
    """用例 3: 检查 WiFi 状态并禁用 WiFi。"""
    status = check_wifi_status()
    if status == "enabled":
        assert disable_wifi(), "用例 3: 禁用 WiFi 失败"
步骤 3:创建日志配置文件

创建一个名为 conftest.py 的文件来配置日志记录。

python 复制代码
import pytest
import logging
from datetime import datetime

@pytest.hookimpl(tryfirst=True)
def pytest_addoption(parser):
    parser.addoption(
        "--custom-log-level", action="store", default="INFO", help="Set the logging level"
    )

@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
    log_level = config.getoption("--custom-log-level").upper()
    current_time = datetime.now().strftime("%Y%m%d%H%M%S")
    log_filename = f'test_log_{current_time}.log'
    logging.basicConfig(
        level=log_level,
        format='%(asctime)s - %(levelname)s - %(message)s',
        filename=log_filename,
        filemode='w'
    )
    config._log_filename = log_filename

@pytest.fixture(autouse=True)
def log_capture(request, caplog):
    caplog.set_level(logging.INFO)
    yield
    log_filename = request.config._log_filename
    with open(log_filename, "a") as log_file:
        log_file.write(caplog.text)
步骤 4:运行测试并生成 HTML 报告

在命令行中运行以下命令以执行测试并生成 HTML 报告,同时设置自定义日志级别:

bash 复制代码
pytest .\test_BTWifi.py --html=wifi_test_report.html --custom-log-level=INFO

这样就会生成一个包含当前日期和时间的日志文件(例如 test_log_20240725153045.log)以及一个 HTML 报告(wifi_test_report.html),其中包含执行测试时捕获的所有日志信息。

总结

通过上述步骤,我们成功地使用 pytest 记录了日志信息,并生成了带有当前日期和时间的日志文件和 HTML 报告。这个方法对于调试和记录测试过程中的详细信息非常有用。

相关推荐
OpenTiny社区3 分钟前
【博文精读】Chrome CSS 2025年回顾
前端·css
菩提小狗23 分钟前
第3天:基础入门-抓包&封包&协议&APP&小程序&PC应用&WEB应用|小迪安全笔记|网络安全|
前端·安全·小程序
雨飞飞雨26 分钟前
深度学习响应式系统
前端·vue.js·前端框架
大布布将军29 分钟前
⚡后端安全基石:JWT 原理与身份验证实战
前端·javascript·学习·程序人生·安全·node.js·aigc
ybc465231 分钟前
React、Next安全漏洞问题修复和自测
前端·安全·next.js
huali32 分钟前
社区划分:让AI理解你的代码重构意图
前端·javascript·vue.js
掘金安东尼33 分钟前
⏰前端周刊第446期(2025年12月22日–12月27日)
前端
不老刘40 分钟前
前端面试八股文:单线程的JavaScript是如何实现异步的
前端·javascript·面试
J总裁的小芒果43 分钟前
后端返回参数不一致 前端手动处理key
前端·vue.js·elementui