当前位置: 首页 > news >正文

【使用 Pytest 记录日志文件并确保测试用例正常执行】

1. 更新测试脚本

首先,确保你的测试脚本 wifi_test.py 配置了日志记录,并包含所有测试用例:

import subprocess
import time
import logging
import pytest
import sys# 配置日志记录
logging.basicConfig(filename='wifi_test.log', level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logging.getLogger().addHandler(console_handler)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 Nonelogging.info(f"命令输出: {output}")return outputexcept Exception as e:logging.error(f"执行命令 '{command}' 时出错: {e}")return Nonedef enable_wifi():"""启用设备上的 WiFi。"""command = "adb shell svc wifi enable"run_adb_command(command)time.sleep(5)  # 等待 5 秒以确保 WiFi 已启用output = run_adb_command("adb shell dumpsys wifi")if output and "enabled" in output:logging.info("WiFi 启用成功。")return Trueelse:logging.error("无法启用 WiFi。")return Falsedef disable_wifi():"""禁用设备上的 WiFi。"""command = "adb shell svc wifi disable"run_adb_command(command)time.sleep(3)  # 等待 3 秒以确保 WiFi 已禁用output = run_adb_command("adb shell dumpsys wifi")if output and "disabled" in output:logging.info("WiFi 禁用成功。")return Trueelse:logging.error("无法禁用 WiFi。")return Falsedef 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"output = run_adb_command(command)return outputdef 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()logging.info(f"当前 WiFi 状态: {status}")if status == "enabled":logging.info("WiFi 已启用,尝试禁用 WiFi...")if not disable_wifi():logging.error("前置条件失败: 无法禁用 WiFi。终止测试。")pytest.exit("前置条件失败: 无法禁用 WiFi。终止测试。")elif status == "disabled":logging.info("WiFi 已处于关闭状态。")else:logging.error("无法确定 WiFi 状态。终止测试。")pytest.exit("无法确定 WiFi 状态。终止测试。")yieldlogging.info("测试结束,执行后置清理。")disable_wifi()def test_enable_wifi():"""用例 1: 启用 WiFi"""logging.info("用例 1: 启用 WiFi。")assert enable_wifi(), "用例 1: 启用 WiFi 失败"def test_start_wifi_scan():"""用例 2: 启动 WiFi 扫描并检查扫描结果"""logging.info("用例 2: 启动 WiFi 扫描并检查扫描结果。")start_wifi_scan()logging.info("等待 15 秒以获取扫描结果...")time.sleep(15)  # 等待扫描完成output = get_scan_results()assert output, "用例 2: WiFi 扫描结果为空"logging.info("用例 2: 扫描结果:")logging.info(output)def test_disable_wifi():"""用例 3: 检查 WiFi 状态。如果 WiFi 已启用,尝试在 3 秒内禁用 WiFi。"""logging.info("用例 3: 检查 WiFi 状态。如果 WiFi 已启用,尝试在 3 秒内禁用 WiFi。")status = check_wifi_status()logging.info(f"当前 WiFi 状态: {status}")if status == "enabled":logging.info("WiFi 已启用,开始尝试禁用 WiFi...")assert disable_wifi(), "用例 3: 禁用 WiFi 失败"else:logging.info("WiFi 当前未启用,不需要禁用。")if __name__ == '__main__':pytest.main()

2. 创建 pytest 配置文件

在你的项目目录下创建一个 pytest.ini 文件,并添加以下内容:

[pytest]
log_cli = true
log_cli_level = INFO
log_file = wifi_test.log
log_file_level = INFO

3. 运行测试

在你的项目目录下,运行以下命令:

pytest wifi_test.py

4. 其他可能问题的排查

  • 检查日志文件路径和权限:确保 wifi_test.log 文件路径正确,并且你有写入权限。
  • 检查 pytest 版本:确保你使用的是支持这些配置的 pytest 版本。可以通过运行 pytest --version 检查版本。
  • 检查日志配置:确认 logging.basicConfigpytest.ini 中的日志配置没有冲突。

如果按照这些步骤配置了日志记录和测试用例,应该能正确生成日志文件,并解决用例重复执行的问题。如果还有问题,可以进一步检查 pytest 的配置和命令是否正确。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • python实现盲反卷积算法
  • 2024最新网络安全自学路线,内容涵盖3-5年技能提升
  • Ubuntu 22.04.4 LTS (linux) GoAccess 分析 Nginx 日志
  • 如何学习自动驾驶仿真与算法优化 前后端开发
  • 深入理解Prompt工程
  • GO集成方式、Java文字识别接口集成方法
  • Odoo 17 仪表盘开发指南:打造高效的数据可视化中心
  • CSS前端面试题——怎么用CSS实现一个宽高自适应的正方形?
  • .NET Core中如何集成RabbitMQ
  • C++初阶学习——探索STL奥秘——标准库中的string类
  • PyCharm2024 专业版激活设置中文
  • 论文总结:A Survey on Evaluation of Large Language Models-鲁棒性相关内容
  • 爬虫基本原理入门
  • Preact:轻量级替代React的选择
  • 【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 亲子游戏(200分) - 三语言AC题解(Python/Java/Cpp)
  • 【每日笔记】【Go学习笔记】2019-01-10 codis proxy处理流程
  • Android框架之Volley
  • Angular 响应式表单之下拉框
  • Docker 笔记(2):Dockerfile
  • isset在php5.6-和php7.0+的一些差异
  • leetcode讲解--894. All Possible Full Binary Trees
  • Linux编程学习笔记 | Linux IO学习[1] - 文件IO
  • MySQL用户中的%到底包不包括localhost?
  • Netty 框架总结「ChannelHandler 及 EventLoop」
  • PermissionScope Swift4 兼容问题
  • php中curl和soap方式请求服务超时问题
  • python 学习笔记 - Queue Pipes,进程间通讯
  • react 代码优化(一) ——事件处理
  • sessionStorage和localStorage
  • 百度贴吧爬虫node+vue baidu_tieba_crawler
  • 前端临床手札——文件上传
  • 软件开发学习的5大技巧,你知道吗?
  • 深入体验bash on windows,在windows上搭建原生的linux开发环境,酷!
  • 一起来学SpringBoot | 第三篇:SpringBoot日志配置
  • 用Canvas画一棵二叉树
  • 用简单代码看卷积组块发展
  • Linux权限管理(week1_day5)--技术流ken
  • Semaphore
  • #define与typedef区别
  • #HarmonyOS:基础语法
  • #laravel 通过手动安装依赖PHPExcel#
  • #stm32驱动外设模块总结w5500模块
  • $分析了六十多年间100万字的政府工作报告,我看到了这样的变迁
  • (10)工业界推荐系统-小红书推荐场景及内部实践【排序模型的特征】
  • (Redis使用系列) Springboot 使用redis的List数据结构实现简单的排队功能场景 九
  • (二)pulsar安装在独立的docker中,python测试
  • (翻译)Entity Framework技巧系列之七 - Tip 26 – 28
  • (论文阅读23/100)Hierarchical Convolutional Features for Visual Tracking
  • (三)Pytorch快速搭建卷积神经网络模型实现手写数字识别(代码+详细注解)
  • (四)库存超卖案例实战——优化redis分布式锁
  • (转) ns2/nam与nam实现相关的文件
  • (转贴)用VML开发工作流设计器 UCML.NET工作流管理系统
  • (自适应手机端)响应式服装服饰外贸企业网站模板
  • .NET CORE 第一节 创建基本的 asp.net core
  • .Net Core与存储过程(一)