【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 插件来轻松实现重复运行某个测试。

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

相关推荐
杜子不疼.4 分钟前
Linux】 性能调优实战:内核参数优化技巧
linux·运维·php
墨寒博客栈29 分钟前
Linux基础常用命令
java·linux·运维·服务器·前端
重生之我在20年代敲代码31 分钟前
【Linux网络编程】初识网络,理解TCP/IP五层模型
linux·运维·服务器·网络
**蓝桉**33 分钟前
服务器管理
linux·笔记
疯狂的小强呀35 分钟前
如何利用 Jupyter 从浏览器访问远程服务器
服务器·jupyter·浏览器访问服务器·jupyter远程访问服务器
GalaxyPokemon1 小时前
PlayerFeedback 插件开发日志
java·服务器·前端
没枕头我咋睡觉1 小时前
【运维】ubuntu修改镜像源
linux·运维·ubuntu
鲸鱼爱泡芙1 小时前
IMX6ULL无法通过Ubuntu22.04 NFS uboot挂载rootfs根目录解决
linux
努力学习的小廉1 小时前
深入了解linux网络—— 守护进程
linux·运维·网络
wheeldown2 小时前
【Linux】从内存布局到信号屏蔽:Linux 内核态与用户态交互核心知识点汇总
linux·运维·服务器