欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 【pytest中同一个用例多次执行生成一个测试报告的方法】

【pytest中同一个用例多次执行生成一个测试报告的方法】

2024/10/24 4:54:56 来源:https://blog.csdn.net/qq_42206726/article/details/143172085  浏览:    关键词:【pytest中同一个用例多次执行生成一个测试报告的方法】

为了实现主函数执行一次,而指定的测试函数(如 test_img)执行 10 次,你可以通过以下两种方式进行控制:

方法一:在 pytest 中使用 @pytest.mark.parametrize

使用 pytestparametrize 装饰器可以实现让某个测试函数运行多次。下面是一个示例,如何修改 test_img 函数使其执行 10 次:

import pytest# 使用 parametrize 装饰器执行10次测试
@pytest.mark.parametrize("run", range(10))  # 运行10次
def test_img(run):screenshot_path = "resources/base3.png"base_image_path = "resources/base1.png"boolean = check_image_similarity(screenshot_path, base_image_path, threshold=0.5)assert boolean, "两张图片不一样"

在这个例子中,pytest.mark.parametrize("run", range(10)) 会让 test_img 被执行 10 次。

方法二:在主函数中控制循环

如果你想在主函数中控制每个测试函数的执行次数,可以通过在 pytest.main() 中使用循环来执行。修改主函数如下:

if __name__ == "__main__":count = 1while True:print(f"这是第{count}轮次蓝牙、WiFi、热点、dvr压测")report_dir = "report"os.makedirs(report_dir, exist_ok=True)current_time = datetime.now().strftime("%Y%m%d_%H%M%S")report_file = os.path.join(report_dir, f"report_{current_time}.html")# 让 test_img 执行 10 次for i in range(10):try:pytest.main(["-v", "test_img.py", f"--html={report_file}"])except Exception as e:print(f"运行测试时出现错误: {e}")count += 1time.sleep(5)

在这个修改后的代码中,通过在主函数中添加一个 for i in range(10) 的循环,每次测试都执行 10 次,并在每轮次测试结束后生成相应的 HTML 报告。

方法三:使用 pytest-repeat 插件

pytest-repeat 是一个插件,允许你重复执行某个测试。首先安装插件:

pip install pytest-repeat

然后你可以通过命令行参数或代码来控制某个测试执行的次数。比如,使用下面的命令让 test_img 执行 10 次:

pytest --count=10 -v test_img.py

或者在代码中通过 @pytest.mark.repeat(10) 来控制:

import pytest@pytest.mark.repeat(10)
def test_img():screenshot_path = "resources/base3.png"base_image_path = "resources/base1.png"boolean = check_image_similarity(screenshot_path, base_image_path, threshold=0.5)assert boolean, "两张图片不一样"

示例代码:

from PIL import Image
import numpy as np
import pytest
from skimage.metrics import structural_similarity as ssim
import uiautomator2 as u2
import time
import subprocess
import os
from datetime import datetime
# 创建目录
os.makedirs('resources/images', exist_ok=True)# 截图并保存
def save_screenshot(d):current_time = datetime.now().strftime("%Y%m%d_%H%M%S")screenshot_path = f'resources/images/screenshot_{current_time}.png'd.screenshot(screenshot_path)print(f"截图已保存: {screenshot_path}")return screenshot_path  # 返回截图路径# 比较图片相似度的函数
def compare_images_similarity(image1_path, image2_path, threshold=0.5):try:img1 = Image.open(image1_path).convert('L')img2 = Image.open(image2_path).convert('L')img1 = np.array(img1)img2 = np.array(img2)if img1.shape != img2.shape:print("图片尺寸不一致")return 0.0, Falsesimilarity_index, _ = ssim(img1, img2, full=True)return similarity_index, similarity_index >= thresholdexcept Exception as e:print(f"处理图片时发生错误: {e}")return 0.0, False# 检查截图与本地存储图片的相似性
def check_image_similarity(new_screenshot, base_image, threshold=0.5):similarity, is_similar = compare_images_similarity(new_screenshot, base_image, threshold)print(f"相似度: {similarity * 100:.2f}%")if is_similar:print("两张图片相似度大于或等于指定阈值,判断为相同")return Trueelse:print("两张图片相似度小于指定阈值,判断为不同")return False
@pytest.mark.repeat(10)
def test_img():print("正在执行测试")screenshot_path = "resources/base3.png" base_image_path="resources/base1.png" boolean=check_image_similarity(screenshot_path, base_image_path, threshold=0.5)assert boolean, "两张图片图片不一样"
@pytest.mark.parametrize("run", range(10))  # 运行10次
def test_img1(run):print(f"正在执行测试,当前轮次: {run}")screenshot_path = "resources/base3.png" base_image_path="resources/base1.png" boolean=check_image_similarity(screenshot_path, base_image_path, threshold=0.5)assert boolean, "两张图片图片不一样"
if __name__ == "__main__":count = 1while True:print(f"这是第{count}轮次蓝牙、WiFi、热点、dvr压测")report_dir = "report"os.makedirs(report_dir, exist_ok=True)current_time = datetime.now().strftime("%Y%m%d_%H%M%S")report_file = os.path.join(report_dir, f"report_{current_time}.html")try:pytest.main(["-v", "test_img.py", f"--html={report_file}"])except Exception as e:print(f"运行测试时出现错误: {e}")count += 1time.sleep(5)break

总结

  • 使用 parametrize 让函数执行多次是较为简便的方式。
  • 在主函数中循环执行测试可以让你更灵活地控制多次执行。
  • 你也可以使用 pytest-repeat 插件来轻松实现重复运行某个测试。

根据你的需求,选择最适合的方式来实现这个功能。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com