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

【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 = 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 是一个插件,允许你重复执行某个测试。首先安装插件:

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

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


http://www.kler.cn/news/368689.html

相关文章:

  • 高效网络自动化:Python在网络基础中的应用
  • Java面试题十一
  • 【解惑】如何用python输出“1024“
  • 飞书文档解除复制限制
  • beautifulsoup4的使用
  • 第二十六节 直方图均衡化
  • 学习FPGA需要掌握哪些语言
  • 线程支持库(C++11)
  • 【JavaEE初阶】网络原理-深入理解网络通信中协议的概念
  • 20241023软考架构-------软考案例5答案
  • 相关Coverage Path Planning的论文整理
  • C#的访问修饰符
  • Python基于TensorFlow实现简单循环神经网络分类模型(SimpleRNN分类算法)项目实战
  • Vue.js 学习总结(11)—— Vue3 Hook 函数实战总结
  • Dyna-Q 算法_笔记_20241023
  • 微信小程序-获取头像和昵称
  • CSS中的!important和空格选择器深入解析
  • 安全运营 -- 监控linux命令history
  • Python量子生成对抗网络QGAN神经网络药物发现、多方法乳腺癌药物筛选应用
  • 开放式耳机哪个品牌音质好?音质最好的开放式耳机推荐!
  • linux上离线安装python环境以及机器学习环境
  • 什么是DDoS脉冲攻击?怎么防御?
  • vue项目常见模块的安装及使用
  • 【Qt】系统相关——多线程、Qt多线程介绍、常用函数、线程安全、网络、UDP Socket、TCP Socket
  • Axios与Java Spring交互:RESTful API设计与实现全解析
  • 图像变换的知识