# -*- coding: utf-8 -*-
import os
import time
import subprocess
import sched
from string import Template
currpath = r"D:\autoTestJmeter"
JMETER_Home = r'"D:\Program Files\JMeter\apache-jmeter\apache-jmeter-5.1.1\bin\jmeter.bat"'
def getDateTime():
#获取当前日期时间
return time.strftime(r'%Y%m%d%H%M%S', time.localtime(time.time()))
def execcmd(command):
print 'command :', command.decode('gbk') #待执行shell命令
utput = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
stderrinfo, stdoutinfo = output.communicate()
returncode = output.returncode
print 'stdout : ', stdoutinfo.decode('gbk')
print 'stderr : ', stderrinfo.decode('gbk')
print 'returncode :', str(returncode).decode('gbk')
def execjmxs(Num_Threads,JmxRunFileName,name): #传入参数根据实际需要可变,这里指定线程数和运行jmx脚本路径及名称
tmpstr = ''
with open(JmxRunFileName, "r") as file:
tmpstr = Template(file.read()).safe_substitute(num_threads=Num_Threads)
now = getDateTime()
tmpjmxfile = currpath + r"\{0}NT{1}T{2}.jmx".format(name, Num_Threads, now)
with open(tmpjmxfile, "w+") as file:
file.writelines(tmpstr)
csvfilename = currpath + r"\{0}Result{1}.csv".format(name, now) #result文件
htmlreportpath = currpath + r"\{0}Htmlreport{1}".format(name, now) #HTMLreport文件
if not os.path.exists(htmlreportpath):
os.makedirs(htmlreportpath)
execjmxouthtml = "cmd.exe /c " + JMETER_Home + " -n -t " + tmpjmxfile + " -l " + csvfilename + " -e -o " + htmlreportpath
execcmd(execjmxouthtml)
def main():
JmxRunFileNameList = [
r"D:\Program Files\JMeter\apache-jmeter-5.1.1\apache-jmeter-5.1.1\workspace\test-api\test-api-single.jmx",
r"D:\Program Files\JMeter\apache-jmeter-5.1.1\apache-jmeter-5.1.1\workspace\test-api\test-api-keyword.jmx"
]
nameList = [
"single","keyword"
]
schedule = sched.scheduler(time.time, time.sleep)
t = (2020, 2, 28, 15, 20 ,00, 0, 0, 0)
startExecTime = time.mktime(t) #开始执行时间
basicTime = 200.0
schedule.enterabs(startExecTime + basicTime * 0, 0, execjmxs, (2,JmxRunFileNameList[0],nameList[0],))#schedule内指定待执行函数,后接函数内参数
schedule.enterabs(startExecTime + basicTime * 1, 0, execjmxs, (5,JmxRunFileNameList[0],nameList[0],))
schedule.enterabs(startExecTime + basicTime * 2, 0, execjmxs, (10,JmxRunFileNameList[0],nameList[0],))
schedule.enterabs(startExecTime + basicTime * 3, 0, execjmxs, (2,JmxRunFileNameList[1],nameList[1],))
schedule.enterabs(startExecTime + basicTime * 4, 0, execjmxs, (5,JmxRunFileNameList[1],nameList[1],))
schedule.enterabs(startExecTime + basicTime * 5, 0, execjmxs, (10,JmxRunFileNameList[1],nameList[1],))
schedule.run()
if __name__ == '__main__':
main()