class TestSql: test_db = opmysql.OperationDbInterface() api_url = 'https://jsonmock.hackerrank.com/api/football_matches' def test_insert_data(self): """ 向表case_interface添加记录,为添加一条api测试用例 :return: assert 添加成功 """ sql_insert = "INSERT INTO case_interface(" \ "name_interface,exe_mode,url_interface,header_interface,params_interface,result_interface," \ "code_to_compare,code_expect, params_to_compare, params_actual) " \ "VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" result = self.test_db.insert_data(sql_insert, [('HackerRank_football', 'get', self.api_url, 'temp', 'year=2011&team1=Barcelona&page=1', 'temp', 'code', '200', 'page', 'temp')]) assert result['code'] == '0000'
class TestHackerRank: test_db = opmysql.OperationDbInterface() request_url = 'https://jsonmock.hackerrank.com/api/football_matches' # Todo: to be updated... def test_page_number(self): # 暂且把case_interface当作test case.简单测试,数据库其它字段待修改 sen_sql = "select * from case_interface where id=2" expected_page_num = int( self.test_db.select_one(sen_sql)['data']['code_expect']) response = requests.get(self.request_url, params={ "year": 2011, "team1": 'Barcelona', "page": 1 }) actual_page_num = int(response.json()['page']) assert actual_page_num == expected_page_num
import json, os, logging from common import opmysql from public import config operation_db = opmysql.OperationDbInterface() #实例化测试数据库操作类 class CompareParam(object): #初始化数据 def __init__(self, params_interface): self.params_interface = params_interface #接口入参 self.id_case = params_interface['id'] self.result_list_response = [] #定义用来存储参数集的空列表 self.params_to_compare = params_interface[ 'params_to_compare'] #定义参数完整性的预期结果 #定义关键参数值code比较 def compare_code(self, result_interface): try: if result_interface.startswith('{') and isinstance( result_interface, str): temp_result_interface = json.loads( result_interface) #将字符类型转换成字典类型 temp_code_to_compare = self.params_interface[ 'code_to_compare'] #获取带比较code值 if temp_code_to_compare in temp_result_interface.keys(): if str(temp_result_interface['code']) == str( self.params_interface['code_expect']): result = { 'code': '0000', 'message': '关键字参数值相同', 'data': []
from xlrd import open_workbook from xlutils.copy import copy import os, logging, datetime from public import config from common import opmysql operation_db = opmysql.OperationDbInterface(link_type=1) #实例化自动化测试数据库操作类 class AnalyseData(object): ''' 定义对解救测试数据进行分析的类,包括的方法有: 1.导出测试数据到EXCEL中 ''' def __init__(self): self.field = config.field_excel #初始化配置文件 def export2excel(self, names_export): ''':param names_export:带导出的接口名称,列表形式''' counts_export = len(names_export) #导出总数 fail_export = [] #导出失败接口名列表 try: src = open_workbook(config.src_path + '/report/report_module.xls', formatting_info=True) #获取要写入EXCEL表格的地址 destination = copy(src) #复制一份 excel表格 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 names_export: cases_interface = operation_db.select_all( "select * from case_interface WHERE case_status=1 AND name_interface='%s'" % (name_interface))
from common import request, opmysql, analyse, compare import logging from public import config import re base_request = request.RequestInterface() #实例化HTTP请求 base_operationdb_interface = opmysql.OperationDbInterface() #实例化接口测试数据库操作类 try: print("开始接口自动化程序,请选择操作类型(0|执行用例;1:导出测试结果)") value_input = input('请输入操作类型:') #该处输入0时,调试窗口是str,而可视化窗口是int while not re.search(r'^[0-1]$', value_input): #判断不是0和1的数字 print("请输入正确的操作类型(0|执行用例;1:导出测试结果)") value_input = str(input('请输入操作类型:')) else: if value_input == '0': print('您输入的是:0|执行测试用例') module_excute = base_operationdb_interface.select_all( "select value_config from config_total WHERE key_config='exe_setup'AND status=1" ) #获取待执行的接口数据 if len(module_excute['data'] ) != 0 and module_excute['code'] == '0000': for module_excute_one in module_excute['data']: temp_module_excute = eval( module_excute_one['value_config']) #每个接口的字典数据 for temp_name_interface, condition in temp_module_excute.items( ): print( '######################开始接口测试:%s#######################\n' % (temp_name_interface)) temp_level_check = condition['level_check'] #检查级别 temp_level_exe = tuple(condition['level_exe']) #执行级别 data_case_interface = base_operationdb_interface.select_all(
""" 定义导出数据库数据到Excel的类。 如要使用excel 2007以后版本,可使用openpyxl模块 init方法初始化获取配置文件数据 export2excel为主方法 """ from xlrd import open_workbook from xlutils.copy import copy import logging, datetime from public import config from common import opmysql operation_db = opmysql.OperationDbInterface(link_type=1) class AnalyseData(object): """ 定义对接口测试数据进行分析的类 """ def __init__(self): self.field = config.field_excel def export2excel(self, names_export): """ 定义导出指定数据到excel :param names_export: 待导出的接口名称,列表形式 :return: """ counts_export = len(names_export) # 导出总数 fail_export = [] # 导出失败接口名列表
""" 定义数据比较方法 compare_param 对外的参数比较类 compare_code 关键参数值比较方法 compare_params_complete参数完整性比较 get_compare_params 获得返回包数据去重集合 recur_params 递归操作,辅助去重 """ import json import logging from common import opmysql from public import config operation_db = opmysql.OperationDbInterface() class CompareParam(object): def __init__(self, params_interface): self.params_interface = params_interface self.id_case = params_interface['id'] self.result_list_response = [] self.params_to_compare = params_interface['params_to_compare'] def compare_code(self, result_interface): """ 关键参数值code比较 :param result_interface: 返回包数据 :return: 返回码code 返回信息message 数据data """
logging.basicConfig( filename=config.src_path + '/log/syserror.log', level=logging.DEBUG, format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s' ) logger = logging.getLogger(__name__) logger.exception(error) return result if __name__ == "__main__": test_interface = RequestInterface() test_db = opmysql.OperationDbInterface(host_db='127.0.0.1', user_db='test_user1', passwd_db='test_user1', name_db='test_interface', port_db=3306, link_type=0) sen_sql = "select exe_mode,url_interface,header_interface, params_interface " \ "from case_interface " \ "where name_interface='getIpInfo.php' and id=1" params_interface = test_db.select_one(sen_sql) # 如果查询成功,取出返回字典中的data(查询results),按数据库字段赋值给对应变量 if params_interface['code'] == '0000': url_interface = params_interface['data']['url_interface'] # 将unicode转换成字典 temp = params_interface['data']['header_interface'] headerdata = eval(params_interface['data']['header_interface']) param_interface = params_interface['data']['params_interface'] type_interface = params_interface['data']['exe_mode']
try: if request_type =='get' or request_type=='GET': result=self.__http_get(interface_url,headerdata,interface_param) elif request_type=='post' or request_type=='POST': result=self.__http_post(interface_url,headerdata,interface_param) else: result ={'code':'1000','message':'请求类型错误','data':request_type} except Exception as error: result={'code':'9999','message':'系统异常','data':[]} logging.basicConfig(filename=config.src_path + '/log/syserror.log',level=logging.DEBUG,format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)') logger = logging.getLogger(__name__) logger.exception(error) return result if __name__ = "__main__": test_interface=RequestInterface() #实例化http请求类 test_db = opmysql.OperationDbInterface(host_db='192.168.1.110',user_db='root',passwd_db='root',name_db='test_interface',port_db=3306,link_type=0) #实例化mysql处理类 sen_sql ="select exe_mode,url_interface,header_interface,params_interface from case_interface where name_interface='getIpInfo' and id=1" params_interface=test_db.select_one(sen_sql) if params_interface['code']=='0000': url_interface=params_interface['data']['url_interface'] temp=params_interface['data']['header_interface'] print(temp) headerdata=eval(params_interface['data']['header_interface']) #unicode 转换成字典 params_interface=params_interface['data']['params_interface'] type_interface=params_interface['data']['exe_mode'] if url_interface!='' and headerdata!='' and params_interface!='' and type_interface!='': result=test_interface.http_request(interface_url=url_interface,headerdata=headerdata,interface_param=params_interface,request_type=type_interface) if result['code']=='0000': request_resp=result['data'] print("处理http请求成功,返回数据是:%s" %request_resp)
# url_interface = params_interface['data']['url_interface'] # temp = params_interface['data']['header_interface'] # header_data = eval(params_interface['data']['header_interface']) # param_interface = params_interface['data']['params_interface'] # # print(params_interface) # type_interface = params_interface['data']['exe_mode'] # # print(params_interface) # if url_interface != '' and header_data != '' and params_interface != '' and type_interface != '': # result = test_interface.http_request(interface_url=url_interface, header_data=header_data, # interface_param=params_interface, request_type=type_interface) # if result['code'] == '0000': # result_resp = result['data'] # test_db.op_sql("update case_interface set result_interface='%s' where id=1" % result_resp) # 更新结果 # print('处理http请求成功,返回数据是: %s' % result_resp) # else: # print('处理请求失败') # else: # print('测试数据中有空值') # else: # print('获取接口测试用例数据失败') if __name__ == '__main__': r = RequestInterface() resp = r.http_request(interface_url='http://ip.taobao.com/service/getIpInfo.php', header_data={'HOST': 'ip.taobao.com'}, interface_param='ip=63.223.108.4', request_type='GET') res = resp['data'] test_db = opmysql.OperationDbInterface(host_db='10.2.12.132', user_db='root', password_db='123456', name_db='test_interface', port_db=3306, link_type=0) test_db.op_sql("update case_interface set result_interface='%s' where id=4".format(res))
print(result) elif request_type=='post' or request_type=='POST': result=self.__http_post(interface_url,headerdata,interface_param) else: result={'code':'1000','message':'请求类型出错','data':request_type} except Exception as error: result={'code':'9999','message':'系统异常','data':[]} logging.basicConfig(filename=config.src_path + '/log/syserror.log', level=logging.DEBUG, format='%(asctime)s%(filename)s[line:%(lineno)d]' '%(levelname)s%(message)s') logger = logging.getLogger(__name__) logging.exception(error) return result if __name__=='__main__': test_interface=RequestInterface() test_db=opmysql.OperationDbInterface( host_db="127.1.0.1", user_db="root", passwd_db="root", name_db="case_interface", port_db=3306, link_type=0) sen_sql="select exe_mode,url_interface,header_interface,params_interface from case_interface WHERE name_interface='getIpInfo.php'and id='1'" params_interface=test_db.select_one(sen_sql) if params_interface['code']=='0000': url_interface=params_interface['data']['url_interface'] temp=params_interface['data']['header_interface'] headerdata=eval(params_interface['data']['header_interface']) #将unicode转换成字典 type_interface = params_interface['data']['exe_mode'] params_interface=params_interface['data']['params_interface'] if url_interface!='' and headerdata!='' and params_interface!='' and type_interface!='': result=test_interface.http_request(interface_url=url_interface,headerdata=headerdata,interface_param=params_interface,request_type=type_interface) if result['code']=='0000': result_resp=result['data'] test_db.op_sql("update case_interface set result_interface='%s' WHERE id=1" %result_resp) print("处理HTTP请求成功,返回数据是:%s" %result_resp) else:
filename=config.src_path + '/log/syserror.log', level=logging.DEBUG, format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s' ) logger = logging.getLogger(__name__) logger.exception(error) return result if __name__ == "__main__": test_interface = RequestInterface() #实例化HTTP请求类 #实例化MYSQL处理类 test_db = opmysql.OperationDbInterface(host_db='127.0.0.1', user_db='root', password_db='hjp123456H.', name_db='test_interface', port_db=3306, link_type=0) sen_sql = "select exe_mode,url_interface,header_interface,params_interface from case_interface where name_interface='getIpInfo.php' and id=1" # sen_sql = "select exe_mode,url_interface,header_interface,params_interface from case_interface where name_interface='testtasks' and id=2" params_interface = test_db.select_one(sen_sql) # print(params_interface) if params_interface['code'] == '0000': url_interface = params_interface['data']['url_interface'] temp = params_interface['data']['header_interface'] headerdata = eval( params_interface['data']['header_interface']) #将unicode转化成字典 param_interface = params_interface['data']['params_interface'] type_interface = params_interface['data']['exe_mode'] if url_interface != '' and headerdata != '' and param_interface != '' and type_interface != '': result = test_interface.http_request(