(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)
運行后結果截圖

浙公網安備 33010602011771號