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

相关推荐
卡兰芙的微笑23 分钟前
get_property --Cmakelist之中
前端·数据库·编辑器
覆水难收呀25 分钟前
三、(JS)JS中常见的表单事件
开发语言·前端·javascript
猿来如此呀33 分钟前
运行npm install 时,卡在sill idealTree buildDeps没有反应
前端·npm·node.js
hw_happy38 分钟前
解决 npm ERR! node-sass 和 gyp ERR! node-gyp 报错问题
前端·npm·sass
FHKHH43 分钟前
计算机网络第二章:作业 1: Web 服务器
服务器·前端·计算机网络
视觉小鸟1 小时前
【JVM安装MinIO】
前端·jvm·chrome
二川bro2 小时前
【已解决】Uncaught RangeError: Maximum depth reached
前端
qq22951165023 小时前
python毕业设计基于django+vue医院社区医疗挂号预约综合管理系统7918h-pycharm-flask
前端·vue.js·express
八了个戒3 小时前
Koa (下一代web框架) 【Node.js进阶】
前端·node.js
Sca_杰3 小时前
vue2使用npm引入依赖(例如axios),报错Module parse failed: Unexpected token解决方案
前端·javascript·vue