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

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

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

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

python 复制代码
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() 中使用循环来执行。修改主函数如下:

python 复制代码
if __name__ == "__main__":
    count = 1
    while 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 += 1
        time.sleep(5)

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

方法三:使用 pytest-repeat 插件

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

bash 复制代码
pip install pytest-repeat

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

bash 复制代码
pytest --count=10 -v test_img.py

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

python 复制代码
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, "两张图片不一样"

示例代码:

python 复制代码
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, False

        similarity_index, _ = ssim(img1, img2, full=True)

        return similarity_index, similarity_index >= threshold

    except 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 True
    else:
        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 = 1
    while 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 += 1
        time.sleep(5)
        break

总结

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

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

相关推荐
青梅橘子皮10 小时前
Linux---基本指令
linux·运维·服务器
REDcker11 小时前
Linux信号机制详解 POSIX语义与内核要点 sigaction与备用栈实践
linux·运维·php
cui_ruicheng12 小时前
Linux进程间通信(三):System V IPC与共享内存
linux·运维·服务器
蚰蜒螟12 小时前
深入 Linux 内核同步机制:从 futex 到 spinlock 的完整旅程
linux·windows·microsoft
运维全栈笔记12 小时前
Linux安装配置Tomcat保姆级教程:从部署到性能调优
linux·服务器·中间件·tomcat·apache·web
dllmayday13 小时前
Linux 上用终端连接 WiFi
linux·服务器·windows
ACP广源盛1392462567313 小时前
IX8024与科学大模型的碰撞@ACP#筑牢科研 AI 算力高速枢纽分享
运维·服务器·网络·数据库·人工智能·嵌入式硬件·电脑
峥无14 小时前
Linux系统编程基石:静态库·动态库·ELF文件·进程地址空间全景图
linux·运维·服务器
用户23678298016815 小时前
从 chmod 755 说起:Unix 文件权限到底是怎么算的?
linux
Strugglingler15 小时前
【systemctl 学习总结】
linux·systemd·systemctl·journalctl·unit file