(Jmeter新玩法)Python 调 Jmeter执行参数化jmx脚本
# Python 调 Jmeter执行参数化jmx脚本 import os from os.path import join import time import re from string import Template jmeter_Home = r"F:\softtotal\xxx\bin\jmeter.bat" # jmx文件路径 currpath = os.path.dirname(os.path.realpath(__file__)) # 要运行的jmx脚本 jmx = r"F:\softtotal\xxx\bin\参数化csv.jmx" # jmx = currpath + r"E:\Dev\xxxx\shoptest.jmx" # 生成的报告放到result文件夹中 # resultpath = currpath + os.sep + "result" resultpath = os.sep + r"F:\softtotal\xxx\result" # 创建参数化jmx文件 # 参数化的内容为:循环次数loops、线程数num_threads、持续运行时间duration def create_para_jmx(): global replaced_jmx jmx_str = '' with open(jmx, 'r', encoding='utf-8') as file: jmx_str = file.read() # 循环次数 loops = 'name="LoopController.loops">(.*?)</stringProp>' replcae_loops = 'name="LoopController.loops">$loops</stringProp>' jmx_str = re.sub(loops, replcae_loops, jmx_str) # 线程数 num_threads = 'name="ThreadGroup.num_threads">(.*?)</stringProp>' repalce_num_threads = 'name="ThreadGroup.num_threads">$num_threads</stringProp>' jmx_str = re.sub(num_threads, repalce_num_threads, jmx_str) # 持续运行时间 duration = 'ThreadGroup.duration">(.*?)</stringProp>' replace_duration = 'ThreadGroup.duration">$duration</stringProp>' jmx_str = re.sub(duration, replace_duration, jmx_str) replaced_jmx = jmx.replace('.jmx', '-P.jmx') with open(replaced_jmx, "w+", encoding="utf-8") as file: file.writelines(jmx_str) # 执行参数化fmx文件,生成带参数的jmx文件 create_para_jmx() # 获取当前时间,格式为20210301122059 now = time.strftime(r'%Y%m%d%H%M%S', time.localtime(time.time())) def execjmx(duration, num_threads, loops): print(f"本次运行的场景为:运行时间:{duration}s、线程数:{num_threads}、循环次数:{loops}") tmpstr = '' with open(replaced_jmx, "r", encoding="utf-8") as file: tmpstr = Template(file.read()).safe_substitute(loops=loops, num_threads=num_threads, duration=duration) with open(replaced_jmx, "w+", encoding="utf-8") as file: file.writelines(tmpstr) # 生成的jtl文件 jtl = resultpath + f'/{now}-{duration}s--{num_threads}threads-{loops}loops.jtl' # 生成的html文件 html = resultpath + f'/{now}-{duration}s-{num_threads}threads-{loops}loops-htmlreport' # Terminal = f*open -a Terminal.app" run = f"{jmeter_Home} -n -t {replaced_jmx} -l {jtl} -e -o {html}" os.system(run) # _执行jmx文件 # 时间、吞吐量、线程数、循环次数 duration = '' # throughput ='' num_threads = '' loops = '' duration = int(input("运行时间:" + duration)) # throughput = int(input("吞吐量:"+ throughput)) num_threads = int(input("线程数:" + num_threads)) loops = int(input("循环次数:" + loops)) execjmx(duration, num_threads, loops)
运行后结果截图