def __init__(self, url_json, module=1): global title_list, json_path self.url_json = url_json r = requests.get(self.url_json).json() self.title = r['info']['title'] print('ssssssss----{}'.format(r)) logger.info('标题' + self.title) write_data(r, '{}.json'.format(self.title)) # swagger 完整大文件 self.interface_params = {} self.row = 1 # 写入excel起始行数 self.num = 1 # 初始化case id if self.check_data(r): # self.json_path = os.path.abspath( # os.path.dirname( # os.path.dirname(__file__))) + '\\common' + '\\report' + '\\{}_data.json'.format( # str(module)) # json file path,执行多个url的情况,区分生成的json文件 self.data = r['paths'] # paths中的数据是有用的 title_list.append(self.title) # 创建excel 文件 self.excel_path = os.path.dirname(__file__) + '/report/' wt = Write_excel(self.excel_path) wt.create_excelFile() else: print("swagger 请求错误!")
def assert_in(asserqiwang, fanhuijson): if len(asserqiwang.split('=')) > 1 or len(asserqiwang.split(':')) > 1: data = asserqiwang.split('&') if '=' in asserqiwang: result = dict([(item.split('=')) for item in data]) value1 = ([(str(key)) for key in fanhuijson.values()]) value2 = ([(str(value)) for value in result.values()]) if set(value2) < set(value1): return {'code': 0, 'result': fanhuijson['results']} else: return {'code': 1, 'result': fanhuijson} else: result = dict([(item.split(':')) for item in data]) value2 = assert_in_plus(result) for xx, yy in value2.items(): if xx in fanhuijson.keys(): if yy == fanhuijson[xx]: return {'code': 0, 'result': fanhuijson['results']} else: return {'code': 1, 'result': fanhuijson} else: return {'code': 1, 'result': fanhuijson} else: logger.info('请填写Case预期') return {'code': 2, 'result': None}
def load_swagger_data(self): ''' :param SourceName: 服务名称list(为空返回所有) :return: 全量服务列表+地址||入参服务列表+地址 ''' self.swagger_cloud = r'https://api-uat.daoyitong.com/cloud' self.swagger_resource = 'https://api-uat.daoyitong.com/cloud/swagger-resources' reponese = requests.get(self.swagger_resource).json() for sourcename in reponese: self.sourcename.append(sourcename['name']) logger.info('swagger中的服务列表:{}'.format(str(self.sourcename))) for cloud in reponese: location = self.swagger_cloud + cloud['location'] reponese1 = requests.get(location).json() if 'paths' in reponese1: for path1 in reponese1['paths']: path = reponese1['paths'][path1] definitions = reponese1['definitions'] for method in path: if 'parameters' in path[method]: # 处理接口入参参数 self.param = self.retrieve_params( path[method]['parameters'], definitions, path1, reponese1['basePath']) else: self.param = ' ' definitionss = {} path3 = path1.split('/') a = 0 b = 0 #移除get接口url{} for ttt in path3: if '{' in ttt: a += len(ttt) b += 1 if b != 0: path1 = path1[0:-(a + b - 1)] definitionss['id'] = 'TEST_' + str(self.num) definitionss['host'] = reponese1['host'] definitionss['url'] = reponese1['basePath'] + path1 definitionss['method'] = method definitionss['param'] = self.param definitionss['consumes'] = path[method]['consumes'][0] definitionss['summary'] = path[method]['summary'] definitionss['tags'] = path[method]['tags'][0] definitionss['sourcename'] = reponese1[ 'basePath'].strip('/') self.num += 1 if definitionss['url'] not in self.case: self.case.append(definitionss) # dict转json,处理中文编码 # reponese1=json.dumps(reponese1,ensure_ascii=False) else: logger.error('{}服务无接口'.format(reponese1['basePath'])) return self.case
def createHtml(filepath, titles, starttime, endtime, passge, fail, id, name, key, coneent, url, meth, yuqi, json, relusts, amount, Skipped): texts = relust(titles, starttime, endtime, passge, fail, id, name, key, coneent, url, meth, yuqi, json, relusts, amount, Skipped) with open(filepath, 'wb') as f: f.write(texts.encode('utf-8')) logger.info('html报告处理完毕') return texts
def run_case(source): starttime = datetime.datetime.now() date = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) listid, listmodule, listname, listhost, listurl, listmethod, listheader, listparmas, listexpect, listisactive,Skipped,case_num = Read_Excel().get_excel( source) listrelust, list_fail, list_pass, list_json = testinterface() filepath = os.path.join('D:\python_package\demo20191112' + ('\\test_Report\\%s-result.html' % date)) try: open(filepath,mode='x') except: pass endtime = datetime.datetime.now() report=createHtml(titles=u'测试报告', filepath=filepath, starttime=starttime, endtime=endtime, passge=list_pass, fail=list_fail, id=listid, name=listname, key=listmodule, coneent=listparmas, url=listurl, meth=listmethod, yuqi=listexpect, json=list_json, relusts=listrelust, amount=case_num,Skipped=Skipped) contec = u'http接口自动化测试完成,测试通过:%s,测试失败:%s,详情见:%s' % ( list_pass, list_fail,filepath) logger.info(contec) mail(report)
def get_excel(self, sheetname): try: workbook = xlrd.open_workbook(self.filepath) me = workbook.sheet_by_name(sheetname) rows = me.nrows listid = [] listmodule = [] listparmas = [] listurl = [] listmethod = [] listheader = [] listhost = [] listname = [] listexpect = [] listisactive = [] Skipped = 0 case_num = 0 for i in range(1, rows): if (me.cell(i, 9).value) != 'N': listid.append(me.cell(i, 0).value) listmodule.append(me.cell(i, 1).value) listname.append(me.cell(i, 2).value) listhost.append(me.cell(i, 3).value) listurl.append(me.cell(i, 4).value) listmethod.append((me.cell(i, 5).value)) listheader.append((me.cell(i, 6).value)) listparmas.append((me.cell(i, 7).value)) listexpect.append((me.cell(i, 8).value)) listisactive.append((me.cell(i, 9).value)) else: Skipped += 1 case_num += 1 logger.info('解析excel') return listid, listmodule, listname, listhost, listurl, listmethod, listheader, listparmas, listexpect, listisactive, Skipped, case_num except Exception as e: logger.info('打开测试用例失败,原因是:%s' % e) return
def testinterface(): list_pass = 0 list_fail = 0 list_json = [] listrelust = [] assert_p = {} logger.info('开始执行case') for i in range(len(listurl)): if listhost[i][0:4] != 'https': listhost[i] = 'https://' + listhost[i] if listisactive[i] != 'N': header = {} header['Content-Type'] = listheader[i] listparmas[i] = assert_parmas(listparmas[i], assert_p) if listmethod[i] == 'post': parma = listparmas[i] else: parma = listparmas[i] api = requestspuls(url=listhost[i] + listurl[i], parmas=parma, method=listmethod[i], header=header) print(parma) re_assert = assert_in(asserqiwang=listexpect[i], fanhuijson=api) if re_assert.get('code') == 0: logger.info('Case执行成功>%s 参数:%s, url:%s ,返回:%s,预期:%s' % (listid[i], parma, listurl[i], api, listexpect[i])) listrelust.append('pass') list_json.append(api['message']) list_pass += 1 if assert_none(api['results']): assert_p[listid[i]] = api['results'] continue else: logger.info('Case执行失败>%s 参数:%s, url:%s ,返回:%s,预期:%s' % (listid[i], parma, listurl[i], api, listexpect[i])) list_fail += 1 list_json.append(api['message']) listrelust.append('fail') if assert_none(api['results']): assert_p[listid[i]] = 'Null' else: listrelust.append('delay') list_json.append('delay') logger.info('执行完毕,处理报告') return listrelust, list_fail, list_pass, list_json
def __init__(self, SourceName=None): self.swagger_cloud = r'https://api-uat.daoyitong.com/cloud' self.swagger_resource = 'https://api-uat.daoyitong.com/cloud/swagger-resources' ''' :param SourceName: 服务名称list(为空返回所有) :return: 全量服务列表+地址||入参服务列表+地址 ''' reponese = requests.get(self.swagger_resource) reponese = reponese.json() source_name = [] source_location = [] source2 = {} for cloud in reponese: location = self.swagger_cloud + cloud['location'] name = cloud['name'] source_name.append(name) source_location.append(location) source = dict(zip(source_name, source_location)) logger.info('swagger中的全部服务:{}'.format(source_name)) if SourceName is None: self.get_ModuleList(source) elif type(SourceName) is str: if SourceName in source.keys(): source2[SourceName] = source[SourceName] print(source2) self.get_ModuleList(source2) else: logger.info('未找到该{}服务'.format(SourceName)) else: for name1 in SourceName: if name1 in source: source2[name1] = source[name1] else: logger.info('未找到该{}服务'.format(name1)) logger.info('查询成功,已找到{}服务'.format(list(source2.keys()))) self.get_ModuleList(source2)
xxx = param['properties'][paramx]['$ref'].split( '/')[-1] param[paramx] = definitions[xxx]['properties'] else: param = param return param else: param = parameters1 return param if __name__ == '__main__': case_list = get_swagger().load_swagger_data() excel_name = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) Write_excel(excel_name).create_excelFile() logger.info('创建{}文件成功'.format(excel_name)) wt = Write_excel(excel_name) row = 1 for case_num in range(len(case_list) - 1): case_list[case_num]['param'] = json.dumps(case_list[case_num]['param'], ensure_ascii=False) wt.write(row, 1, case_list[case_num]['id']) wt.write(row, 2, case_list[case_num]['sourcename']) wt.write(row, 3, case_list[case_num]['tags']) wt.write(row, 4, case_list[case_num]['summary']) wt.write(row, 5, case_list[case_num]['host']) wt.write(row, 6, case_list[case_num]['url']) wt.write(row, 7, case_list[case_num]['method']) wt.write(row, 8, case_list[case_num]['consumes']) # wt.write(row, 9, case_list[case_num]['param'])