(Jmeter新玩法)Python 調 Jmeter執行引數化jmx指令碼

BUGMANWL發表於2024-08-06
# 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)

執行後結果截圖

相關文章