def run_dependent_case(self): run_method = RunMethod() row_Num = self.oper_excel.get_row_num_by_caseId(self.caseId) url = self.get_data.get_url_data(row_Num) method = self.get_data.get_method_data(row_Num) header = self.get_data.get_header_data(row_Num) request_data = self.get_data.get_data_for_json(row_Num) response_data = run_method.run_main(method, url, request_data, header) return json.loads(response_data)
class RunTest: def __init__(self): self.run_method = RunMethod() self.data = GetData() self.common_util = CommonUtil() self.send_email = SendEmail() def go_on_run(self): res = None pass_count = [] fail_count = [] rows_count = self.data.get_case_lines() for i in range(1, rows_count): url = self.data.get_request_url(i) method = self.data.get_request_method(i) is_run = self.data.get_is_run(i) data = self.data.get_data_for_json(i) expect = self.data.get_expcet_data(i) header = self.data.is_header(i) case_depend = self.data.get_case_depend(i) if case_depend: case_depend = "'" + str(case_depend) + "'" jsontodata = str(data).replace("'@@@'", case_depend) jsontodata = jsontodata.replace("'", '"') data = json.loads(jsontodata) if is_run: res = self.run_method.run_main(method, url, data, header) if self.common_util.is_contain(expect, res): self.data.write_status(i, 'pass') pass_count.append(i) else: self.data.write_status(i, 'fail') fail_count.append(i) self.data.write_res(i, res)
def __init__(self, methodName='runTest'): super(RunTest, self).__init__(methodName) # 获取logger和run_log read_logger = ReadLogger() self.logger = read_logger.get_logger() self.run_log_src = read_logger.get_run_log() # 使用自封装requests self.run_method = RunMethod() # 使用自封装关联数据 self.rely_data = RelyData() self.case_id = '' # 用例id self.desc = '' # 用例描述 self.req_msg = {'request': {}, '\nresponse': {}} # 用例基本信息
class RunMain: def __init__(self): self.run_method = RunMethod() self.get_data = GetData() self.common_util = CommonUtil() def run_test_flow(self): res = None pass_count = [] fail_count = [] rowNum = self.get_data.get_case_numbers() for i in range(2, rowNum + 1): is_run = self.get_data.get_is_run(i) if is_run: url = self.get_data.get_url_data(i) method = self.get_data.get_method_data(i) header = self.get_data.get_header_data(i) request_data = self.get_data.get_data_for_json(i) expect_data = self.get_data.get_expect_data(i) dep_caseId = self.get_data.get_dep_caseId(i) # 如果有依赖的case要执行,则执行依赖case并获取依赖case的返回数据 if dep_caseId != None: self.dep_data = DependentData(dep_caseId) dep_response_data = self.dep_data.get_data_by_dep_response_data( i) dep_field_data = self.get_data.get_dep_field_data(i) request_data[dep_field_data] = dep_response_data # method, url, data = None, header = None res = self.run_method.run_main(method, url, request_data, header) compareResult = self.common_util.is_contain(expect_data, res) if compareResult: print('This test case passed') self.get_data.write_result(i, 'Passed') pass_count.append(i) else: print('This test case failed') self.get_data.write_result(i, res) fail_count.append(i) print(res) # return res print(len(pass_count)) print(len(fail_count))
class RunTest(unittest.TestCase, unittest.SkipTest): def __init__(self, methodName='runTest'): super(RunTest, self).__init__(methodName) # 获取logger和run_log read_logger = ReadLogger() self.logger = read_logger.get_logger() self.run_log_src = read_logger.get_run_log() # 使用自封装requests self.run_method = RunMethod() # 使用自封装关联数据 self.rely_data = RelyData() self.case_id = '' # 用例id self.desc = '' # 用例描述 self.req_msg = {'request': {}, '\nresponse': {}} # 用例基本信息 def skipTest(self, reason): raise unittest.SkipTest def getCasePro(self): return self.case_id, self.desc def getCaseMsg(self): return self.req_msg def start(self, url, uri, method, api_name, header, cookie, **kw): # 获取case数据 skip = kw.get('skip', '0') # skip默认值为0,为1表示跳过该case self.case_id = kw.get('case_id') self.desc = kw.get('desc') api_name = api_name url = url + uri method = method header = header cookie = cookie # header = kw.get('request').get('header', '') # 缺省headers为空 # cookie = kw.get('request').get('cookie', '') # 缺省cookies为空 # data = kw.get('request').get('data', '') # 缺省data为空 data = kw.get('request_data') validators = kw.get('validators') relyDataExport = kw.get('relyDataExport') # 关联输出,即该接口响应返回被其他接口关联字段 relyDataImport = kw.get('relyDataImport') # 关联引入,即该接口运行所需的关联字段设置 start_time = time.strftime("%Y/%m/%d %H:%M:%S") start_timestamp = time.time() * 1000 # ms self.req_msg.get('request').setdefault('\nreq.url', url) self.req_msg.get('request').setdefault('\nreq.method', method) self.req_msg.get('request').setdefault('\nreq.header', header) self.req_msg.get('request').setdefault('\nreq.cookie', cookie) self.req_msg.get('request').setdefault('\nreq.data', data) self.req_msg.get('request').setdefault('\nreq.validators', validators) self.req_msg.get('request').setdefault('\nreq.relyDataExport', relyDataExport) self.req_msg.get('request').setdefault('\nreq.relyDataImport', str(relyDataImport) + '\n') if int(skip) == 1: self.logger.debug('跳过用例 :%s(%s)' % (self.case_id, self.desc)) self.skipTest('skip case') try: # 处理关联数据 if relyDataImport is not None: for x in relyDataImport: relyDataSrc = x.get('relyDataSrc') # 关联字段 relyDataDes = x.get('relyDataDes') # 依赖关联字段 rely_data = self.rely_data.get_rely_from_file(relyDataSrc) data[relyDataDes] = rely_data self.logger.debug('用例编号 :%s ' % self.case_id) self.logger.debug('接口名称 : %s' % api_name) self.logger.debug('用例描述 : %s' % self.desc) self.logger.debug('请求时间 : %s' % start_time) self.logger.debug(' 请求信息 '.center(50, '-')) self.logger.debug('url : %s' % url) self.logger.debug('method : %s' % method) self.logger.debug('header : %s' % header) self.logger.debug('cookie : %s' % cookie) self.logger.debug('请求数据 : %s' % data) self.logger.debug('断言设置 : %s' % validators) self.logger.debug('关联输出 : %s' % relyDataExport) self.logger.debug('关联引入 : %s' % relyDataImport) # 发送请求 # 接口有异常的情况下,可能返回的不是json串,会报错 res = self.run_method.run_main(method, url, data, cookies=cookie, headers=header) end_time = time.strftime("%Y/%m/%d %H:%M:%S") end_timestamp = time.time() * 1000 # ms time_spend = '%.2f' % (end_timestamp - start_timestamp) # ms精度 self.logger.debug(' 响应信息 '.center(50, '-')) self.logger.debug('响应时间 : %s' % end_time) self.logger.debug('响应耗时 : %s ms' % time_spend) self.logger.debug('响应码 : %s' % res.status_code) self.logger.debug('响应头 : %s' % res.headers) self.req_msg.get('\nresponse').setdefault('\nresp.status_code', res.status_code) self.req_msg.get('\nresponse').setdefault('\nresp.headers', res.headers) # 查看是否包含 断言查看一次错误就停止,后面加入错误提示 self.assertEqual(res.status_code, 200, msg='预计结果不符:http_code预期结果 200,实际结果【%s】' % (res.status_code)) # 响应结果转json res = res.json() self.req_msg.get('\nresponse').setdefault('\nresp.json', str(res) + '\n') # 保存被关联数据 if relyDataExport is not None: for x in relyDataExport: relyKey = x.get('relyKey') keepKey = x.get('keepKey') self.rely_data.write_rely_to_file(relyKey, keepKey, res) # 断言 for valid in validators: check = valid.get('check') # 待检查字段 expect = valid.get('expect') # 预期值 resp_data = res.get(check) if isinstance(expect, int): self.assertEqual(expect, resp_data, msg='预计结果不符:【%s】预期结果【%s】,实际结果【%s】' % (check, expect, resp_data)) if isinstance(expect, str): self.assertIn(expect, resp_data, msg='预计结果不符:【%s】预期结果【%s】,实际结果【%s】' % (check, expect, resp_data)) self.logger.debug('响应内容 : %s' % res) except Exception as e: self.logger.debug('响应内容 : %s' % res) self.logger.error('错误信息 : %s' % e) raise
def __init__(self): self.run_method = RunMethod() self.get_data = GetData() self.common_util = CommonUtil()
def __init__(self): self.run_method = RunMethod() self.data = GetData() self.common_util = CommonUtil() self.send_email = SendEmail()
class RunTest(unittest.TestCase, unittest.SkipTest, DataCheck): def __init__(self, methodName='runTest'): super(RunTest, self).__init__(methodName) # 获取logger和run_log read_logger = ReadLogger() self.logger = read_logger.get_logger() self.run_log_src = read_logger.get_run_log() # 使用自封装requests self.run_method = RunMethod() # 使用自封装关联数据 self.rely_data = RelyData() self.case_id = '' # 用例id self.desc = '' # 用例描述 self.resp = None # 响应数据 self.req_msg = {'request': {}, '\nresponse': {}} # 用例基本信息 def get_resp(self): """ 获取响应信息 :return: response data """ return self.resp def skipTest(self, reason): """ 过滤用例 :param reason: 过滤用例原因 :return: unittest.SkipTest """ raise unittest.SkipTest def getCasePro(self): """ 获取用例基本信息 :return: case_id, desc """ return self.case_id, self.desc def getCaseMsg(self): """ 获取待执行用例详细信息 :return: req_msg = {'request': {}, '\nresponse': {}} """ return self.req_msg def start(self, url, uri, method, api_name, header, cookie, **kw): """ 用例运行主入口 :param url: 请求地址 :param uri: 请求路径 :param method: 请求方法 :param api_name: 接口名称 :param header: header设置 :param cookie: cookie设置 :param kw: 其他参数 :return: None """ # 获取case数据 options = kw.get('options', {}) skip = options.get('skip', '0') # skip默认值为0,为1表示跳过该case data_check = options.get('datacheck', None) # 数据校验 toJsonData = options.get('jsonData', '0') # jsonData默认值为0,表示请求数据不做序列化 self.case_id = kw.get('case_id') # case id self.desc = kw.get('desc') # case描述 api_name = api_name # api名 url = url + uri # 请求url method = method # 请求方法 header = header # header设置 cookie = cookie # cookie设置 data = kw.get('request_data', '') # 请求数据,缺省为空 validators = kw.get('validators') # 断言设置 relyDataExport = kw.get('relyDataExport') # 关联输出,即该接口响应返回被其他接口关联字段 relyDataImport = kw.get('relyDataImport') # 关联引入,即该接口运行所需的关联字段设置 start_time = time.strftime("%Y/%m/%d %H:%M:%S") # 开始时间 start_timestamp = time.time() * 1000 # 时间戳,ms # 处理关联数据 if relyDataImport is not None: for x in relyDataImport: datatype = x.get( 'datatype') # 获取目标关联数据替换源,可能是 request_data/header/cookie relyDataSrc = x.get( 'relyDataSrc') # 获取依赖字段,可能在request_data中为层级结构 relyDataDes = x.get('relyDataDes') # 获取关联字段 rely_value = self.rely_data.get_rely_from_file( relyDataDes) # 获取关联数据 # 替换依赖字段值为关联数据 if datatype in "header": header[relyDataSrc] = rely_value elif datatype in "cookie": cookie[relyDataSrc] = rely_value else: paths = jsonpath( data, '$..%s' % relyDataSrc, result_type='IPATH') # 获取目标字段的位置的层级结构,返回list # 替换request_data中所有目标key的值为关联数据 for path in paths: lens = len(path) for index in range(lens): if re.match(r'[0-9]', path[index]): path[index] = int(path[index]) if lens == 1: data[path[0]] = rely_value elif lens == 2: data[path[0]][path[1]] = rely_value elif lens == 3: data[path[0]][path[1]][path[2]] = rely_value elif lens == 4: data[path[0]][path[1]][path[2]][ path[3]] = rely_value elif lens == 5: data[path[0]][path[1]][path[2]][path[3]][ path[4]] = rely_value elif lens == 6: data[path[0]][path[1]][path[2]][path[3]][path[4]][ path[5]] = rely_value else: self.logger.debug('层级结构过长') self.req_msg.get('request').setdefault('\nreq.url', url) self.req_msg.get('request').setdefault('\nreq.method', method) self.req_msg.get('request').setdefault('\nreq.header', header) self.req_msg.get('request').setdefault('\nreq.cookie', cookie) self.req_msg.get('request').setdefault('\nreq.data', data) self.req_msg.get('request').setdefault('\nreq.validators', validators) self.req_msg.get('request').setdefault('\nreq.relyDataExport', relyDataExport) self.req_msg.get('request').setdefault('\nreq.relyDataImport', str(relyDataImport)) self.req_msg.get('request').setdefault('\nreq.data_check', str(data_check) + '\n') if int(skip) == 1: self.logger.debug('跳过用例 :%s(%s)' % (self.case_id, self.desc)) self.skipTest('skip case') try: self.logger.debug('用例编号 :%s ' % self.case_id) self.logger.debug('接口名称 : %s' % api_name) self.logger.debug('用例描述 : %s' % self.desc) self.logger.debug('请求时间 : %s' % start_time) self.logger.debug(' 请求信息 '.center(50, '-')) self.logger.debug('url : %s' % url) self.logger.debug('method : %s' % method) self.logger.debug('header : %s' % header) self.logger.debug('cookie : %s' % cookie) self.logger.debug('请求数据 : %s' % data) self.logger.debug('断言设置 : %s' % validators) self.logger.debug('关联输出 : %s' % relyDataExport) self.logger.debug('关联引入 : %s' % relyDataImport) self.logger.debug('校验数据 : %s' % data_check) # 发送请求 # 接口有异常的情况下,可能返回的不是json串,会报错 if toJsonData == 1: resp = self.run_method.run_main(method, url, json.dumps(data), cookies=cookie, headers=header) else: resp = self.run_method.run_main(method, url, data, cookies=cookie, headers=header) resp_headers = dict(resp.headers) # 响应头 resp_status_code = resp.status_code # 响应码 resp_cookie = dict(resp.cookies) # 响应cookie resp_text = resp.text # 响应文本 end_time = time.strftime("%Y/%m/%d %H:%M:%S") end_timestamp = time.time() * 1000 # ms time_spend = '%.2f' % (end_timestamp - start_timestamp) # ms精度 self.logger.debug(' 响应信息 '.center(50, '-')) self.logger.debug('响应时间 : %s' % end_time) self.logger.debug('响应耗时 : %s ms' % time_spend) self.logger.debug('响应码 : %s' % resp_status_code) self.logger.debug('响应头 : %s' % resp_headers) self.req_msg.get('\nresponse').setdefault('\nresp.status_code', resp_status_code) self.req_msg.get('\nresponse').setdefault('\nresp.headers', resp_headers) # 查看是否包含 断言查看一次错误就停止,后面加入错误提示 self.assertEqual(resp_status_code, 200, msg='预计结果不符:http_code预期结果 200,实际结果【%s】' % (resp_status_code)) # 响应结果处理,可能是文本、网页、dict if resp_text.startswith('{'): resp = resp.json() self.resp = resp self.req_msg.get('\nresponse').setdefault( '\nresp.json', str(resp) + '\n') # 保存被关联数据 if relyDataExport is not None: for x in relyDataExport: datatype = x.get('datatype') relyKey = x.get('relyKey') keepKey = x.get('keepKey') if datatype in "header": self.rely_data.write_rely_to_file( relyKey, keepKey, resp_headers) elif datatype in "cookie": self.rely_data.write_rely_to_file( relyKey, keepKey, resp_cookie) else: self.rely_data.write_rely_to_file( relyKey, keepKey, resp) # 响应数据断言 json for valid in validators: check = valid.get('check') # 待检查字段 expect = valid.get('expect') # 预期值 resp_data = resp.get(check) if isinstance(expect, int): self.assertEqual(expect, resp_data, msg='预计结果不符:【%s】字段预期结果【%s】,实际结果【%s】' % (check, expect, resp_data)) if isinstance(expect, str): self.assertIn(expect, resp_data, msg='预计结果不符:【%s】字段预期结果【%s】,实际结果【%s】' % (check, expect, resp_data)) else: resp = resp_text resp = resp.replace(r"<", r"<--") # 注释html标签,防止误识别 self.resp = resp self.req_msg.get('\nresponse').setdefault( '\nresp.text', str(resp) + '\n') # 保存被关联数据 if relyDataExport is not None: for x in relyDataExport: datatype = x.get('datatype') relyKey = x.get('relyKey') keepKey = x.get('keepKey') if datatype in "header": self.rely_data.write_rely_to_file( relyKey, keepKey, resp_headers) elif datatype in "cookie": self.rely_data.write_rely_to_file( relyKey, keepKey, resp_cookie) else: pass # 响应数据断言 text for valid in validators: expect = valid.get('expect') # 预期值 if isinstance(expect, str): self.assertIn(expect, resp_text, msg='预计结果不符:预期值【%s】在响应文本中不存在!' % expect) self.logger.debug('响应内容 : %s' % resp) # 数据校验 if data_check == 1: raise DataCheck except DataCheck: raise except Exception as e: self.logger.debug('响应内容 : %s' % resp) self.logger.error('错误信息 : %s' % e) raise