【使用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 报告。这个方法对于调试和记录测试过程中的详细信息非常有用。

相关推荐
小小龙学IT10 分钟前
Go 语言 reflect 反射包深度解析:从 Type/Value 到三大定律与工业实践
前端·golang
小溪学编程19 分钟前
C语言篇:枚举类型
java·c语言·前端
xingpanvip22 分钟前
星盘接口开发文档:推算星座接口指南
前端·php
Da Da 泓25 分钟前
HTML浅浅入门
前端·html
এ慕ོ冬℘゜27 分钟前
es6基础
前端·javascript·es6
熊猫钓鱼>_>33 分钟前
从2D平铺到3D沉浸:我用HarmonyOS 7端侧AI做了一个全程数据不出设备的空间化私密相册
前端·人工智能·3d·华为·华为云·harmonyos·鸿蒙
孔令飞1 小时前
Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中
前端
溪语流沙2 小时前
【Web全栈进阶】PostgreSQL上手:Docker跑库 + 把早报站从SQLite迁过去
前端·docker·postgresql
IT_陈寒2 小时前
SpringBoot自动配置的坑:你以为的捷径可能是弯路
前端·人工智能·后端
paopaokaka_luck2 小时前
高校社团管理(AI辅助任务分配、协同过滤算法推荐、ECharts数据可视化、活动参与闭环、校园交流与反馈、器材借还管理)
java·前端·javascript·spring boot·数据分析·echarts