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

相关推荐
web小白成长日记1 天前
企业级 Vue3 + Element Plus 主题定制架构:从“能用”到“好用”的进阶之路
前端·架构
APIshop1 天前
Python 爬虫获取 item_get_web —— 淘宝商品 SKU、详情图、券后价全流程解析
前端·爬虫·python
风送雨1 天前
FastMCP 2.0 服务端开发教学文档(下)
服务器·前端·网络·人工智能·python·ai
XTTX1101 天前
Vue3+Cesium教程(36)--动态设置降雨效果
前端·javascript·vue.js
LYFlied1 天前
WebGPU与浏览器边缘智能:开启去中心化AI新纪元
前端·人工智能·大模型·去中心化·区块链
Setsuna_F_Seiei1 天前
2025 年度总结:人生重要阶段的一年
前端·程序员·年终总结
model20051 天前
alibaba linux3 系统盘网站迁移数据盘
java·服务器·前端
han_1 天前
从一道前端面试题,谈 JS 对象存储特点和运算符执行顺序
前端·javascript·面试
aPurpleBerry1 天前
React 01 目录结构、tsx 语法
前端·react.js
jayaccc1 天前
微前端架构实战全解析
前端·架构