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): is_run = self.data.get_is_run(i) if is_run: url = self.data.get_url(i) method = self.data.get_request_method(i) data = self.data.get_data_for_json(i) expect = self.data.get_expcet_data(i) header = self.data.get_is_header(i) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData() # 获取的依赖响应数据 depend_resonse_data = self.depend_data.get_data_for_key(i) # 获取依赖的key depend_key = self.data.get_depend_field(i) data[depend_key] = depend_resonse_data res = self.run_method.run_main(method, url, data, header) if self.com_util.is_contain(expect, res): self.data.write_result(i, "pass") pass_count.append(i) else: self.data.write_result(i, res) fail_count.append(i) self.send_mai.send_main(pass_count, fail_count)
def go_on_run(self): pass_count = [] fail_count = [] rows_count = self.data.get_case_lines() for i in range(1,rows_count): url = self.data.get_url(i) method = self.data.get_request_way(i) is_run = self.data.get_is_run(i) data = self.data.get_data_for_json(i) header = self.data.is_header(i) expect = self.data.get_expcet_data(i) depend_case = self.data.is_depend(i) if depend_case != None: # print("`````11`") self.depend_data = DependentData(depend_case) #获取返回结果里面的依赖 depend_respones_data = self.depend_data.get_data_for_key(i) #获取依赖的key depend_data = self.data.get_depend_field(i) #将返回结果里面的依赖赋值给依赖数据 data[depend_data] = depend_respones_data if is_run == True: run_main = self.run_method.run_main(method,url,data,header) # print(type(run_main)) # print(type(expect)) print(run_main) if expect in run_main: self.data.write_result(i,"pass") pass_count.append(i) else: self.data.write_result(i,run_main) fail_count.append(i) self.sendemail.send_main(pass_count,fail_count)
def go_on_run(self): 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) header = self.data.is_header(i) expect = self.data.get_expcet_data(i) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData(i) # 获取依赖的响应数据 depend_response_data = self.depend_data.get_data_for_key(i) # 获取依赖的key depend_key = self.data.get_depend_field(i) request_data[depend_key] = depend_response_data # if is_run: res = self.run_method.run_main(method,url,data,header) if self.com_util.is_contain(expect,res): self.data.write_result(i,'pass') # print("测试通过") else: self.data.write_result(i, 'fail')
def go_on_run(self): """程序执行""" pass_count = [] fail_count = [] res = None # 获取用例数 rows_count = self.data.get_case_lines() # 第一行索引为0 for i in range(1, rows_count): is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) request_data = self.data.get_data_for_json(i) expect = self.data.get_expcet_data(i) header = self.data.is_header(i) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData(depend_case) # 获取依赖的响应数据 depend_response_data = self.depend_data.get_data_for_key(i) # 获取依赖的key depend_key = self.data.get_depend_field(i) # 更新请求字段 request_data[depend_key] = depend_response_data # 如果header字段值为write则将该接口的返回的token写入到token.json文件,如果为yes则读取token.json文件 if header == "write": res = self.run_method.run_main(method, url, request_data) op_header = OperationHeader(res) op_header.write_token() elif header == 'yes': op_json = OperationJson("../dataconfig/token.json") token = op_json.get_data('data') request_data = dict(request_data, **token) # 把请求数据与登录token合并,并作为请求数据 res = self.run_method.run_main(method, url, request_data) else: res = self.run_method.run_main(method, url, request_data) if expect != None: if self.com_util.is_contain(expect, res): self.data.write_result(i, "Pass") pass_count.append(i) else: self.data.write_result(i, res) fail_count.append(i) else: print("用例ID:case-{i},预期结果不能为空") # 发送邮件 # self.send_email.send_main(pass_count, fail_count) print("通过用例数:{len(pass_count)}") print("失败用例数:{len(fail_count)}")
def go_on_run(self): """ 执行测试用例 :return: 通过用例和失败用例 """ pass_list = [] fail_list = [] rows_count = self.data.get_case_num() for i in range(1, rows_count): is_run = self.data.is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_method(i) data = self.data.get_data_for_json(i) cookie = self.data.is_cookie(i) header = self.data.is_header(i) expect = self.data.get_expect_data(i) if isinstance(expect, float): expect = str(int(expect)) depend_case = self.data.is_depend(i) if depend_case is not None: depend_data = DependentData(depend_case) # 获取依赖响应的返回数据 depend_response_data = depend_data.get_data_for_key(i) # # 使用mock-test模拟请求 # depend_response_data = mock_test(self.run_method.run_main, data, url, "POST", order) # 获取依赖的字段 depend_field = self.data.get_depend_field(i) # 更新 data[depend_field] = depend_response_data if cookie == 'write': res = self.run_method.run_main(method, url, data, header) opera_cookie = OperationCookie(res) opera_cookie.write_cookie() elif cookie == 'yes': op_json = OperationJson('../data_config/cookie.json') cookie = op_json.get_data('ASP.NET_SessionId') cookies = {'ASP.NET_SessionId': cookie} res = self.run_method.run_main(method, url, data, cookies) else: res = self.run_method.run_main(method, url, data) if self.common_util.is_contain(expect, res.text): # print("PASS") pass_list.append(i) self.data.write_result(i, 'PASS') else: # print("FAILED") fail_list.append(i) self.data.write_result(i, 'FAILED') self.send_email.send_main(pass_list, fail_list)
def run_test(self, row): error_num = 0 Log().info("开始执行第%d条用例" % row) while error_num <= 3: is_run = self.data.get_is_run(row) if is_run: url = self.data.get_request_url(row) method = self.data.get_request_method(row) request_data = self.data.get_request_data(row) headers = self.data.get_is_header(row) expect = self.data.get_expect_data(row) depend_case = self.data.get_depend_case(row) # 判断是否存在依赖数据 if depend_case != '': self.depend_data = DependentData(depend_case) depend_reponse_value = self.depend_data.get_dependent_values( row) # 获取依赖接口返回的数据的依赖的key对应的value值 depend_key = self.data.get_field_depend( row) # 获取依赖数据value所对应的新的接口的key request_data[ depend_key] = depend_reponse_value # key=value # 发送请求 res = self.run_method.run_main(method, url, request_data, headers) Log().info("请求传入数据:请求方法:%s,请求url:%s,请求参数:%s,请求的信息头:%s" % (method, url, request_data, headers)) # 预期结果与实际结果对比 # result = operator.contains(res,expect) try: self.assertIn(expect, res) Log().info("对code断言,断言结果--预期值%s == 实际值%s,测试通过" % (expect, res)) self.data.write_result(row, "pass") self.pass_count.append(row) error_num = 0 break except AssertionError as e: Log().info("对code断言,断言结果--预期值%s != 实际值%s,测试不通过" % (expect, res)) if error_num <= 2: error_num += 1 Log().info("失败用例重试第%d次" % error_num) else: Log().info("失败重试中次数用完,最后结果不通过") self.data.write_result(row, res) self.fail_count.append(row) # raise break
def go_on_run(self): pass_count = [] fail_count = [] cookies = None rows = self.getdata.get_case_lines() for i in range(1, rows): is_run = self.getdata.get_is_run(i) if is_run: url = self.getdata.get_url(i) is_depend = self.getdata.is_depend(i) request_method = self.getdata.get_request_method(i) expect = self.getdata.get_expect(i) # print(expect) is_cookie = self.getdata.is_cookie(i) is_header = self.getdata.is_header(i) data = self.getdata.get_data_for_json(i) print(data) depend_case = self.getdata.is_depend(i) if is_depend: self.depend_data = DependentData(depend_case) field_depend = self.getdata.get_field_depend(i) data_depend = self.depend_data.get_data_for_key(i) data[field_depend] = data_depend if is_cookie == 'write': res = self.runmethod.run_main(url, request_method, data) op_cookie = OperationCookie(json.loads(res)) op_cookie.write_cookie() if is_cookie == 'yes': op_json = OperationJson('../dataconfig/cookie.json') cookie = op_json.get_data("apsid") cookies = {"apsid": cookie} res = self.runmethod.run_main(url, request_method, data, is_header, cookies) if self.commonutil.iscontain(expect, res): print("测试通过") self.getdata.write_result(i, "测试通过") pass_count.append(i) else: print(expect) print(res) print("测试失败") self.getdata.write_result(i, res) fail_count.append(i) else: return None
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): is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) # if i == 7: # print("已经成年") # url = 'http://192.168.2.81:10003/shop/goods/new-list' 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) # expect = self.data.get_expcet_data_for_mysql(i) # data = {'pageNum': 1, 'pageSize': 10} header = self.data.is_header(i) depend_case = self.data.is_depend(i) # header = {'Content-Type': 'application/json'} if depend_case != None: self.depend_data = DependentData(depend_case) # 获取的依赖响应数据 depend_response_data = self.depend_data.get_data_for_key(i) print("this is dependResponseData = ",depend_response_data) # 获取依赖的key depend_key = self.data.get_depend_fileld(i) print("*************this is depend_key = ",depend_key) # 根据获取的依赖key,将depend_kay更新成depend_response_data data[depend_key] = depend_response_data print("*************this is data[depend_key]",data[depend_key]) res = self.run.run_main(method, url, data, header) if self.com_util.is_contain(expect,res): self.data.write_result(i,'Pass') pass_count.append(i) else: self.data.write_result(i,res) fail_count.append(i) else: self.data.write_result(i, 'N/A') continue # print(res) # print(len(pass_count)) # print(len(fail_count)) self.send_mail.send_main(pass_count,fail_count)
def go_on_run(self): '''主运行程序''' res = None pass_count = [] fail_count = [] row_count = self.data.get_case_lines() for i in range(1, row_count): url = self.data.get_request_url(i) method = self.data.get_request_method(i) data = self.data.get_data_from_json(i) header = self.data.is_header(i) is_run = self.data.get_is_run(i) #expect_result = self.data.get_expect_data(i) expect_result, expect_result_type = self.data.get_expect_data_for_mysql( i) #expect_result_type = self.data.get_expect_data_for_mysql(i)[1] #print('-------expect_result',expect_result) #print('-------expect_result_type',expect_result_type) depend_case = self.data.get_field_depend_value(i) if is_run: if depend_case: #print('1111---------depend_case',depend_case) case_id = self.data.get_case_depend_value(i) #允许数据依赖逻辑 #print('1111---------case_id',case_id) value = DependentData(case_id).get_data_for_key(i) #print('1111------------value',value) #判断是否为post请求,如果是,将data中的值刷新,如果为get,将依赖值,赋值给url if method == 'POST': data[depend_case] = value else: url = url + '?' + depend_case + '=' + value #print('-------------url', url) #print('-------data',data) ''' if header == 'write': res = self.run_method.run_main(method,url,data) OperationHeader(res).write_cookie() elif header == 'yes': cookie = OperationJson('../dataconfig/cookie.json').get_data('apsid') cookies = {'apsid':cookie} res = self.run_method.run_main(method,url,data,cookies) else: res = self.run_method.run_main(method,url,data) ''' #res = OperationHeader().header_main(header,method,url,data) res = OperationHeader().header_main(header, method, url, data) #head判断和处理 #print('---------',expect_result) #print('----res',res,type(res)) #if self.com_util.is_contain(expect_result,res):#字符串判断 if self.com_util.is_equal(expect_result, res, expect_result_type): #测试结果写入excel self.data.write_result(i, 'pass') pass_count.append(i) else: self.data.write_result(i, str(res)) fail_count.append(i) self.email.send_main(pass_count, fail_count) #发送邮件
def go_on_run(self): print("开始执行。。。") response = None pass_count = [] fail_count = [] rows_conut = self.data.get_case_lines() print(rows_conut) for i in range(1, rows_conut): is_run = self.data.get_is_run(i) #判断是否运行 if is_run: request_url = self.data.get_request_url(i) request_method = self.data.get_request_method(i) request_data = self.data.get_data_for_json(i) expect_data = self.data.get_expect_data(i) request_header = self.data.is_header(i) depend_case = self.data.is_depend(i) #判断是否有依赖 if depend_case != None: self.depend_data = DependentData(depend_case) #获取响应数据 depend_response_data = self.depend_data.get_data_for_key(i) #获取依赖的key depend_key = self.data.get_depend_field(i) #更新depend_response_data值 request_data[depend_key] = depend_response_data # 参数顺序不能错 response = self.httpclient.request(request_method, request_url, request_data, request_header) print("response:", response) print( '-----------------------------------------------------------' ) if self.com_util.is_contain(expect_data, response): # print("测试通过:",'result中包含预期值'+expect) self.data.write_result(i, 'pass') pass_count.append(i) else: # print("测试失败:",'result中不包含预期值'+expect) self.data.write_result(i, response) fail_count.append(i)
class RunTest(): def __init__(self): self.run_method = RunMethod() self.data = GetData() self.com_util = CommonUtil() self.depend_data = DependentData() # 程序执行 def go_on_run(self): res = None #获取case个数(获取有数据的单元格行) rows_count = self.data.get_case_lines() #循环判断要执行的case,跳过第一行标题开始循环 for i in range(1, rows_count): #获取是否执行 is_run = self.data.get_is_run(i) # print is_run # #判断is_run的值为true时执行 if is_run: # print i #获取url url = self.data.get_request_url(i) # print url #获取请求类型 method = self.data.get_request_method(i) # print method #获取数据 data = self.data.get_data_for_json(i) # print data expect = self.data.get_expect_data(i) #获取header(默认demo) # header = self.data.demo_header() #获取excel中指定header header = self.data.is_header(i) # print header #获取依赖数据 depend_case = self.data.is_depend(i) #判断是否需要依赖数据 if depend_case != None: #获取依赖的响应数据 depend_response_data = self.depend_data.get_data_for_key(i) #获取依赖key depend_key = self.data.get_depend_field(i) #将获取到的依赖case响应数据赋值给依赖key request_data[depend_key] = depend_response_data #获取响应数据 res = self.run_method.run_main(method, url, data, header) return res #打印结果并转码为字符串类型 # print res.text.encode('unicode-escape').decode('string_escape') #判断返回结果与预期结果比对 if self.com_util.is_contain(expect, res): self.data.write_result(i, 'pass') else: self.data.write_result(i, 'false')
def go_on_run(self): count = self.data.get_case_lines() pass_count = [] fail_count = [] for i in range(1, count): is_run = self.data.get_is_run(i) print(i) if is_run is True: url = self.data.get_request_url(i) method = self.data.get_request_method(i) data = self.data.get_data_for_json(i) header = self.data.is_header(i) expect = self.data.get_expect_data(i) # 如果用需要查询数据库则用下面这条 # expect = self.data.get_expect_data_for_mysql(i) depend_case = self.data.is_depend(i) if depend_case is not None: depend_data = DependentData(depend_case) # 获取依赖的相应数据 depend_response_data = depend_data.get_data_for_key(i) # 获取依赖的key depend_key = self.data.get_depend_filed(i) data[depend_key] = depend_response_data if header == 'write': res = self.run_method.run_main(method, url, data) op_header = OperationHerader(res) op_header.write_cookie() elif header == 'yes': op_json = OperationJson('../dataconfig/cookie.json') new_header = op_json.new_header() res = self.run_method.run_main(method, url=url, data=data, header=new_header) else: res = self.run_method.run_main(method, url, data) res = self.comment_util.remate_data(res) # 字符串比较用is_contain,字典比较用is_equal_dict result = self.comment_util.is_contain(expect, res) if result is True: self.data.write_value(i, 'pass') pass_count.append(i) else: self.data.write_value(i, res) fail_count.append(i)
def is_depend(self, i, depend_morecase, request_type, url, token_header, data): # 判断是否存在依赖 if depend_morecase != None: depend_data = DependentData(depend_morecase, self.sheet_name, self.json_file) dependent_response_data = depend_data.get_data_for_key(i, 0) if request_type == "get": request_url = url + dependent_response_data response = self.run_method.run_main(request_type, request_url, data, token_header) else: depend_key = self.data.get_dependent_key(i, 0) jsonData = json.loads(data) jsonData[depend_key] = dependent_response_data requestData = json.dumps(jsonData) response = self.run_method.run_main( request_type, url, requestData, token_header) # 获取接口返回数据(返回类型:string型) else: response = self.run_method.run_main( request_type, url, data, token_header) # 获取接口返回数据(返回类型:string型) return response
class RunTest: def __init__(self): self.run_method = RunMethod() self.data = GetData() self.com_util = CommonUtil() self.send_mail = 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): is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) request_data = self.data.get_data_for_json(i) expect = self.data.get_expcet_data(i) header = self.data.is_header(i) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData() #获取的依赖响应数据 depend_response_data = self.depend_data.get_data_for_key(i) #获取依赖的key depend_key = self.data.get_depend_field(i) request_data[depend_key] = depend_response_data res = self.run_method.run_main(method, url, request_data, header) if self.com_util.is_contain(expect, res): self.data.write_result(i, 'pass') pass_count.append(i) #print("测试通过") else: #print("测试失败") self.data.write_result(i, res) fail_count.append(i) print(len(pass_count)) print(len(fail_count)) self.send_mail.send_main(pass_count, fail_count)
def base_run(self): res = None pass_count = [] fail_count = [] no_run_count = [] rows_count = self.data.get_case_rows() log_file = "../log/interface-demo03.log" # 每次执行用例前,将log日志文件清空数据 with open(log_file, "w") as lf: lf.seek( 0, 0 ) # 加上lf.seek(0),把文件定位到position 0;若没有这句话,文件是定位到数据最后,truncate也是从最后这里删除。 lf.truncate() if self.excel.sheet_name == 0: self.tool.write_mobile() # 向get_mobile.json 中写入手机号码 # self.__mobile__ = self.tool.phone_code_generator() for i in range(1, rows_count): try: is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) # data = self.data.get_request_data(i) # 获取excel 中的 data data = self.data.get_request_excel_data( i) # 直接读取 excel 中的 data # 获取依赖单元格 depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData(depend_case) depend_response_data = self.depend_data.get_value_for_key( i) # 获取 依赖字段的 响应数据 # depend_key = self.data.get_depend_field(i) # 获取 请求依赖的 key # data[depend_key] = depend_response_data # 将依赖case的响应返回中某个字段的value赋值给该接口请求中某个参数 if data.find("${mobile}") != -1: # data = data.replace("${mobile}", self.__mobile__) data = data.replace("${mobile}", self.tool.get_mobile()) elif data.find("${idCardNumber}") & data.find( "${name}") != -1: data = data.replace("${idCardNumber}", self.tool.getRandomIdCard()) name = "雨点" + self.tool.num_chinese( self.tool.get_mobile()[-4:]) data = data.replace("${name}", name) elif data.find("${businessLicenseNumber}") != -1: data = data.replace("${businessLicenseNumber}", self.tool.license_no()) elif data.find("${write_borrowerCode}") != -1: self.use_mysql.select_borrowercode() use_json = UseJson("../data_config/borrowerCode.json") borrowerCode = use_json.get_data("borrowerCode") data = data.replace("${write_borrowerCode}", borrowerCode) elif data.find("${borrowerCode}") != -1: use_json = UseJson("../data_config/borrowerCode.json") borrowerCode = use_json.get_data("borrowerCode") data = data.replace("${borrowerCode}", borrowerCode) elif data.find("${creditApplyCode}") != -1: use_json = UseJson( "../data_config/credit_apply_code.json") code = use_json.get_data("code") # code = use_json.read_data() data = data.replace("${creditApplyCode}", code) now = time.strftime("%Y-%m-%d 08:%M:%S") data = data.replace("${nowdate}", now) elif data.find("${nowdate}") != -1: now = time.strftime("%Y-%m-%d 08:%M:%S") data = data.replace("${nowdate}", now) # data = self.data.get_request_excel_data_wrapper(i, self.mobile) # 直接读取 excel 中的 data # data = self.data.get_data_values(i) # data = self.data.get_data_values_wrapper(i, self.mobile) header = self.data.get_request_header( i) # 获取 excel 中的 header 关键字 # header_json = self.data.get_header_value(i) # 获取 json 中的 header_key 对应的头文件数据 expect_data = self.data.get_expect_data(i) expect = json.loads(expect_data) # # 获取依赖单元格 # depend_case = self.data.is_depend(i) # if depend_case != None: # self.depend_data = DependentData(depend_case) # depend_response_data = self.depend_data.get_value_for_key(i) # 获取 依赖字段的 响应数据 # # depend_key = self.data.get_depend_field(i) # 获取 请求依赖的 key # # data[depend_key] = depend_response_data # 将依赖case的响应返回中某个字段的value赋值给该接口请求中某个参数 if header == '{"Content-Type":"application/json"}': header1 = eval(header) # header1 = {"Content-Type": "application/json"} # data = json.dumps(data) # res = self.run_method.run_main(method, url, data, header=header_json, params=data) res = self.run_method.run_main(method, url, data, header=header1, params=data) elif header == '{"Content-Type": "application/json", "Product": "31G"}': header1 = eval(header) res = self.run_method.run_main(method, url, data, header=header1, params=data) elif header == '{"Content-Type":"multipart/form-data"}': # data = {"imageType": "ID_CARD_FRONT_IMAGE"} data = eval(data) # 把 str 转成 dict with open("H:/wahh.jpg", "rb") as f: # 打开上传文件 r = f.read() files = {"file": ("wahh.jpg", r, "image/jpeg")} use_json = UseJson("../data_config/config_header.json") header_json = use_json.read_data() # header_json = { # "Content-Type": "multipart/form-data", # 不要画蛇添足写这一句 # "Cookie": "SESSION=NGExN2Y0MzUtNjVhNy00MDRkLWIyZjItMGFjZWVlMDFiZjM5"} response = requests.post(url=url, data=data, files=files, headers=header_json) # 获取返回请求 res = response.text # res = self.run_method.run_main(method, url, data, header=header_json, params=data) elif header == 'get_cookie': use_json = UseJson("../data_config/config_header.json") cookie_value = use_json.get_data("Cookie") # a = json.dumps(cookie1) # cookie = re.findall(r'{(.*?)}', a) # cookie_value = cookie1['Cookie'] header_json = { "Content-Type": "application/json", "Cookie": cookie_value } res = self.run_method.run_main(method, url, data, header=header_json, params=data) elif header == 'get_cookie,31G': use_json = UseJson("../data_config/config_header.json") cookie_value = use_json.get_data("Cookie") # a = json.dumps(cookie1) # cookie = re.findall(r'{(.*?)}', a) # cookie_value = cookie1['Cookie'] header_json = { "Content-Type": "application/json", "Product": "31G", "Cookie": cookie_value } res = self.run_method.run_main(method, url, data, header=header_json, params=data) elif header == "write_Cookie1": # res = self.run_method.run_main(method, url, data, header=header_json, params=data) use_header = UseHeader(res) use_header.write_cookie() elif header == "get_Cookie1": use_json = UseJson("../data_config/cookie.json") cookie = use_json.get_data("apsid") cookies = {"apsid": cookie} res = self.run_method.run_main(method, url, data=data, header=cookies, params=data) else: res = self.run_method.run_main(method, url, data, header, params=data) if self.tool.is_contain(expect, res): self.data.write_actual( i, json.dumps(res, ensure_ascii=False)) # 返回值为中文时,不乱码 self.data.write_result(i, "PASS") pass_count.append(i) else: self.data.write_actual( i, json.dumps(res, ensure_ascii=False)) self.data.write_result(i, "FAIL") with open(log_file, "a", encoding="utf-8") as lf: lf.write("\n第{}条用例实际结果与期望结果不一致:\n".format(i)) lf.write("期望结果:{}\n实际结果:{}\n".format(expect, res)) fail_count.append(i) else: no_run_count.append(i) except Exception as e: self.data.write_result(i, str(e)) with open(log_file, "a", encoding="utf-8") as lf: lf.write("\n第%s条用例报错:\n" % i) initLogging(log_file, e) fail_count.append(i)
def go_on_run(self): res = None rows_count = self.data.get_case_lines() success_count = 0 fail_count = 0 total_count = 0 for i in range(1, rows_count): is_run = self.data.get_is_run(i) if is_run: url = self.read_int.get_value() + self.data.get_url(i) method = self.data.get_request_method(i) request_data = self.data.get_data_for_json(i) header = self.data.get_header(i) depend_case = self.data.is_depend(i) if depend_case is not None: self.depend_data = DependentData(depend_case) # 获取的依赖响应数据 depend_response_data = self.depend_data.get_data_for_key(i) # 获取依赖的key depend_key = self.data.get_depend_field(i) if depend_key is None: # 如果依赖字段为空,则替换 url 中的{id} url = url.replace('{id}', depend_response_data) else: # 如果依赖字段有值,则更改请求字段对应的 depend_key 的 value为依赖请求的结果 request_data[depend_key] = depend_response_data if method != 'get': request_data = json.dumps(request_data) total_count += 1 res = self.run_method.run_main(method, url, request_data, header) expect_res_str = self.data.get_expect_data(i).__str__() if expect_res_str is not None: expect_res_list = expect_res_str.split('/') all_expect_pass = True for a in expect_res_list: # 断言报错继续执行 try: # self.assertIn(self.data.get_expect_data(i), json.dumps(res), "返回结果不是期望结果") # 因为返回结果中不会有中文,所以将期望值的中文转成 Unicode 的 byte ,为了匹配 assertIn 的参数类型,再转成 utf-8的str self.assertIn(a.encode("unicode_escape").decode('utf-8'), json.dumps(res), "返回结果不是期望结果") print("用例编号:", self.data.get_case_id(i), ",接口自动化测试通过") self.data.write_result(i, 'pass') except AssertionError as e: print("用例编号:", self.data.get_case_id(i), ",接口自动化测试失败!!!\n", "断言异常为:", e) self.data.write_result(i, 'fail' + e.__str__().encode("utf-8").decode('utf-8')) # fail_count += 1 all_expect_pass = False if all_expect_pass: success_count += 1 else: fail_count += 1 else: # 断言报错继续执行 try: self.assertEqual(res.status_code, 204, '该操作不成功,无返回结果') print("用例编号:", self.data.get_case_id(i), ",接口自动化测试通过") self.data.write_result(i, 'pass') success_count += 1 except AssertionError as e: print("用例编号:", self.data.get_case_id(i), ",接口自动化测试失败!!!\n", "断言异常为:", e) self.data.write_result(i, 'fail' + e.__str__()) fail_count += 1 if type(res) is not dict: self.data.write_res_to_pre(i, res.__str__().encode("utf-8").decode('utf-8')) else: # self.data.write_res_to_pre(i, json.dumps(res)) # 回写 excel时,通过json.dumps() 会将中文编译成 Unicode,这里直接处理成 str # 结果回写需要是 json格式,将单引号换成双引号 pre_json = res.__str__().replace('\'', '\"') self.data.write_res_to_pre(i, pre_json) print("本次接口自动化测试运行用例总数:", total_count) print("本次接口自动化测试通过用例数:", success_count) print("本次接口自动化测试失败用例数:", fail_count)
def __init__(self): self.run_method = RunMethod() self.data = GetData() self.com_util = CommonUtil() self.depend_data = DependentData()
def go_on_run(self): """程序执行""" pass_count = [] fail_count = [] request_data_file = '' res = None # 获取用例数 rows_count = self.data.get_case_lines() # 第一行索引为0 for i in range(1, rows_count): is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) #request_data = json.load(self.data.get_request_data(i)) expect = self.data.get_expcet_data(i) token = self.data.is_token(i) depend_case = self.data.is_depend(i) headers = self.data.get_headers(i) r = self.data.get_request_data(i) # 上传文件处理 if r != None: if r.endswith('jpg') | r.endswith('png') | r.endswith( 'docx') | r.endswith('doc') | r.endswith( 'ppt') | r.endswith('pptx'): #其他文件暂不考虑 file_payload = { 'file': (r, open('../' + r, 'rb')) } #, "image/jpg" m = MultipartEncoder(file_payload) headers['Content-Type'] = m.content_type request_data = m #处理依赖 elif depend_case != None: self.depend_data = DependentData(depend_case) # 获取依赖key和value [id1:3] depend_response_data = self.depend_data.get_data_for_key( i) # {caseid:{id1:1,id2:2}} for caseid in depend_response_data: for k in depend_response_data[caseid]: y = '${' + caseid + ',' + k + '}' if r.find(y): t = r.replace( y, str(depend_response_data[caseid][k])) r = t request_data = json.loads(r, encoding='utf-8') else: # 没有依赖直接转换输出 request_data = json.loads(r, encoding='utf-8') else: request_data = {} # 如果token字段值为write则将该接口的返回的token写入到token.json文件,如果为yes则读取token.json文件 if token == "write": res = self.run_method.run_main(method, url, request_data, headers) op_header = OperationHeader(res) op_header.write_token() elif token == 'yes': op_json = OperationJson("../dataconfig/token.json") token = op_json.get_data('data') headers.update(token) #request_data = dict(request_data, **token) # 把请求数据与登录token合并,并作为请求数据 res = self.run_method.run_main(method, url, request_data, headers) else: res = self.run_method.run_main(method, url, request_data, headers) #将响应数据写入excel log().info("响应结果\n%s", res) self.data.write_respond_data(i, res) if expect != None: if self.com_util.is_contain(expect, res): self.data.write_result(i, "Pass") pass_count.append(i) else: self.data.write_result(i, "failed") fail_count.append(i) else: print(f"用例ID:case-{i},预期结果不能为空") # 发送邮件 # self.send_email.send_main(pass_count, fail_count) print(f"通过用例数:{len(pass_count)}") print(f"失败用例数:{len(fail_count)}")
def go_on_run(self): #结果 res = None #通过率 pass_count = [] #失败率 fail_count = [] #获取case个数(获取有数据的单元格行) rows_count = self.data.get_case_lines() #循环判断要执行的case,跳过第一行标题开始循环 for i in range(1, rows_count): #获取是否执行 is_run = self.data.get_is_run(i) # print (is_run) # #判断is_run的值为true时执行 if is_run: # print i #获取url url = self.data.get_request_url(i) # print (url) #获取请求类型 method = self.data.get_request_method(i) # print method #获取数据 request_data = self.data.get_data_for_json(i) print(request_data) print(type(request_data)) break expect = self.data.get_expect_data(i) # print(expect) # print(type(expect)) # break #获取header(默认demo) # header = self.data.demo_header() #获取excel中指定header header = self.data.is_header(i) # print header #获取依赖数据 depend_case = self.data.is_depend(i) #判断是否需要依赖数据 if depend_case != None: self.depend_data = DependentData(depend_case) #获取依赖的响应数据 depend_response_data = self.depend_data.get_data_for_key(i) #获取依赖key depend_key = self.data.get_depend_field(i) #将获取到的依赖case响应数据赋值给依赖key request_data[depend_key] = depend_response_data #获取响应数据 res = self.run_method.run_main(method, url, request_data, header) # print (res) #打印结果并转码为字符串类型 # print res.text.encode('unicode-escape').decode('string_escape') #判断返回结果与预期结果比对 if self.com_util.is_contain(expect, res): self.data.write_result(i, 'pass') #成功率统计 pass_count.append(i) else: self.data.write_result(i, res) #失败率统计 fail_count.append(i)
def base_run(self): res = None pass_count = [] fail_count = [] no_run_count = [] rows_count = self.data.get_case_rows() log_file = "../log/interface-demo02.log" # 每次执行用例前,将log日志文件清空数据 with open(log_file, "w") as lf: lf.seek( 0, 0 ) # 加上lf.seek(0),把文件定位到position 0;若没有这句话,文件是定位到数据最后,truncate也是从最后这里删除。 lf.truncate() self.tool.write_mobile() # 向get_mobile.json 中写入手机号码 for i in range(1, rows_count): try: is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) data = self.data.get_request_excel_data( i) # 直接读取 excel 中的 data if data.find("${mobile}") != -1: data = data.replace("${mobile}", self.tool.get_mobile()) elif data.find("${idCardNumber}") & data.find( "${name}") != -1: data = data.replace("${idCardNumber}", self.tool.getRandomIdCard()) name = "雨点" + self.tool.num_chinese( self.tool.get_mobile()[-4:]) data = data.replace("${name}", name) elif data.find("${businessLicenseNumber}") != -1: data = data.replace("${businessLicenseNumber}", self.tool.license_no()) header = self.data.get_request_header( i) # 获取 excel 中的 header 关键字 expect_data = self.data.get_expect_data(i) expect = json.loads(expect_data) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData(depend_case) depend_response_data = self.depend_data.get_value_for_key( i) # 获取 依赖字段的 响应数据 if header == '{"Content-Type":"application/json"}': header_json = eval(header) res = self.run_method.run_main(method, url, data, header=header_json, params=data) elif header == '{"Content-Type":"multipart/form-data"}': data = eval(data) # 把 str 转成 dict with open("H:/wahh.jpg", "rb") as f: # 打开上传文件 r = f.read() files = {"file": ("wahh.jpg", r, "image/jpeg")} use_json = UseJson("../data_config/config_header.json") header_json = use_json.read_data() # header_json = { # "Content-Type": "multipart/form-data", # 不要画蛇添足写这一句 # "Cookie": "SESSION=NGExN2Y0MzUtNjVhNy00MDRkLWIyZjItMGFjZWVlMDFiZjM5"} response = requests.post(url=url, data=data, files=files, headers=header_json) # 获取返回请求 res = response.text elif header == 'get_cookie': use_json = UseJson("../data_config/config_header.json") cookie_value = use_json.get_data("Cookie") header_json = { "Content-Type": "application/json", "Cookie": cookie_value } res = self.run_method.run_main(method, url, data, header=header_json, params=data) elif header == "write_Cookie1": use_header = UseHeader(res) use_header.write_cookie() elif header == "get_Cookie1": use_json = UseJson("../data_config/config_cookie.json") cookie = use_json.get_data("apsid") cookies = {"apsid": cookie} res = self.run_method.run_main(method, url, data=data, header=cookies, params=data) else: res = self.run_method.run_main(method, url, data, header, params=data) if self.tool.is_contain(expect, res): self.data.write_result(i, "pass") pass_count.append(i) else: self.data.write_result(i, json.dumps(res)) with open(log_file, "a", encoding="utf-8") as lf: lf.write("\n第%s条用例实际结果与期望结果不一致:\n" % i) lf.write("期望结果:%s\n实际结果:%s\n" % (expect, res)) fail_count.append(i) else: no_run_count.append(i) except Exception as e: self.data.write_result(i, str(e)) with open(log_file, "a", encoding="utf-8") as lf: lf.write("\n第%s条用例报错:\n" % i) initLogging(log_file, e) fail_count.append(i)
def test_run(self): res = None pass_count = [] fail_count = [] skip_count = [] # 获取多少行 rows_count = self.data.get_case_lines() for i in range(2, rows_count + 1): run_num = [2, 1] is_run = self.data.get_is_run(i) message = self.data.get_api_msg(i) api_name = self.data.get_api_name(i) if is_run: url_path = self.data.get_request_url(i) url = config_global.base_url[0] + url_path method = self.data.get_request_method(i) data = self.data.get_request_data(i) code = self.data.get_http_code_data(i) expect = self.data.get_expect_data(i) headers = self.data.get_request_headers(i) depend_Value = self.data.get_depend_value(i) # tiquzhi set_key = self.data.get_set_key(i) wait_key = self.data.get_waiting_replace_key(i) actual_key = self.data.get_actual_replace_key(i) header = get_header_value() if data != None: if '88888888' in data: data = data.replace("88888888", "17154654546") data = json.loads(data) if headers != None: try: with open(depend_data_path, 'r', encoding='utf-8') as f: header_value = json.load(f) header[headers] = header_value["token"] except Exception as e: logging.info("错误为:", e) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData(depend_case) # 获取的依赖响应 depend_response_data = self.depend_data.get_data_for_key(i) # 获取依赖的key depend_key = self.data.get_depend_field(i) # 更新参数值 data[depend_key] = depend_response_data '''待提取的key''' if wait_key != None: try: with open(depend_data_path, 'r', encoding='utf-8') as f: dependvalue = f.read() depend_value_dict = json.loads(dependvalue) wait_key_list = str_for_list(wait_key) actual_key_list = str_for_list(actual_key) for index_num in range(len(wait_key_list)): Wait_key = wait_key_list[index_num] Act_key = actual_key_list[index_num] depend_value_key = depend_value_dict[Act_key] data[Wait_key] = depend_value_key except Exception as e: logging.info("错误为:", e) def fail_run(): response = self.run_method.run_main( method, url, data, header) res = response[0] # print('response---->',response) # print('res---->',res) global http_code http_code = response[1] # print(type(http_code), http_code) # 断言 if int(code) == http_code: if self.common_util.is_contain(expect, res): logging.info('\033[1;32;m%s接口:%s->接口执行通过\033[0m' % (api_name, message)) writeTestResult(excelObj.get_data(), rowNo=i, testResult='pass') pass_count.append(i) if depend_Value != None: self.depend_data = DependentData(depend_case) self.depend_data.save_depend_value( res, depend_Value, set_key) else: fail = run_num[0] fail -= 1 run_num[0] = fail while run_num[0]: fail_num = run_num[1] run_num[1] = run_num[1] + 1 print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1)) time.sleep(1) logging.info( "\033[0;43;41m%s接口:%s->接口执行失败\033[0m" % (api_name, message)) fail_run() writeTestResult(excelObj.get_data(), rowNo=i, testResult='faild', errorInfo=res) fail_count.append(i) else: fail = run_num[0] fail -= 1 run_num[0] = fail while run_num[0]: fail_num = run_num[1] run_num[1] = run_num[1] + 1 print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1)) time.sleep(1) logging.info("\033[0;43;41m%s->接口执行失败\033[0m" % message) fail_run() writeTestResult(excelObj.get_data(), rowNo=i, testResult='faild', errorInfo=res) fail_count.append(i) fail_run() else: logging.info('%s接口:%s->接口不执行' % (api_name, message)) skip_count.append(i) writeTestResult(excelObj.get_data(), rowNo=i, testResult='skip') # 发送邮件 logging.info("正在发送邮件,请等待。。。")
def fail_run(): response = self.run_method.run_main( method, url, data, header) res = response[0] # print('response---->',response) # print('res---->',res) global http_code http_code = response[1] # print(type(http_code), http_code) # 断言 if int(code) == http_code: if self.common_util.is_contain(expect, res): logging.info('\033[1;32;m%s接口:%s->接口执行通过\033[0m' % (api_name, message)) writeTestResult(excelObj.get_data(), rowNo=i, testResult='pass') pass_count.append(i) if depend_Value != None: self.depend_data = DependentData(depend_case) self.depend_data.save_depend_value( res, depend_Value, set_key) else: fail = run_num[0] fail -= 1 run_num[0] = fail while run_num[0]: fail_num = run_num[1] run_num[1] = run_num[1] + 1 print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1)) time.sleep(1) logging.info( "\033[0;43;41m%s接口:%s->接口执行失败\033[0m" % (api_name, message)) fail_run() writeTestResult(excelObj.get_data(), rowNo=i, testResult='faild', errorInfo=res) fail_count.append(i) else: fail = run_num[0] fail -= 1 run_num[0] = fail while run_num[0]: fail_num = run_num[1] run_num[1] = run_num[1] + 1 print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1)) time.sleep(1) logging.info("\033[0;43;41m%s->接口执行失败\033[0m" % message) fail_run() writeTestResult(excelObj.get_data(), rowNo=i, testResult='faild', errorInfo=res) fail_count.append(i)
def test_go_on_run(self): run_method = RunRequest() data = GetData() cases_num = data.get_case_lines() fail_count = 0 pass_count = 0 for i in range(1, cases_num): url = data.get_request_url(i) method = data.get_request_method(i) cookie_flag = data.get_is_header(i) request_data = data.get_data_from_json(i) is_run = data.get_is_run(i) expect = data.get_expect_data(i) depend_case = data.get_case_depend(i) depend = DependentData(depend_case) if is_run: print("--------------run ", i) if depend_case != None: # 有依赖case print("-------------->depend") # 获取依赖的响应数据 depend_response_data = depend.get_data_from_key(i) depend_field = data.get_field_depend(i) # 更新依赖字段的值 request_data[depend_field] = depend_response_data if cookie_flag == 'write': # 需要写入cookies res = run_method.run_main(method, url, request_data) print(res) operate_header = OperateHeader(res.json()) operate_header.write_cookie() elif cookie_flag == 'yes': # 需要携带cookies operate_json = OpereatJson('../config/cookie.json') cookies = operate_json.read_data() # print(cookies) res = run_method.run_main(method, url, request_data, cookies) else: res = run_method.run_main(method, url, request_data) com = CommonUtil() res_str = bytes.decode(res.content) # self.data.write_result(i,res_str) if com.is_contains(expect, res_str): print("测试通过") # self.assertTrue(True) pass_count = pass_count + 1 data.write_result(i, "pass") else: print("测试失败") # self.assertTrue(False) data.write_result(i, res_str) fail_count = fail_count + 1 res_dict = data.search_dict(res.content) if res_dict: res_format = json.dumps(res_dict, ensure_ascii=False, indent=2, sort_keys=True) print(res_format) else: print(res.content) print(pass_count, fail_count) send = SendMail() send.send_main(pass_count, fail_count)
class GuestCase: def __init__(self): self.json_file = "/Users/mac/Desktop/测试资料/蜗牛家产品线/woniujia_cc_jiekou/woniujia_cc_jiekou_git/woniujia_cc_project/dataconfig/request_pram.json" self.sheet_name = "客户模块" self.sheet_id = 5 self.data = GetData(self.json_file, self.sheet_name, self.sheet_id) self.run_method = RunMethod() self.util = CommonUtil() self.email = SendEmail() def go_to_guest(self): # self.run_comm = RunCommon(self.excel_file, self.json_file) # self.run_comm.go_run_case() # 获取用例行数 row_count = self.data.get_case_line() pass_count = [] fail_count = [] for i in range(1, row_count): is_run = self.data.get_is_run(i) if is_run: url = self.data.get_url(i) request_type = self.data.get_request_type(i) data = self.data.get_data_for_json(i) if i == 1: header = self.data.get_header(i) response = self.run_method.run_main( request_type, url, data, header) res = json.loads(response) # 获取token、operid并写入文件中 with open(self.util.base_dir(), 'w') as f: f.write(res["data"]["token"] + "," + res["data"]["id"]) else: token = self.util.getToken(0) token_header = self.data.get_token_header(i, token) depend_morecase = self.data.is_more_depend(i, 0) # 判断是否存在依赖 if depend_morecase != None: self.depend_data = DependentData( depend_morecase, self.excel_file, self.json_file) dependent_response_data = self.depend_data.get_data_for_key( i, 0) depend_key = self.data.get_dependent_key(i, 0) print("depend_key", depend_key) if url == "http://182.61.33.241:8089/app/api/private/1.0/client/": request_url = url + dependent_response_data response = self.run_method.run_main( request_type, request_url, data, token_header) if url == "http://182.61.33.241:8089/app/api/private/1.0/reporting/addorupdate": depend_param2 = self.data.is_more_depend(i, 1) self.depend_data2 = DependentData( depend_param2, self.excel_file, self.json_file) dependent_response_data2 = self.depend_data2.get_data_for_key( i, 1) depend_key2 = self.data.get_dependent_key(i, 1) jsonData = json.loads(data) jsonData[depend_key] = dependent_response_data jsonData[depend_key2] = dependent_response_data2 requestData = json.dumps(jsonData) response = self.run_method.run_main( request_type, url, requestData, token_header) else: jsonData = json.loads(data) print("data:", data) jsonData[depend_key] = dependent_response_data requestData = json.dumps(jsonData) response = self.run_method.run_main( request_type, url, requestData, token_header) else: if url == "http://182.61.33.241:8089/app/api/private/1.0/follow/clientpage": oper_id = self.util.getToken(1) json_data = json.loads(data) json_data["operId"] = oper_id request_data = json.dumps(json_data) response = self.run_method.run_main( request_type, url, request_data, token_header) else: response = self.run_method.run_main( request_type, url, data, token_header) expect_res = self.data.get_except(i) print("期望结果:", expect_res) if self.util.is_contain(expect_res, response): self.data.write_result(i, "测试通过", self.sheet_id) pass_count.append(i) print("测试通过") else: self.data.write_result(i, "测试失败", self.sheet_id) fail_count.append(i) print("测试失败") self.data.write_response(i, response, self.sheet_id) self.email.send_main(pass_count, fail_count) return response
def go_on_run(self): """程序执行""" pass_count = [] fail_count = [] res = None # 获取用例数 rows_count = self.data.get_case_lines() # 第一行索引为0 for i in range(1, rows_count): is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) request_data = (self.data.get_data_for_json(i)) request_data = json.dumps(request_data) expect = self.data.get_expcet_data(i) header = self.data.is_header(i) depend_case = self.data.is_depend(i) headers = {'Content-Type': 'application/json;charset=utf-8'} if depend_case != None: self.depend_data = DependentData(depend_case) # 获取依赖的响应数据 depend_response_data = self.depend_data.get_data_for_key(i) # 获取依赖的key depend_key = self.data.get_depend_field(i) # 更新请求字段 request_data[depend_key] = depend_response_data # 如果header字段值为write则将该接口的返回的token写入到token.json文件,如果为yes则读取token.json文件 #if True: if header == 'write': res = self.run_method.run_main(method=method, url=url, data=request_data, header=headers) res = self.run_method.run_main(method, url, request_data, headers) print(res) op_header = OperationHeader(res) op_header.write_token() elif header == 'yes': op_json = OperationJson(tokenPath + "/token.json") token = op_json.get_data('token') request_data = dict(request_data, **token) # 把请求数据与登录token合并,并作为请求数据 res = self.run_method.run_main(method, url, request_data) else: res = self.run_method.run_main(method, url, request_data) if expect != None: dict_res = json.loads(res) if expect == dict_res["code"]: #if self.com_util.is_contain(expect, res): self.data.write_result(i, "Pass") pass_count.append(i) else: self.data.write_result(i, res) fail_count.append(i) else: print(f"用例ID:case-{i},预期结果不能为空") # 发送邮件 # self.send_email.send_main(pass_count, fail_count) print(f"通过用例数:{len(pass_count)}") print(f"失败用例数:{len(fail_count)}")
def go_on_run(self): res = None pass_count = [] fail_count = [] no_run_count = [] rows_count = self.data.get_case_lines() # 每次执行用例之前将log日志文件清空数据 log_file = '../log/log.txt' with open(log_file, 'w') as f: f.seek(0, 0) # 加上f.seek(0),把文件定位到position 0;没有这句的话,文件是定位到数据最后,truncate也是从最后这里删除 f.truncate() # 清空数据 # 循环执行每行用例 for i in range(1, rows_count): try: is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) # 获取请求参数 data = self.data.get_data_value(i) # 获取excel文件中header关键字 header_key = self.data.get_request_header(i) # 获取json文件中header_key对应的头文件数据 header = self.data.get_header_value(i) expect = self.data.get_expect_data(i) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData(depend_case) # 获取依赖字段的响应数据 depend_response_data = self.depend_data.get_value_for_key(i) # 获取请求依赖的key depend_key = self.data.get_depend_field(i) # 将依赖case的响应返回中某个字段的value赋值给该接口请求中某个参数 data[depend_key] = depend_response_data # cookie相关的没有跑通,代码逻辑是正常的,但是模拟登陆返回一直是非法请求 if header_key == 'write_Cookies': res = self.run_method.run_main(method, url, data, header, params=data) op_header = OperationHeader(res) op_header.write_cookie() elif header_key == 'get_Cookies': op_json = OperationJson('../dataconfig/cookie.json') cookie = op_json.get_data('apsid') cookies = {'apsid': cookie} res = self.run_method.run_main(method, url, data, header=cookies, params=data) else: res = self.run_method.run_main(method, url, data, header, params=data) ''' get请求参数是params:request.get(url='',params={}),post请求数据是data:request.post(url='',data={}) excel文件中没有区分直接用请求数据表示,则data = self.data.get_data_value(i)拿到的数据,post请求就是data=data,get请就是params=data ''' # excel中拿到的expect数据是str类型,但是返回的res是dict类型,两者数据比较必须都是字符类型 if self.com_util.is_contain(expect, json.dumps(res)): self.data.write_result(i, 'pass') pass_count.append(i) else: # 返回的res是dict类型,要将res数据写入excel中,需将dict类型转换成str类型 self.data.write_result(i, json.dumps(res)) with open(log_file, 'a', encoding='utf-8') as f: f.write("\n第%s条用例实际结果与预期结果不一致:\n" % i) f.write("Expected:%s\n Actual:%s\n" % (expect, res)) fail_count.append(i) else: no_run_count.append(i) except Exception as e: # 将异常写入excel的测试结果中 self.data.write_result(i, str(e)) # 将报错写入指定路径的日志文件里 with open(log_file, 'a', encoding='utf-8') as f: f.write("\n第%s条用例报错:\n" % i) initLogging(log_file, e) fail_count.append(i) self.send_mail.send_main(pass_count, fail_count, no_run_count)
class TestAllCase(unittest.TestCase): def setUp(self): self.run = TestRun() self.data = GetData() self.run_method = RunMethod() self.common_util = CommonUtil() self.send_email = SendEmail() self.excel = OperationExcel() self.sheet_obj = self.excel.get_data() @ddt.data(*all_data) def test_all_case(self, data): # 提取值 提取值的key 待替换的key 实际替换的key get_num, get_case_des, get_api, get_exec, get_module, get_pre, get_url, get_header, get_method, get_parames, get_hope_http_code, get_hope_response, get_results, get_run_time, get_error_msg, get_depend_Value, get_setting_key, get_wait_key, get_actual_key = data print(get_num, get_case_des, get_api, get_exec, get_module, get_pre, get_url, get_header, get_method, get_parames, get_hope_http_code, get_hope_response, get_results, get_run_time, get_error_msg, get_depend_Value, get_setting_key, get_wait_key, get_actual_key) print("=" * 20) print(*all_data) # run.test_run() res = None pass_count = [] fail_count = [] skip_count = [] run_num = [2, 1] is_run = get_exec # exec message = get_case_des api_name = get_api if is_run == 'y': url_path = get_url url = config_global.base_url[0] + url_path method = get_method data = get_parames code = get_hope_http_code expect = get_hope_response headers = get_header depend_Value = get_depend_Value # tiquzhi set_key = get_setting_key wait_key = get_wait_key actual_key = get_actual_key header = get_header_value() if data != None: if '88888888' in data: data = data.replace("88888888", "17154654546") data = json.loads(data) if headers != None: try: with open(depend_data_path, 'r', encoding='utf-8') as f: header_value = json.load(f) header[headers] = header_value["token"] except Exception as e: logging.info("错误为:", e) # depend_case = data.is_depend(num) depend_case = get_num # # if depend_case != None: # self.depend_data = DependentData(depend_case) # # 获取的依赖响应 # depend_response_data = self.depend_data.get_data_for_key(i) # # # 获取依赖的key # depend_key = self.data.get_depend_field(i) # # # 更新参数值 # data[depend_key] = depend_response_data '''待提取的key''' if wait_key != None: try: with open(depend_data_path, 'r', encoding='utf-8') as f: dependvalue = f.read() depend_value_dict = json.loads(dependvalue) wait_key_list = str_for_list(wait_key) actual_key_list = str_for_list(actual_key) for index_num in range(len(wait_key_list)): Wait_key = wait_key_list[index_num] Act_key = actual_key_list[index_num] depend_value_key = depend_value_dict[Act_key] data[Wait_key] = depend_value_key except Exception as e: logging.info("错误为:", e) def fail_run(): response = self.run_method.run_main(method, url, data, header) res = response[0] # print('response---->',response) # print('res---->',res) global http_code http_code = response[1] # print(type(http_code), http_code) # 断言 if int(code) == http_code: if self.common_util.is_contain(expect, res): logging.info('\033[1;32;m%s接口:%s->接口执行通过\033[0m' % (api_name, message)) self.assertTrue(True) # 断言 writeTestResult(excelObj.get_data(), rowNo=get_num, testResult='pass') pass_count.append(get_num) if depend_Value != None: self.depend_data = DependentData(depend_case) self.depend_data.save_depend_value( res, depend_Value, set_key) else: fail = run_num[0] fail -= 1 run_num[0] = fail while run_num[0]: fail_num = run_num[1] run_num[1] = run_num[1] + 1 print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1)) time.sleep(1) logging.info( "\033[0;43;41m%s接口:%s->接口执行失败\033[0m" % (api_name, message)) fail_run() writeTestResult(excelObj.get_data(), rowNo=get_num, testResult='faild', errorInfo=res) self.assertTrue(False, msg=res) # 断言 fail_count.append(get_num) else: fail = run_num[0] fail -= 1 run_num[0] = fail while run_num[0]: fail_num = run_num[1] run_num[1] = run_num[1] + 1 print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1)) time.sleep(1) logging.info("\033[0;43;41m%s->接口执行失败\033[0m" % message) fail_run() writeTestResult(excelObj.get_data(), rowNo=get_num, testResult='faild', errorInfo=res) fail_count.append(get_num) fail_run() else: logging.info('%s接口:%s->接口不执行' % (api_name, message)) skip_count.append(get_num) writeTestResult(excelObj.get_data(), rowNo=get_num, testResult='skip')
def go_on_run(self): """程序执行""" pass_count = [] fail_count = [] no_run_count = [] res = None # 获取用例数 rows_count = self.data.get_case_lines() print(rows_count) # 第一行索引为0 for i in range(1, rows_count): print("i:", i) is_run = self.data.get_is_run(i) print(is_run) if is_run: url = self.data.get_request_url(i) print("url:", url) method = self.data.get_request_method(i) print("method:", method) request_data = self.data.get_data_for_json(i) print("request_data:", request_data) print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$", type(request_data)) expect = self.data.get_expect_data(i) print("expect:", expect) header = self.data.is_header(i) print("header:", header) token = self.data.is_token(i) print("token:", token) depend_case = self.data.is_depend(i) print("depend_case:", depend_case) if depend_case != None: self.depend_data = DependentData(depend_case) # 获取依赖的响应数据 print("#### i", i) depend_response_data = self.depend_data.get_data_for_key(i) print("##################") print("1depend_response_data:", depend_response_data) # 获取依赖的key depend_key = self.data.get_depend_field(i) print("depend_key:", depend_key) # 更新请求字段 request_data.get( 'params')[depend_key] = depend_response_data #request_data = json.dumps(request_data, ensure_ascii=False) print("request_data:", request_data) print(type(request_data)) # 如果header字段值为write则将该接口的返回的token写入到token.json文件,如果为yes则读取token.json文件 if header == "write_token": print("********************") res = self.run_method.run_main(method, url, request_data).json() print("res:", res) print("res type", type(res)) #print("res.json():", res.json()) op_header = OperationHeader(res) op_header.write_token() elif header == 'write_cookie' and token == 'yes': print("case22222222222222") op_json = OperationJson("../dataconfig/token.json") token = op_json.get_data('data') request_data = dict(request_data, **token) # 把请求数据与登录token合并,并作为请求数据 print("login_data", request_data) res = self.run_method.run_main(method, url, request_data) print("res_login:"******"@@@@@@@@@@@@@@@@@@@@@@@@@@") op_json1 = OperationJson('../dataconfig/cookie.json') op_json2 = OperationJson('../dataconfig/token.json') cookies = op_json1.get_data('cookie') token = op_json2.get_data('data') request_data = dict(request_data, **token) print("post_data:", request_data) print("cookie:", cookies) new_value = json.dumps(request_data.get("params")) request_data["params"] = new_value res = self.run_method.run_main(method, url, request_data, cookies=cookies) print("res:", type(res)) else: res = self.run_method.run_main(method, url, request_data) if expect != None: if self.com_util.is_contain(expect, res): self.data.write_result(i, "Pass") pass_count.append(i) if type(res) is dict: self.data.write_real_res(i, json.dumps(res)) else: self.data.write_real_res(i, json.dumps(res.json())) else: self.data.write_result(i, "Fail") fail_count.append(i) if type(res) is dict: self.data.write_real_res(i, json.dumps(res)) else: self.data.write_real_res(i, json.dumps(res.json())) else: print(f"用例ID:case-{i},预期结果不能为空") else: self.data.write_result(i, "Not run") no_run_count.append(i) # 发送邮件 print(f"通过用例数:{len(pass_count)}") print(f"失败用例数:{len(fail_count)}") print(f"未执行败用例数:{len(no_run_count)}") self.send_email.send_main(pass_count, fail_count, no_run_count)
def go_on_run(self): """获取用例行数""" row_count = self.data.get_case_line() print("用例行数:", row_count) pass_count = [] fail_count = [] #循环执行用例 for i in range(1, row_count): is_run = self.data.get_is_run(i) print("i的值:", i) print("is_run:", is_run) if is_run: url = self.data.get_url(i) print("url:", url) request_type = self.data.get_request_type(i) print("request_type:", request_type) data = self.data.get_data_for_json(i) print("data:", data) #dependent_case = self.data.is_depend(i) dependent_more_case = self.data.is_more_depend(i, 0) print("dependent_more_case:", dependent_more_case) if dependent_more_case != None: self.dependent_data = DependentData(dependent_more_case) #获取依赖的响应数据 dependent_response_data = self.dependent_data.get_data_for_key( i, 0) print("dependent_response_data", dependent_response_data) token_value = self.common_util.getToken(0) token_header = self.data.get_token_header(i, token_value) print("token_header:", token_header) if url == "http://182.61.33.241:8089/app/api/private/1.0/client/": new_url = url + dependent_response_data print("------------------------------------") print("new_url:", new_url) result = self.run_method.run_main( request_type, new_url, data, token_header) else: #获取依赖的key depend_key = self.data.get_dependent_key(i, 0) print("depend_key", depend_key) jsonData = json.loads(data) print("data:", data) jsonData[depend_key] = dependent_response_data requestData = json.dumps(jsonData) result = self.run_method.run_main( request_type, url, requestData, token_header) else: if i == 1: header = self.data.get_header(i) print("header:", header) #result = self.run_method.post_main(url, data, header) result = self.run_method.run_main( request_type, url, data, header) res = json.loads(result) #获取token值 with open(self.common_util.base_dir(), 'w') as f: f.write(res["data"]["token"] + "," + res["data"]["id"]) print("获取token:", res["data"]["token"]) else: token_value = self.common_util.getToken(0) token_header = self.data.get_token_header( i, token_value) if url == "http://182.61.33.241:8089/app/api/private/1.0/follow/clientpage": oper_id = self.common_util.getToken(1) jsonData = json.loads(data) jsonData["operId"] = oper_id request_data = json.dumps(jsonData) result = self.run_method.run_main( request_type, url, request_data, token_header) else: result = self.run_method.run_main( request_type, url, data, token_header) print("返回结果:", result) except_res = self.data.get_except(i) print("except_res:", except_res) if self.common_util.is_contain(except_res, result): self.data.write_result(i, "测试通过") print("测试通过") pass_count.append(i) else: self.data.write_result(i, "测试失败") print("测试失败") fail_count.append(i) print("打印结果:", result) print("通过数:", len(pass_count)) print("失败数:", len(fail_count)) # self.email.send_main(pass_count, fail_count) return result
def go_on_run(self): res = None pass_count = [] fail_count = [] no_run_count = [] rows_count = self.data.get_case_lines() #每次执行时清楚log文件 log_file = '../log/log.txt' with open(log_file, 'w') as f: f.seek(0, 0) #定位光标位置 f.truncate() #删除文件 for i in range(1, rows_count): try: is_run = self.data.get_is_run(i) if is_run: url = self.data.get_request_url(i) method = self.data.get_request_method(i) #获取请求参数 data = self.data.get_data_value(i) #获取excel文件的关键字 header_key = self.data.get_request_header(i) #获取json文件中header对应的文件数据 header = self.data.get_header_value(i) expect = self.data.get_expect_data(i) depend_case = self.data.is_depend(i) if depend_case != None: self.depend_data = DependentData(depend_case) #获取依赖字段的响应数据 depend_response_data = self.depend_data.get_value_for_key( i) #获取请求依赖的key depend_key = self.data.get_depend_field(i) #将依赖case的响应返回某个字段value赋值给接口请求 data[depend_key] = depend_response_data if header_key == 'write_Cookies': res = self.run_method.run_main(method, url, data, header, params=data) op_header = OperationHeader(res) op_header.write_cookie() elif header_key == 'get_Cookies': op_json = OperationJson('../dataconfig/cookie.json') cookie = op_json.get_data('apsid') cookies = {'apsid': cookie} res = self.run_method.run_main(method, url, data, header=cookies, params=data) else: res = self.run_method.run_main(method, url, data, header, params=data) #get请求参数是params:request.get(url='',params={}),post请求数据是data:request.post(url='',data={}) #excel文件中没有区分直接用请求数据表示,则data = self.data.get_data_value(i)拿到的数据,post请求就是data=data,get请就是params=data #excel拿到的expect数据时str类型,返回的是res是dic类型 if self.com_util.is_contain(expect, json.dumps(res)): self.data.write_result(i, 'pass') pass_count.append(i) else: #返回res是dic类型,res数据写入excel中,需要dict转换为str self.data.write_result(i, json.dumps(res)) with open(log_file, 'a', encoding='utf-8') as f: f.write('\n第%s条用例不相同\n' % i) f.write('expect:%s\n Actual:%s\n' % (expect, res)) fail_count.append(i) else: no_run_count.append(i) except Exception as e: #异常写入测试结果 self.data.write_result(i, str(e)) #报错写入指定路径文件 with open(log_file, 'a', encoding='utf-8') as f: f.write('\n第%s条测试用例' % i) initlogging(log_file, e) fail_count.append(i) self.send_email.send_main(pass_count, fail_count, no_run_count)