def do_search(searchTxT): single_api_sql = f"select apiname, apidesc from case_singeapi where apiname like '%{searchTxT}%'" scenect_api_sql = f"select apitestname, apitestdesc from case_apitest where apitestname like '%{searchTxT}%'" task_sql = f"select name, task from djcelery_periodictask where name like '%{searchTxT}%'" product_sql = f"select name,`desc` from items_items where name like '%{searchTxT}%'" app_sql = f"select name,`desc` from items_itemsapplication where name like '%{searchTxT}%'" results = Mysql().sql_result(scenect_api_sql) + Mysql().sql_result(single_api_sql) + Mysql().sql_result(task_sql) +\ Mysql().sql_result(product_sql) + Mysql().sql_result(app_sql) dict_result = [] if len(results) == 0: pass else: for result in results: new_result = {"name": result[0], "desc": result[1]} dict_result.append(new_result) return dict_result
def caseWriteResult_scence(reason, status): now = time.strftime("%Y-%m-%d %H:%M:%S") reason = pymysql.escape_string(reason).replace('\\n', ' ').replace('"', "'") sql = f'UPDATE case_apitest SET case_apitest.update_time="{now}", case_apitest.failreason="{reason}", ' \ f'case_apitest.apitestresult={status}' Mysql().updata(sql)
def get_bugList_name(): sql = f"select bugname from bug_bug where bugstatus<>'关闭'" nameList = Mysql().sql_result(sql) names = [] for name in nameList: names.append(name[0]) return names
def add_delay_product(): url = web_host + '/admin/product/delayProductAdd' data = { 'id': '', 'version': '', 'name': time.asctime(), 'type': f"P_T_0{random.randint(1,3)}", 'marketPriceValue': random.randint(5000, 1000000), 'beginPrice': random.randint(0, 100), 'bidIncValue': random.randrange(100, 500, 100), 'desc': f'拍品创建于:{time.asctime()}.', 'images': Mysql().reslut_replace(f'select url from img order by rand() limit 1'), 'video': '', 'videoImage': '', 'noSiteMeshWapper': 'true' } req = requests.post(url, data=data, headers=web_headers, timeout=2) return req
def api_test(): sql = "SELECT id, `apiname`, apiurl, apimethod, apiparamvalue, apiresult, `apistatus`, apistatuscode," \ " ItemsApplication_id, apiheaders from case_singeapi " caselist = Mysql().sql_result(sql) case_list = [] for ii in caselist: case_list.append(ii) Doapi(case_list)
def caseWriteResult(case_id, result, code, status): now = time.strftime("%Y-%m-%d %H:%M:%S") result = result.replace('"', "'") sql = f'UPDATE case_singeapi SET case_singeapi.update_time="{now}", ' \ f'case_singeapi.apistatuscode="{code}", ' \ f'case_singeapi.apiresponse="{result}", ' \ f'case_singeapi.apistatus="{status}" ' \ f'where case_singeapi.id={case_id}' Mysql().updata(sql)
def add_bid_product(): url = web_host + '/admin/product/productAdd' data = { 'id': '', # 商品ID 'version': '', # 'name': time.asctime(), # 商品名字 'type': f"P_T_0{random.randint(1,5)}", # 商品类型 # 预计拍卖时长 'planTime': 'P_P_02', 'marketPrice': f'P_M_0{random.randint(1,6)}', # 市场预估价 'beginPrice': random.randint(0, 100), # 起拍价 'bidInc': 'B_I_03', # 加价幅度 'desc': f'拍品创建于:{time.asctime()}.', 'images': Mysql().reslut_replace( f'select url from img order by rand() limit 1'), # 封面图片 'file': '', # 'lot3dFilePath': '', # 3D图 'attachments': Mysql().reslut_replace( f'select url from img order by rand() limit 1'), # 简介图 'video': '', # 视频 'videoImage': '', # 视频文件图片 # 字体详情定义样式 'markFonts': '' } req = requests.post(url, data=data, headers=web_headers, timeout=2) return req
def add_delay_auction(): expectedStartTime = (datetime.datetime.now() + datetime.timedelta(minutes=3)) expectedEndTime = (expectedStartTime + datetime.timedelta(minutes=50)) productIdList = TestMysql().reslut_replace \ (f'SELECT SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id DESC),",", 10) from product WHERE member_id=5152 ' f'AND valid=TRUE AND bid_model="AUC_DELAY" AND sold_out=FALSE AND source="APP" AND in_auction=FALSE ' f'GROUP BY member_id') if len(productIdList.split(',')) == 0: for i in range(10): self.delayProductAdd() productIdList = TestMysql().reslut_replace \ (f'SELECT SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY id DESC),",", 10) from product WHERE member_id=5152 ' f'AND valid=TRUE AND bid_model="AUC_DELAY" AND sold_out=FALSE AND source="APP" AND in_auction=FALSE ' f'GROUP BY member_id') url = web_host + '/admin/auction/delayAuctionAdd' data = { "id": '', "version": "", "categoryCode": "A_D_T_01", "buyerCommissionPercent": '0', "name": time.asctime(), "bidBondAmount": random.randrange(0, 5000, 1000), "freePost": 1, "guaranteeCommission": '', "scheduled": True, 'icon': Mysql().reslut_replace(f'select url from img order by rand() limit 1'), "expectedStartTime": expectedStartTime.strftime("%Y-%m-%d %H:%M:%S"), "desc": (time.asctime() + '\n') * 20, "expectedEndTime": expectedEndTime.strftime("%Y-%m-%d %H:%M:%S"), "productIdList": productIdList, "noSiteMeshWapper": True } requests.post(url, data=data, headers=web_headers) auctionId = TestMysql().reslut_replace\ (f'select id from auction where member_id=5152 AND bid_model="AUC_DELAY" AND valid=TRUE AND source="APP" ' f'AND appr_state="D" and auction_state="N" order by id desc') push_url = web_host + '/admin/auction/publishAuction' push_data = {"auctionId": auctionId, "_method": "put"} requests.post(push_url, data=push_data, headers=web_headers)
def scence_test(): sql = f'SELECT id, apiname, apiurl, apimethod, apiparamvalue, apiheaders, apiresult, apistatuscode, `apistatus`, ' \ f'Apitest_id from case_apistep' results = Mysql().sql_result(sql) dict_list = [] if len(results) > 1: for i in range(1, len(results)): dict_result = {f'场景{results[i-1][-1]}': [results[i - 1]]} if f'场景{results[i-1][-1]}' == f'场景{results[i][-1]}': dict_result[f'场景{results[i-1][-1]}'].append(results[i - 1]) dict_list.append(dict_result) else: dict_result = {f'场景{results[0][-1]}': [results[0]]} dict_list.append(dict_result) for api in dict_list: apisteps = list(api.values())[0] DoScneceapi(apisteps)
def writeBug(bug_id, api_name, api_url, request, code, response, res_check, ItemAppId): now = time.strftime("%Y-%m-%d %H:%M:%S") names = get_bugList_name() bugname = str(bug_id) + '_' + api_name + '_出错了' bugdetail = '[请求接口]<br />' + api_url + '<br/>' +\ '[请求数据]<br />' + str(request) + '<br/>' +\ '[响应状态码]<br />' + str(code) + '<br/>' +\ '[预期结果]<br/>' + res_check + '<br/>' +\ '[响应数据]<br />' + str(response) + '<br/>' sql = "INSERT INTO bug_bug (bugname, bugdesc, buglevel, bugcreater, createtime, " \ "bugstatus, ItemsApplication_id, bugrepair) " \ "VALUES ('%s', '%s', '3', 'admin', '%s', '激活', '%s', 'admin');" % \ (bugname, pymysql.escape_string(bugdetail), pymysql.escape_string(now), ItemAppId) if bugname in names: pass else: Mysql().updata(sql)
def writeScenceBug(apitest_name, api_name, api_url, request, code, response, res_check): now = time.strftime("%Y-%m-%d %H:%M:%S") bugname = '场景测试: %s_出错了' % apitest_name names = get_bugList_name() bugdetail = '[场景测试]<br/>' + apitest_name + '<br/>' +\ '[错误接口名称]<br/>:' + api_name + '<br/>'+\ '[接口地址]<br/>' + api_url + '<br/>' +\ '[请求数据]<br />' + str(request) + '<br/>' +\ '[响应状态码]<br />' + str(code) + '<br/>' +\ '[预期结果]<br/>' + res_check + '<br/>' +\ '[响应数据]<br />' + str(response) + '<br/>' sql = "INSERT INTO bug_bug (bugname, bugdesc, buglevel, bugcreater, createtime, " \ "bugstatus, bugrepair) " \ "VALUES ('%s', '%s', '3', 'admin', '%s', '激活', 'admin');" % \ (bugname, pymysql.escape_string(bugdetail), pymysql.escape_string(now)) if bugname in names: pass else: Mysql().updata(sql)
def Doapi(case_list): res_flags = [] request_urls = [] responses = [] try: host = 'select value from parameter_parameter where name="host"' defult_headers = 'select value from parameter_parameter where name="headers"' host = Mysql().reslut_replace(host) defult_headers = Mysql().reslut_replace(defult_headers) except: host = None defult_headers = None for case in case_list: try: case_id = case[0] case_name = case[1] case_url = host + case[2] case_method = case[3] case_param = case[4] try: if case_param is None or case_param == '/': case_param = None else: case_param = json.loads(case_param.replace("'", '"')) except: case_param = None res_check = case[5] case_code = case[7] case_headers = case[-1] ItemAppId = case[-2] try: if case_headers is None or case_headers == '/': case_headers = defult_headers case_headers = json.loads(case_headers.replace("'", '"')) else: case_headers = json.loads(case_headers.replace("'", '"')) except: case_headers = eval(defult_headers) except Exception as e: return '测试用例格式不正确,请严格严重要求添加接口测试案例! %s' % e # get方法 if case_method.upper() == 'GET': req = requests.get(case_url, params=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code( responses_code, case_code) and compare_result(responseText) == "PASS": res_flags.append('PASS') caseWriteResult(case_id, responseText, responses_code, '1') else: res_flags.append('FAILE') caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'POST': req = requests.post(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') caseWriteResult(case_id, responseText, responses_code, '1') else: res_flags.append('FAILE') caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'PUT': req = requests.put(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') caseWriteResult(case_id, responseText, responses_code, '1') else: res_flags.append('FAILE') caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'DELETE': req = requests.delete(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') caseWriteResult(case_id, responseText, responses_code, '1') else: res_flags.append('FAILE') caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'PATCH': req = requests.patch(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') caseWriteResult(case_id, responseText, responses_code, '1') else: res_flags.append('FAILE') caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId)
def add_sellself_live_bid_auction(): url = web_host + '/admin/auction/auctionAdd' can_use_url = web_host + '/admin/product/findCanAuctionProductPage' update_url = web_host + '/admin/lot/updateLotDeliverPeople' pass_url = web_host + '/admin/auction/auctionApprPass' can_data = {'page': 1, "rows": 20} can_use_req = requests.get(can_use_url, headers=web_headers, params=can_data) can_user_product = can_use_req.json() productIdList = '' if int(can_user_product['total']) <= 5: for i in range(5): add_bid_product() can_use_req = requests.get(can_use_url, headers=web_headers, params=can_data) can_user_product = can_use_req.json() for result in can_user_product['rows']: if can_user_product['rows'].index(result) <= 10: productIdList += '%s,' % str(result['id']) else: break productIdList = productIdList.strip(',') data = { 'id': '', # 拍场ID 'version': '', # 版本号 'name': time.asctime(), # 拍场名称 'startTime': (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime('%Y-%m-%d %H:%M:%S'), # 拍场开始时间 'keyword': time.asctime(), # 拍场关键字 'auctionType': "A_T_03", # 拍场类型 'preEnter': "A_P_09", # 提前入场类型 'perActionDelay': "A_D_01", # 每次出价延时 'celebrateDuration': "A_PT_01", # 庆祝时间 'warmDuration': "A_I_01", # 预热时长 'countDownTime': "C_D_T_01", # 出价倒计时 "liveSuperAnchor": 0, # 是否超级主播。如果为False时,auctioneerId就为空默认商家 # 拍卖师--写死,对应账号:19900000008 'auctioneerId': "AUC_4", # 主播账号,写死:19900000009 'liveAuctioneerId': "", 'useGroup': 1, 'desc': f'拍场创建于:{time.asctime()}.', 'icon': Mysql().reslut_replace( f'select url from img order by rand() limit 1'), # 拍场图片地址 'productIdList': productIdList, 'noSiteMeshWapper': 'true' } req = requests.post(url, data=data, headers=web_headers) auctionId = TestMysql().reslut_replace \ (f'SELECT id FROM auction WHERE member_id=5152 AND appr_state="W" ORDER BY create_time DESC') lot_list = TestMysql().reslut_replace( f'SELECT GROUP_CONCAT(id) FROM lot WHERE auction_id={auctionId} GROUP BY auction_id' ) lot_list = lot_list.split(',') for lotId in lot_list: data = {'lotId': lotId, 'deliverPeople': "NULL"} requests.get(update_url, params=data, headers=web_headers) update_data = {'_method': 'put', 'auctionId': auctionId} requests.post(pass_url, data=update_data, headers=web_headers)
def single_scence_test(Apitest_id): sql = f'SELECT id, apiname, apiurl, apimethod, apiparamvalue, apiheaders, apiresult, apistatuscode, `apistatus`, Apitest_id ' \ f'from case_apistep where Apitest_id={Apitest_id} order by id' apis = Mysql().sql_result(sql) DoScneceapi(apis)
import os import pymysql import requests, time, sys import json import random, re import hashlib import datetime, time from apitest.mysql import Mysql, TestMysql curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(rootPath) PATH = lambda p: os.path.abspath(os.path.join(os.path.dirname(__file__), p)) host = Mysql().reslut_replace( f'select value from parameter_parameter where name="host"') web_host = Mysql().reslut_replace( f'select value from parameter_parameter where name="web_host_1"') headers = Mysql().reslut_replace( 'select value from parameter_parameter where name="headers"') user = Mysql().reslut_replace( 'select value from parameter_parameter where name="web_admin"') password = Mysql().reslut_replace( 'select value from parameter_parameter where name="web_admin_password"') web_headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': f'{web_host}/admin/login', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
def single_api_test(caseId): request_urls = [] responses = [] try: host = 'select value from parameter_parameter where name="host"' defult_headers = 'select value from parameter_parameter where name="headers"' host = Mysql().reslut_replace(host) defult_headers = Mysql().reslut_replace(defult_headers) except: host = None defult_headers = None sql = f"SELECT id, `apiname`, apiurl, apimethod, apiparamvalue, apiresult, `apistatus`, apistatuscode," \ f" ItemsApplication_id, apiheaders from case_singeapi where id={caseId}" case = Mysql().sql_result(sql)[0] try: case_id = case[0] case_name = case[1] case_url = host + case[2] case_method = case[3] case_param = case[4] try: if case_param is None or case_param == '/': case_param = None else: case_param = json.loads(case_param.replace("'", '"')) except: case_param = None res_check = case[5] case_code = case[7] case_headers = case[-1] ItemAppId = case[-2] try: if case_headers is None or case_headers == '/': case_headers = defult_headers case_headers = json.loads(case_headers.replace("'", '"')) else: case_headers = json.loads(case_headers.replace("'", '"')) except: case_headers = eval(defult_headers) except Exception as e: return '测试用例格式不正确,请严格严重要求添加接口测试案例! %s' % e # get方法 if case_method.upper() == 'GET': req = requests.get(case_url, params=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): caseWriteResult(case_id, responseText, responses_code, '1') else: caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'POST': req = requests.post(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): caseWriteResult(case_id, responseText, responses_code, '1') else: caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'PUT': req = requests.put(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): caseWriteResult(case_id, responseText, responses_code, '1') else: caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'DELETE': req = requests.delete(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): caseWriteResult(case_id, responseText, responses_code, '1') else: caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId) if case_method.upper() == 'PATCH': req = requests.patch(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): caseWriteResult(case_id, responseText, responses_code, '1') else: caseWriteResult(case_id, responseText, responses_code, '0') writeBug(case_id, case_name, case_url, case_param, responses_code, responseText, res_check, ItemAppId)
def DoScneceapi(case_list): res_flags = [] request_urls = [] responses = [] try: host = 'select value from parameter_parameter where name="host"' defult_headers = 'select value from parameter_parameter where name="headers"' host = Mysql().reslut_replace(host) defult_headers = Mysql().reslut_replace(defult_headers) except: host = None defult_headers = None for case in case_list: try: case_id = case[0] case_name = case[1] case_url = host + case[2] case_method = case[3] case_param = case[4] Apitest_id = case[-1] Apitest_name = Mysql().reslut_replace( f'select apitestname from case_apitest where id={Apitest_id}') try: if case_param is None or case_param == '/': case_param = None else: case_param = json.loads( case_param.replace("'", '"').replace('”', '"')) except: case_param = None res_check = case[6] case_code = case[7] case_headers = case[5] try: if case_headers is None or case_headers == '/': case_headers = defult_headers case_headers = json.loads(case_headers.replace("'", '"')) else: case_headers = json.loads(case_headers.replace("'", '"')) except: case_headers = eval(defult_headers) except Exception as e: return '测试用例格式不正确,请严格严重要求添加接口测试案例! %s' % e # get方法 if case_method.upper() == 'GET': req = requests.get(case_url, params=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') else: res_flags.append('FAILE') reason = f'接口:{case_name}调用出错。\n' \ f'错误代码:实际响应code:{responses_code};预期响应code:{case_code}\n' \ f'预期结果:{res_check}\n' \ f'实际响应结果:{responseText}' caseWriteResult_scence(reason, '0') writeScenceBug(Apitest_name, case_name, case_url, case_param, responses_code, responseText, res_check) break if case_method.upper() == 'POST': req = requests.post(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') else: res_flags.append('FAILE') reason = f'接口:{case_name}调用出错。\n' \ f'错误代码:实际响应code:{responses_code};预期响应code:{case_code}\n' \ f'预期结果:{res_check}\n' \ f'实际响应结果:{responseText}' caseWriteResult_scence(reason, '0') writeScenceBug(Apitest_name, case_name, case_url, case_param, responses_code, responseText, res_check) break if case_method.upper() == 'PUT': req = requests.put(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') else: res_flags.append('FAILE') reason = f'接口:{case_name}调用出错。\n' \ f'错误代码:实际响应code:{responses_code};预期响应code:{case_code}\n' \ f'预期结果:{res_check}\n' \ f'实际响应结果:{responseText}' caseWriteResult_scence(reason, '0') writeScenceBug(Apitest_name, case_name, case_url, case_param, responses_code, responseText, res_check) break if case_method.upper() == 'DELETE': req = requests.delete(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') else: res_flags.append('FAILE') reason = f'接口:{case_name}调用出错。\n' \ f'错误代码:实际响应code:{responses_code};预期响应code:{case_code}\n' \ f'预期结果:{res_check}\n' \ f'实际响应结果:{responseText}' caseWriteResult_scence(reason, '0') writeScenceBug(Apitest_name, case_name, case_url, case_param, responses_code, responseText, res_check) break if case_method.upper() == 'PATCH': req = requests.patch(case_url, data=case_param, headers=case_headers) responses_code = req.status_code responseText = req.text if compare_code(responses_code, case_code) and compare_result( responseText, res_check): res_flags.append('PASS') else: res_flags.append('FAILE') reason = f'接口:{case_name}调用出错。\n' \ f'错误代码:实际响应code:{responses_code};预期响应code:{case_code}\n' \ f'预期结果:{res_check}\n' \ f'实际响应结果:{responseText}' caseWriteResult_scence(reason, '0') writeScenceBug(Apitest_name, case_name, case_url, case_param, responses_code, responseText, res_check) break if "FAILE" not in res_flags: caseWriteResult_scence("PASS", '1')