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

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

相关推荐
努力的搬砖人.11 分钟前
nacos配置达梦数据库驱动源代码步骤
java·服务器·数据库·经验分享·后端
丁总学Java16 分钟前
如何用 nvm alias default 18.20.8 实现全局 Node.js 版本管理?一篇保姆级指南!!!
linux·node.js·vim
Yang三少喜欢撸铁35 分钟前
【Linux部署DHCP服务】
linux·运维·服务器
GanGuaGua37 分钟前
linux系统下如何提交git和调试
服务器·git
太极淘38 分钟前
桌面版本及服务器版本怎么查看网络源软件包的url下载路径
运维·服务器·网络
自由与自然40 分钟前
乐观锁与悲观锁的使用场景
java·服务器·数据库
程序员小软2 小时前
linux-添加开机自启动指定脚本
linux·运维
安於宿命2 小时前
【Linux】用C++实现UDP通信:详解socket编程流程
linux·c++·udp
BUG 劝退师9 小时前
进程间通讯(IPC)
运维·服务器·网络
冷冷清清中的风风火火9 小时前
linux 里的创建了一个tomcat用户 怎么禁止该用户使用crontab 功能
linux·tomcat·firefox