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

相关推荐
yuanyxh1 小时前
Mac 软件推荐
前端·javascript·程序员
万少2 小时前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
某人辛木2 小时前
Web自动化测试
前端·python·pycharm·pytest
Kagol2 小时前
Superpowers GSD gstack AgentSkills深度测评
前端·人工智能
excel3 小时前
JavaScript 字符串与模板字面量:从表象到本质理解
前端
京东云开发者4 小时前
当AI成为导演-如何用AI创作动漫短剧
前端
李白的天不白4 小时前
使用 SmartAdmin 进行前后端开发
java·前端
乘风gg4 小时前
🤡PUA AI Coding 工具 的 10 条终极语录
前端·ai编程·claude
学Linux的语莫4 小时前
Vue 3 入门教程
前端·javascript·vue.js
怕浪猫5 小时前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome