-
Notifications
You must be signed in to change notification settings - Fork 21
/
run.py
356 lines (306 loc) · 11.4 KB
/
run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
'''
此处存放后台接口,由于目前接口较少
'''
import logging
from flask import render_template, jsonify
from initial import app
from test_method.caseOperator import apiFunc
from common.function import Operator
import os
from datetime import datetime
from flask import send_file
from common.time_handle import handle
from db_operator.mysql_db import MysqlDb
from flask import request
import re
from db_operator.user_db import UserDb
from flask import session
from flask import url_for
from flask import redirect
from datetime import timedelta
from db_operator.mongo_operator import MongoClient
from flask import make_response
from functools import wraps
def login_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if session.get('user'):
return func(*args, **kwargs)
else:
return render_template("login.html")
return wrapper
'''
# 运行excel文件用例接口
@app.route('/run/<filename>', methods=['GET'])
def run_test(filename):
rt, report = {}, None
try:
# 获取excel工作目录
dir = app.config['WORKSPACE']
obj = apiFunc()
rt = obj.run_test(dir, [filename], app.config['THREAD_NUM'])
report = obj.writeReport(rt)
except Exception as err:
logging.error("run_test error: {}".format(str(err)))
return render_template('testResult.html',failNum=rt['failed_num'], ignored=rt['ignored'],
successNum=rt['success_num'], total=rt['total'], start=rt['start'],
end=rt['end'], cost="{:.2}秒".format(rt['cost']), fileName=report)
'''
@app.route('/', methods=['GET'])
@login_required
def index():
return render_template('index.html', user=session.get('user'))
@app.route('/case')
@login_required
def case_view():
db = MongoClient()
caseList = db.get_case_list()
del db
return render_template('case_list.html', posts=caseList, user=session.get('user'))
# 运行excel文件用例接口
@app.route('/run', methods=['POST'])
def run_selected():
excel_list = []
start = handle.now_str()
form_data = request.form.__str__()
# 正则提取选中的excel
if re.findall(r'\[(.+)\]', form_data):
rv = re.findall(r'\[(.+)\]', form_data)[0]
rv = re.findall(r'\((.+?)\)', rv)
for item in rv:
excel_list.append(item.split(',')[-1].replace("\'","").replace("\\\\", "\\").split()[0])
rt, report = {}, None
try:
# 获取excel工作目录
dir = app.config['WORKSPACE']
obj = apiFunc()
if excel_list:
rt = obj.run_test(dir, excel_list, app.config['THREAD_NUM'])
report = obj.writeReport(rt)
else:
return render_template("error.html", errorInfo="请选择至少一个xlsx文件! 页面会在3秒后跳转!")
except Exception as err:
logging.error("run_test error: {}".format(str(err)))
return render_template('testResult.html',failNum=rt['failed_num'], ignored=rt['ignored'],
successNum=rt['success_num'], total=rt['total'], start=start,
end=handle.now_str(), cost="{:.2}秒".format(handle.delta(start, handle.now_str())),
fileName=report)
# 查看报告接口
@app.route('/report/<filename>')
@login_required
def showHtml(filename):
return send_file(os.path.join(app.config['REPORT'], filename))
# 查询验证码并返回
@app.route('/getVerifyCode')
def getVerify(mobile="18516600716"):
rt = {'code': None}
db = MysqlDb(app.config['DBNAME'])
rt.update(dict(code=db.getVerifyCode(mobile)))
return jsonify(rt)
@app.route('/delUser')
def delUser(mobile="18516600716"):
rt = {'status': False}
db = MysqlDb(app.config['DBNAME'])
rt.update(dict(status=db.delete_user(mobile)))
return jsonify(rt)
@app.route('/case/new', methods=['POST'])
@login_required
def create_case():
db = None
rt = {'code': 500, 'error': '', 'status': 0}
case_info = {}
try:
data = request.form
if data:
expect = data.get('expected')
case_name = str(data.get('case_name'))
params = data.get('params')
method = data.get('method')
_assert = data.get('assert')
url = data.get('url')
headers = data.get('headers')
content = data.get('content', '')
precondition = data.get("precondition")
sql_prepare = data.get('sql_prepare')
sql_verify = data.get('sql_verify')
sql_clean = data.get('sql_clean')
case_info.update(dict(
expected=expect, enable=True,
name=case_name, params=params,
_assert=_assert, url=url,
content=content, method=method,
headers=headers, sql_clean=sql_clean,
sql_verify=sql_verify, sql_prepare=sql_prepare,
pre=precondition
))
case_info = Operator.transfer_str(**case_info)
if expect and case_name and method and url and headers:
if method.lower() == 'post':
if not params:
raise Exception('Please provide params for post method.')
db = MongoClient()
result = db.add_case(**case_info)
if result:
rt.update(dict(code=200, status=1, msg='Add a case Successfully.'))
else:
raise Exception('Please check your params for case_info.')
except Exception as err:
logging.error('create_case error: {}'.format(str(err)))
rt.update(dict(error=str(err)))
finally:
if db:
del db
return jsonify(rt)
@app.route('/create_case', methods=['GET'])
def create_case_html():
return render_template('create_case.html', user=session.get('user'))
@app.route('/run_xlsx')
def run_xlsx():
file_list = Operator.getFileList()
return render_template('run_xlsx.html', fileList=file_list, user=session.get('user'))
@app.route('/login', methods=('POST', ))
def login():
db = UserDb(app.config['LOCAL_DB'])
form = request.form
user = form.get('user')
pwd = form.get('pwd')
password = db.login(user)
del db
if pwd == password:
# 添加登陆状态
session.permanent = True
# session保留时间
app.permanent_session_lifetime = timedelta(minutes=30)
session.update(dict(user=user))
return render_template('index.html')
elif password is None:
return render_template('login.html', info="该用户不存在!")
else:
return render_template('login.html', info="密码不正确!")
@app.route('/for_login')
def for_login():
if session.get('user'):
return render_template('index.html', info=None, user=session.get('user'))
else:
return render_template('login.html')
@app.route('/for_register')
def for_register():
return render_template('register.html', info=None)
@app.route('/register', methods=('POST', ))
def register():
form = request.form
user = form.get('user')
pwd = form.get('passwd1')
db = UserDb(app.config['LOCAL_DB'])
rt = db.register(user, pwd)
if rt:
session.update(dict(user=user))
return render_template('register_to_main.html')
else:
return render_template('register.html', info='用户已存在!')
@app.route('/delete_case', methods=('POST', ))
def delete_case():
rt = {'status': False, 'msg': None}
try:
data = request.get_json()
case_name = data.get('case_name')
db = MongoClient()
db.delete_case(case_name)
del db
rt.update(dict(status=True))
except Exception as err:
print("{} error: {}".format(Operator.get_current_func(), str(err)))
return jsonify(rt)
@app.route("/logout")
def logout():
session.pop('user')
return redirect(url_for("for_login"))
@app.route("/run_case", methods=('POST', ))
def run_selected_case():
# return jsonify(dict(name='selenium'))
data = request.get_json()
start = handle.now_str()
# 先找到mongo里的case信息
db = MongoClient()
case_list = db.get_case_by_name(data.get('case_name'))
obj = apiFunc()
rt = obj.run_tests(case_list, app.config['THREAD_NUM'])
report = obj.writeReport(rt)
html = render_template('testResult.html',failNum=rt['failed_num'], ignored=rt['ignored'],
successNum=rt['success_num'], total=rt['total'], start=start,
end=handle.now_str(), cost="{:.2}秒".format(handle.delta(start, handle.now_str())),
fileName=report)
return jsonify(dict(html=html))
@app.route("/homework")
def get_homework():
if session.get('user'):
obj = MongoClient()
db = obj.get_db()
homework = list(db.homework.find())
return render_template('homework.html', user=session.get('user'), homework=homework)
else:
return render_template('login.html')
@app.route("/homework/download/<filename>")
def download_homework(filename):
return send_file(os.path.join(app.config['HOMEWORK'], filename))
@app.route("/edit_case/<case_name>")
def edit_page(case_name):
db = MongoClient()
case = db.get_case_info(case_name)
case = Operator.transfer_case_info(case)
return render_template('edit_case.html', case=case)
@app.route("/case/edit", methods=('POST', ))
@login_required
def edit_case():
db = None
rt = {'code': 500, 'error': '', 'status': 0}
case_info = {}
try:
data = request.form
if data:
_id = data.get('_id')
expect = data.get('expected')
case_name = str(data.get('case_name'))
params = data.get('params')
method = data.get('method')
_assert = data.get('assert')
url = data.get('url')
headers = data.get('headers')
content = data.get('content', '')
precondition = data.get("precondition")
sql_prepare = data.get('sql_prepare')
sql_verify = data.get('sql_verify')
sql_clean = data.get('sql_clean')
case_info.update(dict(
expected=expect, enable=True,
name=case_name, params=params,
_assert=_assert, url=url,
content=content, method=method,
headers=headers, sql_clean=sql_clean,
sql_verify=sql_verify, sql_prepare=sql_prepare,
pre=precondition
))
case_info = Operator.transfer_str(**case_info)
if expect and case_name and method and url and headers:
if method.lower() == 'post':
if not params:
raise Exception('Please provide params for post method.')
db = MongoClient()
result = db.edit_case(_id, case_info)
if result.raw_result['ok']:
rt.update(dict(code=200, status=1, msg='Add a case Successfully.'))
else:
raise Exception('Please check your params for case_info.')
except Exception as err:
logging.error('create_case error: {}'.format(str(err)))
rt.update(dict(error=str(err)))
finally:
if db:
del db
return jsonify(rt)
@app.route('/people')
@login_required
def photos():
return render_template("people.html", user=session.get('user'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000)