性能测试自动化平台(三)后端逻辑实现(python)

在这里插入图片描述
在这里插入图片描述

入口

from flask import Flask
from flask_cors import *

app=Flask(__name__)
CORS(app, supports_credentials=True)


@app.route('/')
def index():
    return 'index'

from vuejmeterauto.uploadfile import *
app.register_blueprint(upload_blue)

from vuejmeterauto.updatejenkins import *
app.register_blueprint(update_blue)

from vuejmeterauto.MatchFilename import *
app.register_blueprint(match_blue)

from vuejmeterauto.Getjmxdata import *
app.register_blueprint(getjmx_blue)

if __name__ == '__main__':
    app.run(host='XXX', port='50055', debug=True)

在线编辑页面的相关操作

from flask import request,Blueprint
import os
import re
import threading
from vuejmeterauto.uploadfile import file_to_git

getjmx_blue = Blueprint("getjmx",__name__)
file_path = r"E:\test\esg-cemp-core-auto-test-project"

#获取jmx文件
@getjmx_blue.route('/getjmxfile',methods=['GET','POST'])
def getjmxfile():
    jmx_name = request.json['jmx_name']
    a = ''
    match_string = '{0}.jmx'.format(jmx_name)
    b = os.system('dir {0} /b > E:\eula.2052.txt'.format(file_path))
    file_open = open(r"E:\eula.2052.txt", 'r', encoding='utf-8')
    file_read = file_open.read().splitlines()
    # print(file_read)
    for i in file_read:
        result = re.match(match_string, i)
        if result is not None:
            a = i
    file_open.close()
    # print(a)
    if bool(a):
        # with open(file_path+jmx_name+'.jmx','r') as jmx_file:
        #     jmx_data = jmx_file.read()
        # jmx_file.close()
        return jmx_name
    else:
        return '000'
#读取jmx文件内容
@getjmx_blue.route('/getjmxdata',methods=['GET','POST'])
def getjmxdata():
    jmx_name = request.json['jmx_name']
    with open(file_path + '\\'+jmx_name+'.jmx','r',encoding='utf-8') as jmx_file:
        jmx_data = jmx_file.read()
    jmx_file.close()
    return jmx_data
#调用jmeter进行调试
@getjmx_blue.route('/runjmeter',methods=['GET','POST'])
def jmeter_run():
    #jmeter -n -t D:\apache-jmeter-3.1\jmx\mimp登录.jmx -l D:\apache-jmeter-3.1\result\2323232.jtl -e -o D:\apache-jmeter-3.1\result\3322323
    # run_cmd=r'''jmeter -Jthread=1 -Jstart_thread=1 -Jseconds=1 -Jadd_thread=1 -n -t {1}\{0}.jmx -l D:\apache-jmeter-3.1\result\{0}.jtl -e -o D:\apache-jmeter-3.1\result\{0}'''.format(jmx_name,file_path)
    time = threading.Timer(0.1, run_cmd)
    time.start()
    return '调试成功'
#异步操作
def run_cmd():
    jmx_name = 'HTTPrequest'
    os.system(r'rd /s/q D:\apache-jmeter-3.1\result\{0}'.format(jmx_name))
    os.system(r'del D:\apache-jmeter-3.1\result\{0}.jtl'.format(jmx_name))
    os.system(r'jmeter -n -t D:\apache-jmeter-3.1\jmx\mimp登录.jmx -l D:\apache-jmeter-3.1\result\HTTPrequest.jtl -e -o D:\apache-jmeter-3.1\result\HTTPrequest')
#保存修改的脚本,根据前端的传值保存
@getjmx_blue.route('/savejmeterdata',methods=['GET','POST'])
def savejmeterdata():
    jmx_name = '111'
    jmx_data = request.json['jmx_data']
    with open(file_path + '\\' + jmx_name + '.jmx', 'w', encoding='utf-8') as jmx_file:
        jmx_file.write(jmx_data)
    jmx_file.close()
    return '保存成功'
#上传文件到git
@getjmx_blue.route('/uploadtogit',methods=['GET','POST'])
def uploadtogit():
    time = threading.Timer(0.1, file_to_git)
    time.start()
    return '上传成功'

前端点击查看报告,后端获取文件

import os
import re
from flask import Blueprint,request

match_blue = Blueprint("match",__name__)
#获取测试报告文件夹
@match_blue.route('/matchfile', methods=['GET', 'POST'])
def match_file():
    jmx_name = request.json['jmx_name']
    # print(jmx_name)
    file_path = r'文件夹存放的路径'
    a = ''
    match_string = '\w*({0})\w*'.format(jmx_name)
    b = os.system('dir {0} /b > E:\eula.2052.txt'.format(file_path))
    file_open = open(r"E:\eula.2052.txt",'r',encoding='utf-8')
    file_read = file_open.read().splitlines()
    # print(file_read)
    for i in file_read:
        result = re.match(match_string,i)
        if result is not None:
            a = i
    file_open.close()
    # print(a)
    if bool(a):
        return '111'
    else:
        return '000'

操作Jenkins

from flask import Blueprint, abort,  make_response, request
import jenkins
from xml.dom import minidom
import time as tm
import threading


update_blue = Blueprint("update",__name__)
file_path = r"D:\test_auto\vuejmeterauto\config"
#调Jenkins新建一个job,根据前端的传值组装job的配置信息传过去
@update_blue.route('/jenkins/update', methods=['POST'])
def jenkins_add_update():
    #获取前端的传值
    jmx_name = request.json['jmx_name']
    time = request.json['time']
    author_id = request.json['author_id']
    thread = request.json['thread']
    start_thread = request.json['start_thread']
    seconds = request.json['seconds']
    add_thread = request.json['add_thread']
    if not request.json or not 'time' in request.json:
        abort(400)

    report_name = jmx_name + author_id + str(int(tm.time()*1000))
    time = threading.Timer(0.1,uploadjenkins(report_name,jmx_name,time,thread,start_thread,seconds,add_thread))
    time.start()
    return '保存成功'

def uploadjenkins(report_name,jmx_name,time,thread,start_thread,seconds,add_thread):

    #实例化jenkins对象,连接远程的jenkins master server
    server = jenkins.Jenkins('XXX', username='xxx', password='xxx')
    #获取已有的模板job的配置
    # xml = server.get_job_config("copy_copy")
    #根据前端的传参修改xml文件内容
    dom = minidom.parse(file_path)
    root = dom.documentElement
    tag = root.getElementsByTagName('spec')
    tag_command = root.getElementsByTagName('command')
    t = tag[0]
    t.firstChild.data = time
    tag_command[0].firstChild.data = r"""set MINIMAL_VERSION=1.8.0
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_40
set PATH=%SystemRoot%/system32;%SystemRoot%;%JAVA_HOME%\bin;%PATH%
rd /s/q D:\apache-jmeter-3.1\result\{0}
del D:\apache-jmeter-3.1\result\{0}.jtl
jmeter -Jthread={1} -Jstart_thread={2} -Jseconds={3} -Jadd_thread={4} -n -t D:\apache-jmeter-3.1\jmx\%jmx_name%.jmx -l D:\apache-jmeter-3.1\result\{0}.jtl -e -o D:\apache-jmeter-3.1\result\{0}
""".format(report_name,thread,start_thread,seconds,add_thread)

    with open("file_path", 'w') as f:
        dom.writexml(f, addindent='', encoding='utf-8')


    #获取xml文件中的配置信息
    f = open("file_path", 'r')
    xml = f.read()
    #创建新的job
    server.create_job(jmx_name,xml)

    f.close()

上传文件到git

因为我们的git禁用了API调用,所以我弄了个本地仓库,通过命令行上传。

from flask import request,Blueprint
import os
from werkzeug.utils import secure_filename
import threading

upload_blue = Blueprint("admin",__name__)
UPLOAD_FOLDER = r'E:\test\esg-cemp-core-auto-test-project'

@upload_blue.route('/upload',methods=['GET','POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(os.path.join(UPLOAD_FOLDER,filename))
        time = threading.Timer(0.1, file_to_git)
        time.start()
        return '保存成功'

def file_to_git():
    os.chdir(UPLOAD_FOLDER)
    os.system('git pull')
    os.system('git commit')
    os.system('git add .')
    os.system('git commit -m test')
    os.system('git push')

详细介绍

1、使用flask(python)编写接口暴露给前端进行调用
(需要解决跨域问题–flask_cors)
2、由于公司的git不允许通过api进行直接调用。所以采用另外的解决方案:先保存文件到git本地仓库,再用cmd命令上传到git(使用os.system(cmd))
3、引用jenkins模块操作Jenkins(pip install python-jenkins,使用说明文档:https://python-jenkins.readthedocs.io/en/latest/api.html)
4、from xml.dom import minidom,使用minidom操作xml文件
5、创建Jenkins的job时将根据前端传值修改后的xml文件内容传给Jenkins
6、使用os.system(cmd)获取到存放测试报告文件夹路径下的文件夹名称
7、使用正则表达式去匹配文件夹的名称,如果匹配上说明jmeter执行完成,则返回测试报告给前端
8、flask.request去获取前端的传值jmx_name
9、使用flask的Blueprint实现模块化
10、import threading,使用threading模块实现异步操作

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值