pytest框架下集成jmeter,输出jmeter的测试报告到allure

jmeter官方文档:jlhxxxx.github.io/jmeter-doc-...

python中指定jmeter的方案

方法 1: 使用 subprocess 模块直接调用 JMeter 命令行

示例代码

python 复制代码
import subprocess

def run_jmeter(jmx_file, jmeter_path, result_file):
    """
    使用 subprocess 调用 JMeter 执行 JMX 文件
    :param jmx_file: JMeter 测试计划文件 (.jmx)
    :param jmeter_path: JMeter 的 bin 目录路径
    :param result_file: 保存测试结果的文件路径 (.jtl)
    """
    jmeter_command = [
        f"{jmeter_path}/jmeter",
        "-n",  # 非 GUI 模式
        "-t", jmx_file,  # 测试计划路径
        "-l", result_file  # 保存结果
    ]

    try:
        result = subprocess.run(jmeter_command, capture_output=True, text=True, check=True)
        print("JMeter executed successfully:")
        print(result.stdout)  # 打印 JMeter 输出
    except subprocess.CalledProcessError as e:
        print("JMeter execution failed:")
        print(e.stderr)

# 示例参数
jmeter_bin_path = "/path/to/apache-jmeter-5.5/bin"  # JMeter 的 bin 目录路径
jmx_test_file = "/path/to/test-plan.jmx"  # JMeter 测试计划文件路径
jtl_result_file = "/path/to/result.jtl"  # 结果文件路径

# 调用 JMeter 脚本
run_jmeter(jmx_test_file, jmeter_bin_path, jtl_result_file)

执行流程

  1. 指定 JMeter 的路径、测试计划文件(.jmx)、输出结果文件(.jtl)。
  2. 使用 subprocess.run 运行 JMeter 的命令行模式。
  3. JMeter 会在终端执行,并将结果保存到 .jtl 文件。

方法 2: 使用第三方库 jmeter_api 动态生成并运行 JMeter 脚本

jmeter_api 是一个 Python 库,允许你通过 Python 动态生成和运行 JMeter 脚本。

安装库

复制代码
bash
pip install jmeter-api

示例代码

python 复制代码
python


复制代码
from jmeter_api.basics.thread_group.elements import ThreadGroup
from jmeter_api.basics.test_plan.elements import TestPlan
from jmeter_api.file_format.jmx_file import JMX
from jmeter_api.basics.http_request.elements import HttpRequest

# 创建测试计划
test_plan = TestPlan(name="Demo Test Plan")

# 创建线程组
thread_group = ThreadGroup(name="Thread Group", num_threads=10, ramp_time=5)

# 添加 HTTP 请求
http_request = HttpRequest(name="GET Example", url="https://example.com", method="GET")
thread_group.append(http_request)
test_plan.append(thread_group)

# 保存到 JMX 文件
jmx = JMX(test_plan)
jmx.save("/path/to/generated_test_plan.jmx")

# 调用 JMeter 执行生成的 JMX 文件
import subprocess
subprocess.run(["/path/to/apache-jmeter-5.5/bin/jmeter", "-n", "-t", "/path/to/generated_test_plan.jmx", "-l", "/path/to/result.jtl"])

方法 3: 使用 os.system 调用 JMeter

直接使用 os.system 也是一种简单的方式,但不推荐,因为它无法捕获 JMeter 的输出结果。

示例代码

python 复制代码
import os

def run_jmeter_with_os(jmx_file, jmeter_path, result_file):
    command = f"{jmeter_path}/jmeter -n -t {jmx_file} -l {result_file}"
    os.system(command)

# 示例
run_jmeter_with_os("/path/to/test-plan.jmx", "/path/to/apache-jmeter-5.5/bin", "/path/to/result.jtl")

方法 4: 调用 JMeter 的 REST API

如果你使用的是 JMeter 5.4+ 或者其集成的分布式工具(如 Taurus),可以通过 REST API 控制 JMeter。

示例

  1. 启用 JMeter 的 HTTP Server 模式。
  2. 使用 Python 的 requests 模块向 JMeter API 发送请求。

对比与建议

方法 优点 缺点 场景适用
subprocess 简单、直接调用 JMeter 的 CLI 命令 需要手动管理命令参数 本地运行脚本
jmeter_api 动态生成 JMeter 脚本,减少手动工作 依赖库功能有限,适合简单场景 动态创建脚本
os.system 实现简单 无法捕获 JMeter 输出 调试简单任务
REST API 可与远程 JMeter 集成 需要配置 HTTP Server,增加复杂性 分布式执行任务

推荐

  • 如果只需要运行现有的 .jmx 文件,使用 方法 1 (subprocess)。
  • 如果需要动态生成并运行 JMeter 脚本,使用 方法 2 (jmeter_api)。

pytest下解析jmeter的测试报告,输出数据生成allure

实现思路

  1. 批量获取 JMeter 脚本文件
    • 遍历指定文件夹,获取所有以 .jmx 为扩展名的 JMeter 测试脚本。
  1. 执行 JMeter 脚本
    • 使用 Python 的 subprocess 批量执行 JMeter CLI 命令。
    • 将执行日志和结果保存到指定目录。
  1. 记录执行步骤
    • 在 Allure 中记录每个 JMeter 测试脚本的执行过程和步骤。
  1. 解析 JMeter 测试结果
    • 解析每个脚本生成的 .jtl 文件,提取响应结果并附加到 Allure 报告中。

代码示例

以下是实现批量执行文件夹内 JMeter 脚本并记录到 Allure 的代码:

python 复制代码
python

import os
import subprocess
import xml.etree.ElementTree as ET
import allure
import pytest


def get_jmx_files(folder_path):
    """
    获取文件夹内所有 .jmx 文件
    :param folder_path: JMeter 脚本所在目录
    :return: 脚本路径列表
    """
    return [os.path.join(folder_path, file) for file in os.listdir(folder_path) if file.endswith(".jmx")]


def run_jmeter_script(jmx_file, jmeter_path, output_dir):
    """
    运行单个 JMeter 脚本
    :param jmx_file: JMeter 脚本文件路径
    :param jmeter_path: JMeter 安装路径
    :param output_dir: 输出结果目录
    :return: JTL 文件路径
    """
    jtl_file = os.path.join(output_dir, os.path.basename(jmx_file).replace(".jmx", ".jtl"))

    command = [
        f"{jmeter_path}/jmeter",
        "-n",  # 非 GUI 模式
        "-t", jmx_file,  # 测试计划路径
        "-l", jtl_file  # 保存结果
    ]

    with allure.step(f"运行 JMeter 脚本: {os.path.basename(jmx_file)}"):
        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        for line in process.stdout:
            allure.attach(line.strip(), name="JMeter Log", attachment_type=allure.attachment_type.TEXT)

        process.wait()
        if process.returncode != 0:
            raise RuntimeError(f"JMeter 脚本执行失败: {jmx_file}")

    return jtl_file


def parse_jtl_file(jtl_file):
    """
    解析 JTL 文件,记录测试结果到 Allure
    :param jtl_file: JMeter 结果文件路径
    """
    try:
        tree = ET.parse(jtl_file)
        root = tree.getroot()

        for sample in root.findall("httpSample"):
            url = sample.get("lb")  # 请求的 URL
            response_code = sample.get("rc")  # 响应码
            success = sample.get("s")  # 请求是否成功 ("true" 或 "false")

            with allure.step(f"请求 {url} 的响应结果"):
                allure.attach(f"响应码: {response_code}", name="Response Code", attachment_type=allure.attachment_type.TEXT)
                allure.attach(f"成功状态: {success}", name="Success", attachment_type=allure.attachment_type.TEXT)

            if success != "true":
                raise AssertionError(f"请求 {url} 失败,响应码: {response_code}")
    except Exception as e:
        raise RuntimeError(f"解析 JTL 文件失败: {e}")


@pytest.mark.parametrize("jmx_file", get_jmx_files("./jmeter_scripts"))
def test_batch_jmeter_execution(jmx_file):
    """
    批量执行 JMeter 脚本,并记录结果到 Allure 报告
    """
    jmeter_path = "/path/to/jmeter/bin"  # 替换为 JMeter 安装路径
    output_dir = "./jmeter_results"  # 保存结果的目录

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 运行 JMeter 脚本
    jtl_file = run_jmeter_script(jmx_file, jmeter_path, output_dir)

    # 解析并记录 JTL 文件结果
    parse_jtl_file(jtl_file)

代码解析

  1. get_jmx_files(folder_path)
    • 遍历指定文件夹,返回所有 .jmx 文件路径列表。
  1. run_jmeter_script(jmx_file, jmeter_path, output_dir)
    • 使用 subprocess 调用 JMeter CLI,运行指定的脚本。
    • 将结果保存到 .jtl 文件中,并记录执行过程到 Allure。
  1. parse_jtl_file(jtl_file)
    • 解析生成的 .jtl 文件,提取 HTTP 请求的响应码和执行结果。
    • 通过 Allure 的步骤功能展示每个请求的详细信息。
  1. test_batch_jmeter_execution
    • 使用 pytest 参数化测试,批量执行所有 JMeter 脚本。
相关推荐
小咕聊编程1 小时前
【含文档+源码】基于SpringBoot的过滤协同算法之网上服装商城设计与实现
java·spring boot·后端
追逐时光者7 小时前
推荐 12 款开源美观、简单易用的 WPF UI 控件库,让 WPF 应用界面焕然一新!
后端·.net
Jagger_7 小时前
敏捷开发流程-精简版
前端·后端
苏打水com8 小时前
数据库进阶实战:从性能优化到分布式架构的核心突破
数据库·后端
间彧9 小时前
Spring Cloud Gateway与Kong或Nginx等API网关相比有哪些优劣势?
后端
间彧9 小时前
如何基于Spring Cloud Gateway实现灰度发布的具体配置示例?
后端
间彧9 小时前
在实际项目中如何设计一个高可用的Spring Cloud Gateway集群?
后端
间彧9 小时前
如何为Spring Cloud Gateway配置具体的负载均衡策略?
后端
间彧9 小时前
Spring Cloud Gateway详解与应用实战
后端
EnCi Zheng10 小时前
SpringBoot 配置文件完全指南-从入门到精通
java·spring boot·后端