def __init__(self, params_interface): """ 初始化数据 :param params_interface: 接口请求参数 """ self.params_interface = params_interface # 接口入参 self.id_case = params_interface.get('id') # 测试用例ID self.result_list_response = [] # 定义用来存储 参数集的空列表 self.params_to_compare = params_interface.get( 'params_to_compare') # 定义参数完整性的预期结果 self.db = OperationDbInterface()
class AnalyseData(object): """ 定义对接口测试数据进行分析的类,包含的方法有: 1.导出测试数据到Excel中 """ def __init__(self): self.field = config.filed_excel # 初始化配置文件 self.db = OperationDbInterface(link_type=1) # 初始化数据库操作类,返回元组 def export2excel(self, name_export): """ :param name_export: 待导出的接口名称,列表形式 :return: """ counts_export = len(name_export) # 导出总数 fail_export = [] # 导出失败接口列表 try: src = open_workbook(config.src_path + '/report/report_module.xls', formatting_info=True) destination = copy(src) dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 当前的时间戳 filepath = config.src_path + '/report/' + str(dt) + '.xls' destination.save(filepath) # 保存模板表格到新的目录下 for name_interface in name_export: cases_interface = self.db.select_all("SELECT * FROM case_interface " "WHERE case_status = 1 " "and name_interface = '%s'" % name_interface) if len(cases_interface.get('data')) != 0 and cases_interface.get('code') == '0000': src = open_workbook(filepath, formatting_info=True) destination = copy(src) sheet = destination.add_sheet(name_interface, cell_overwrite_ok=True) for col in range(0, len(self.field)): sheet.write(0, col, self.field[col]) # 获取并写入数据段信息到Sheet中 for row in range(1, len(cases_interface['data']) + 1): for col in range(0, len(self.field)): sheet.write(row, col, '%s' % cases_interface['data'][row - 1][col]) # 写数据到对应Excel表中 destination.save(filepath) elif len(cases_interface['data']) == 0 and cases_interface['code'] == '0000': fail_export.append(name_interface) else: fail_export.append(name_interface) result = {'code': '0000', 'message': '导出总数: %s , 失败数: %s' % (counts_export, len(fail_export)), 'data': fail_export} except Exception as e: MyLog.error(e) result = {'code': '9999', 'message': '导出过程异常|导出总数: %s , 失败数: %s' % (counts_export, len(fail_export)), 'data': fail_export} finally: return result
class ExcelToDB(object): def __init__(self): self.db = OperationDbInterface() self.table_name = '' def setExcelpath(self, file_path): self.filepath = file_path def intoMysql(self, list=[]): excel_op = ReadFromExcel(self.filepath) datas_list = excel_op.readall() params_list = [] for data in datas_list: name_interface = data.get('name_interface') name_case = data.get('name_case') exe_mode = data.get('exe_mode') url_interface = data.get('url_interface') header_interface = data.get('header_interface') params_interface = data.get('params_interface') check_level = data.get('check_level') extra = data.get('extra') code_to_compare = data.get('code_to_compare') code_expect = data.get('code_expect') params_to_compare = data.get('params_to_compare') param = (name_interface, name_case, exe_mode, url_interface, header_interface, params_interface, check_level, extra, code_to_compare, code_expect, params_to_compare) condition = "INSERT INTO case_interface (" \ "name_interface," \ "name_case," \ "exe_mode," \ "url_interface," \ "header_interface," \ "params_interface," \ "check_level," \ "extra," \ "code_to_compare," \ "code_expect," \ "params_to_compare)" \ "VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" params_list.append(param) return self.db.insert_data(condition=condition, params=params_list)
def __init__(self): self.db = OperationDbInterface() self.cases_to_run = [] self.cache = Cache(maxsize=256, ttl=0, timer=time.time)
class Run(object): def __init__(self): self.db = OperationDbInterface() self.cases_to_run = [] self.cache = Cache(maxsize=256, ttl=0, timer=time.time) def get_all_cases(self): """ 获取所有测试用例 :return: [] """ sql = 'select * from case_interface' print(self.db.select_all(sql)) def get_one_case(self, condition): """ 获取一条测试用例 :return: [] """ def get_cases_for_run(self): """ 获取要执行的测试用例 :return: """ pass def execute_test_case(self, *arg): """ 执行测试用例 :param arg: :return: """ test_interface = RequestInterface() sql = "SELECT * FROM `case_interface` WHERE case_status = 1" result = self.db.select_all(sql) if result.get('code') == '0000' and result.get('data'): MyLog.debug('获取执行接口成功') datas = result.get('data') for temp_case_interface in datas: obj = extraDB(temp_case_interface, self.cache) params_interface = obj.replace() # 执行测试前重构测试数据 url_interface = params_interface.get('url_interface') id_case = temp_case_interface.get('id') name_interface = temp_case_interface.get('name_interface') name_case = temp_case_interface.get('name_case') headdata = ast.literal_eval(params_interface.get('header_interface')) type_interface = params_interface.get('exe_mode') if url_interface != '' and headdata != '' and type_interface != '': temp_level_check = temp_case_interface.get('check_level') # 检查级别 result_http_respones = test_interface.http_request(url_interface, headdata, params_interface.get('params_interface'), type_interface) print(result_http_respones) MyLog.debug("用例返回消息:{result}".format(result=result_http_respones.get('data'))) obj.setvar(result_http_respones.get('data')) self.db.op_sql("UPDATE case_interface SET result_interface = '%s' where id = %s " % (result_http_respones.get('data'), id_case)) # 将返回包数据写入用例表 if result_http_respones['code'] == '0000' and len(result_http_respones['data']) != 0: base_compare = CompareParam(temp_case_interface) if '0' in list(temp_level_check): # 执行关键值参数检查 result_compare_code = base_compare.compare_code(result_http_respones.get('data')) MyLog.debug('用例编号:%s|检查级别:关键字参数值|接口名称:%s|用例名称:%s|提示信息:%s \n' % (id_case, name_interface, name_case, result_compare_code['message'])) if '1' in list(temp_level_check): # 执行参数完整性检查 result_compare_params_complete = base_compare.compare_params_complete( result_http_respones.get('data')) MyLog.debug('用例编号:%s|检查级别:参数完整性|接口名称:%s|用例名称:%s|提示信息:%s \n' % (id_case, name_interface, name_case, result_compare_params_complete['message'])) elif len(result_http_respones['data']) == 0: MyLog.debug('接口名称: %s|信息错误:获取用例数据为空,请检查用例\n' % name_interface) else: MyLog.debug('接口名称: %s|信息错误:获取用例数据失败' % name_interface)
class CompareParam(object): def __init__(self, params_interface): """ 初始化数据 :param params_interface: 接口请求参数 """ self.params_interface = params_interface # 接口入参 self.id_case = params_interface.get('id') # 测试用例ID self.result_list_response = [] # 定义用来存储 参数集的空列表 self.params_to_compare = params_interface.get( 'params_to_compare') # 定义参数完整性的预期结果 self.db = OperationDbInterface() def compare_code(self, result_interface): """ :param result_interface: HTTP返回数据包 :return: ,返回信息message,数据data """ try: if isinstance(result_interface, str) and result_interface.startswith('{'): temp_result_interface = json.loads( result_interface) # 将字符类型转换为字典类型 temp_code_to_compare = self.params_interface.get( 'code_to_compare') if temp_code_to_compare in temp_result_interface.keys(): if str(temp_result_interface.get( temp_code_to_compare)) == str( self.params_interface.get('code_expect')): result = { 'code': '0000', 'message': '关键字参数值相同', 'data': [] } print( "############", "UPDATE case_interface set code_actual=%s," "result_code_compare =%s where id =%s" % (str( temp_result_interface.get(temp_code_to_compare) ).replace("'", "\\'"), 1, self.id_case)) self.db.op_sql( "UPDATE case_interface set code_actual=%s," "result_code_compare =%s where id =%s" % (str( temp_result_interface.get(temp_code_to_compare) ).replace("'", "\\'"), 1, self.id_case)) elif str(temp_result_interface.get( temp_code_to_compare)) != str( self.params_interface.get('code_expect')): result = { 'code': '1003', 'message': '关键字参数值不相同', 'data': [] } print( "############", "UPDATE case_interface set code_actual='%s'," "result_code_compare =%s where id =%s" % (str( temp_result_interface.get(temp_code_to_compare) ).replace("'", "\\'"), 0, self.id_case)) self.db.op_sql( "UPDATE case_interface set code_actual='%s'," "result_code_compare =%s where id =%s" % (str( temp_result_interface.get(temp_code_to_compare) ).replace("'", "\\'"), 0, self.id_case)) else: result = { 'code': '1002', 'message': '关键字参数值比较出错', 'data': [] } self.db.op_sql( "UPDATE " " set code_actual='%s'," "result_code_compare =%s where id =%s" % (temp_result_interface.get(temp_code_to_compare), 3, self.id_case)) else: result = { 'code': '1001', 'message': '返回包数据无关键字参数', 'data': [] } self.db.op_sql( "UPDATE case_interface set result_code_compare =%s where id =%s" % (2, self.id_case)) else: result = {'code': '1000', 'message': '返回包格式不合法', 'data': []} self.db.op_sql( "UPDATE case_interface set result_code_compare =%s where id =%s" % (4, self.id_case)) except Exception as e: result = {'code': '9999', 'message': '关键字参数值比较异常', 'data': []} self.db.op_sql( "UPDATE case_interface set result_code_compare =%s where id =%s" % (9, self.id_case)) MyLog.error(e) finally: return result def get_compare_params(self, result_interface): """ :param result_interface: HTTP返回包数据 :return: 返回码code,返回信息message,数据data """ try: if result_interface.startswith('{') and isinstance( result_interface, str): temp_result_interface = json.loads( result_interface) # 将字符串类型转换为字典类型 self.result_list_response = temp_result_interface.keys() result = { 'code': '0000', 'message': '成功', 'data': self.result_list_response } else: result = { 'code': '1000', 'message': '返回包格式不合法', 'data': self.result_list_response } except Exception as e: result = {'code': '9999', 'message': '处理数据异常', 'data': []} MyLog.error(e) finally: return result def compare_params_complete(self, result_interface): """ 定义参数完整性的比较方法,将传参值与__recur_params 方法返回结果进行比较 :param result_interface: :return: 返回码Code,返回信息Message,数据data """ try: temp_compare_params = self.__recur_params__( result_interface) # 获取返回包的参数集 if temp_compare_params.get('code') == '0000': temp_result_list_response = temp_compare_params.get( 'data') # 获取接口返回参数去重列表 if self.params_to_compare.startswith('[') and isinstance( self.params_to_compare, str): # 判断测试用例列表中预期结果集是否为列表 print('debug', self.params_to_compare) list_params_to_compare = eval( self.params_to_compare) # 将数据库中的unicode编码数据转换为列表 if set(list_params_to_compare).issubset( set(temp_result_list_response)): # 判断集合包含关系 result = { 'code': '0000', 'message': '参数完整性比较一致', 'data': [] } self.db.op_sql( "UPDATE case_interface set params_actual=\"%s\"," "result_params_compare =%s where id =%s" % (temp_result_list_response, 1, self.id_case)) else: result = { 'code': '3001', 'message': '实际结果中元素不都在预期结果中', 'data': [] } self.db.op_sql( "UPDATE case_interface set params_actual=\"%s\"," "result_params_compare =%s where id =%s" % (temp_result_list_response, 0, self.id_case)) else: result = { 'code': '4001', 'message': '用例中待比较参数集错误', 'data': self.params_to_compare } else: result = { 'code': '2001', 'message': '调用__recur_params__方法返回错误', 'data': self.params_to_compare } self.db.op_sql( "UPDATE case_interface set result_params_compare =%s where id =%s" % (2, self.id_case)) except Exception as e: result = {'code': '9999', 'message': '参数完整性比较异常', 'data': []} self.db.op_sql( "UPDATE case_interface set result_params_compare =%s where id =%s" % (9, self.id_case)) MyLog.error(e) return result def __recur_params__(self, result_interface): """ 定义递归操作,将接口返回数据中的参数名写入列表中(去重) :return: """ try: if isinstance(result_interface, str) and result_interface.startswith('{'): temp_result_interface = json.loads(result_interface) self.__recur_params__(temp_result_interface) elif isinstance(result_interface, dict): # 入参是字典 for param, value in result_interface.items(): self.result_list_response.append(param) if isinstance(value, list): for param in value: self.__recur_params__(param) elif isinstance(value, dict): self.__recur_params__(value) else: continue else: pass except Exception as e: MyLog.error(e) result = {'code': '9999', 'message': '数据处理异常', 'data': []} return result return { 'code': '0000', 'message': '成功', 'data': list(set(self.result_list_response)) }
for param in value: self.__recur_params__(param) elif isinstance(value, dict): self.__recur_params__(value) else: continue else: pass except Exception as e: MyLog.error(e) result = {'code': '9999', 'message': '数据处理异常', 'data': []} return result return { 'code': '0000', 'message': '成功', 'data': list(set(self.result_list_response)) } if __name__ == '__main__': sql = "select * from case_interface where name_interface = 'getIpInfo.php' and id = 1" parma_interface = OperationDbInterface().select_one(sql) print(parma_interface) resul_interface = parma_interface.get('data').get('result_interface') print(parma_interface.get('data')) test_compara_parma = CompareParam(parma_interface['data']) result_compare_params_complete = test_compara_parma.compare_params_complete( resul_interface) print(result_compare_params_complete)
def __init__(self): self.db = OperationDbInterface() self.table_name = ''
def __init__(self): self.field = config.filed_excel # 初始化配置文件 self.db = OperationDbInterface(link_type=1) # 初始化数据库操作类,返回元组
for col in range(0, len(self.field)): sheet.write(0, col, self.field[col]) # 获取并写入数据段信息到Sheet中 for row in range(1, len(cases_interface['data']) + 1): for col in range(0, len(self.field)): sheet.write(row, col, '%s' % cases_interface['data'][row - 1][col]) # 写数据到对应Excel表中 destination.save(filepath) elif len(cases_interface['data']) == 0 and cases_interface['code'] == '0000': fail_export.append(name_interface) else: fail_export.append(name_interface) result = {'code': '0000', 'message': '导出总数: %s , 失败数: %s' % (counts_export, len(fail_export)), 'data': fail_export} except Exception as e: MyLog.error(e) result = {'code': '9999', 'message': '导出过程异常|导出总数: %s , 失败数: %s' % (counts_export, len(fail_export)), 'data': fail_export} finally: return result if __name__ == '__main__': names_export = OperationDbInterface(link_type=0).select_one("SELECT value_config from config_total WHERE `status` =1 AND key_config = 'name_export'") if names_export['code'] =='0000': print(names_export['data']['value_config']) temp_export = eval(names_export['data']['value_config']) s = AnalyseData().export2excel(temp_export) print(s)
# coding=utf8 # import re import pytest import allure from common.opmysql import OperationDbInterface # from common.analyse import AnalyseData from common.request import RequestInterface from common.compare import CompareParam # from public import config from common.Log import MyLog cases_list = [ ] # 测试用例集,里面放tuple[(name_interface1,case1),(name_interface2,case2)] base_request = RequestInterface() base_db = OperationDbInterface() module_execute = base_db.select_all( "SELECT value_config from config_total " "WHERE key_config = 'exe_setup' and `status` = 1") # 获取待执行接口数据 if len(module_execute.get('data')) != 0 and module_execute.get( 'code') == '0000': for module_execute_one in module_execute.get('data'): temp_module_execute = eval(module_execute_one.get('value_config')) for temp_name_interface, condition in temp_module_execute.items(): # print("###########开始执行接口:%s############\n" % temp_name_interface) temp_level_check = condition.get('level_check') # 检查级别 temp_level_exe = tuple(condition.get('level_exe')) # 执行级别 data_case_interface = base_db.select_all( "SELECT * FROM case_interface WHERE " "case_status = 1 AND " "name_interface = '%s' AND exe_level in %s" %
MyLog.debug('用例发送消息URL:%s\n' '用例发送消息头:%s\n' '用例发送消息体:%s\n' % (interface_parm, headerdata, interface_parm)) else: result = {'code': '1000', 'message': '请求类型错误', 'data': []} except Exception as e: # traceback.print_exc() MyLog.error(e) return result if __name__ == '__main__': test_interface = RequestInterface() obj = OperationDbInterface(host_db='127.0.0.1', user_db='root', pwd_db='123456', name_db='test_interface', port_db=3306, link_type=0) sen_sql = "SELECT exe_mode,url_interface,header_interface,params_interface,code_expect from case_interface WHERE name_interface='getIpInfo.php' AND id=1; " parmams_interface = obj.select_one(sen_sql) print(parmams_interface) if parmams_interface.get('code') == '0000': # print(parmams_interface) url_interface = parmams_interface.get('data').get('url_interface') # print(url_interface) print(parmams_interface.get('data').get('header_interface')) headdata = ast.literal_eval(parmams_interface.get('data').get('header_interface')) # 将unicode转换为字典 type_interface = parmams_interface.get('data').get('exe_mode') # print((headdata)) if url_interface != '' and headdata != '' and parmams_interface != '' and type_interface != '': print('yes')
# coding=utf8 import re from common.opmysql import OperationDbInterface from common.analyse import AnalyseData from common.request import RequestInterface from common.compare import CompareParam from public import config from common.Log import MyLog if __name__ == '__main__': base_request = RequestInterface() base_db = OperationDbInterface() try: print("开始接口自动化程序,请选择操作类型(0|执行用例:1|导出测试结果)") value_input = str(input('请输出操作类型:')) while not re.search(r'^[0-1]$', value_input): print('请输入正确的操作类型(0|执行用例:1|导出测试结果)') value_input = str(input('请输出操作类型:')) else: if value_input == '0': print('你输入的是:0|执行测试用例') module_execute = base_db.select_all( "SELECT value_config from config_total " "WHERE key_config = 'exe_setup' and `status` = 1" ) # 获取待执行接口数据 if len(module_execute.get('data')) != 0 and module_execute.get( 'code') == '0000': for module_execute_one in module_execute.get('data'): temp_module_execute = eval( module_execute_one.get('value_config')) for temp_name_interface, condition in temp_module_execute.items(