def test_login(self, case_info): with allure.step("对当前的case进行参数化替换"): # 对当前的case进行参数化替换 case_info = self.params_replace_current_case_info(case_info) with allure.step("发起请求"): res = HttpRequest().http_request(case_info) # 断言 with allure.step("响应结果断言"): self.assert_expected(case_info, res) member_id = jmespath.search("data.id", res.json()) if member_id != None: with allure.step("保存token到环境变量里"): token = jmespath.search("data.token_info.token", res.json()) if case_info["case_id"] == 1: # 2、保存到环境变量中 setattr(RelyData, "token1", token) elif case_info["case_id"] == 2: # 2、保存到环境变量中 setattr(RelyData, "token2", token) elif case_info["case_id"] == 3: # 2、保存到环境变量中 setattr(RelyData, "token3", token)
def Pay(surroundings, orderNum, payPassword, payType, cookies): # 查询买家各种钱包明细 myPayWay_url = f"http://m.{surroundings}.hobay.com.cn/ribbon-api/userWallet/myPayWay" myPayWay_headers = {"login": ""} myPayWay_res = HttpRequest().http_request(myPayWay_url, "get", headers=myPayWay_headers, cookies=cookies) # 支付订单 pay_headers = {"login": "", "payPassword": payPassword} if payType in [3, 4]: pay_url = f'http://m.{surroundings}.hobay.com.cn/ribbon-api/batchOrders/payAllCBP' pay_data = { "tradeNUm": orderNum, "payType": payType, "shareWalletUserId": "", "shareWalletId": "" } pay_res = HttpRequest().http_request(pay_url, "post", json=pay_data, cookies=cookies, headers=pay_headers) elif payType in [5, 6]: if payType == 5: shareWalletUserId = myPayWay_res.json( )['results']['myPayWay']['myKinship'][0]['shareWalletUserId'] shareWalletId = myPayWay_res.json( )['results']['myPayWay']['myKinship'][0]['shareWalletId'] elif payType == 6: shareWalletUserId = myPayWay_res.json( )['results']['myPayWay']['myWages']['shareWalletUserId'] shareWalletId = myPayWay_res.json( )['results']['myPayWay']['myWages']['shareWalletId'] pay_url = f'http://m.{surroundings}.hobay.com.cn/ribbon-api/batchOrders/payAllCBP' pay_data = { "tradeNUm": orderNum, "payType": payType, "shareWalletUserId": shareWalletUserId, "shareWalletId": shareWalletId } pay_res = HttpRequest().http_request(pay_url, "post", json=pay_data, cookies=cookies, headers=pay_headers) elif payType == 7: pay_url = f'http://m.{surroundings}.hobay.com.cn/ribbon-api/pay/payCash' pay_data = {"tradeNum": orderNum} pay_res = HttpRequest().http_request(pay_url, "post", data=pay_data, cookies=cookies, headers=pay_headers) return pay_res
def test_register(self, caseInfo): with allure.step("读数据库获取没有注册过的手机号码"): # 读数据库获取没有注册过的手机号码 if caseInfo["case_id"] == 1: mobile_phone = self.get_random_phone() setattr(RelyData, "mobile_phone1", mobile_phone) elif caseInfo["case_id"] == 2: mobile_phone = self.get_random_phone() setattr(RelyData, "mobile_phone2", mobile_phone) elif caseInfo["case_id"] == 3: mobile_phone = self.get_random_phone() setattr(RelyData, "mobile_phone3", mobile_phone) with allure.step("对当前的case进行参数化替换"): # 对当前的case进行参数化替换 case_info = self.params_replace_current_case_info(caseInfo) with allure.step("发起请求"): res=HttpRequest().http_request(case_info) with allure.step("响应结果断言"): # 1、响应结果断言 self.assert_expected(case_info, res) with allure.step("数据库断言"): # 2、数据库断言 self.assert_SQL(case_info) memberId = jmespath.search("data.id", res.json()) if memberId != None: with allure.step("保存手机号、用户id、密码到环境变量里"): mobile_phone = jmespath.search("data.mobile_phone", res.json()) # 3、注册成功的密码--从用例数据里面 pwd = case_info['input_params']['pwd'] if case_info["case_id"] == 1: setattr(RelyData, "mobile_phone1", mobile_phone) setattr(RelyData, "member_id1", memberId) setattr(RelyData, "pwd1", pwd) elif case_info["case_id"] == 2: # 2、保存到环境变量中 setattr(RelyData, "mobile_phone2", mobile_phone) setattr(RelyData, "member_id2", memberId) setattr(RelyData, "pwd2", pwd) elif case_info["case_id"] == 3: # 2、保存到环境变量中 setattr(RelyData, "mobile_phone3", mobile_phone) setattr(RelyData, "member_id3", memberId) setattr(RelyData, "pwd3", pwd)
def myPayWay(surroundings, cookies): # 查询买家各种钱包明细 myPayWay_url = f"http://m.{surroundings}.hobay.com.cn/ribbon-api/userWallet/myPayWay" myPayWay_headers = {"login": ""} myPayWay_res = HttpRequest().http_request(myPayWay_url, "get", headers=myPayWay_headers, cookies=cookies) return myPayWay_res.json()
def test_add_loan(self, case_info): with allure.step("对当前的case进行参数化替换"): # 对当前的case进行参数化替换 case_info = self.params_replace_current_case_info(case_info) with allure.step("发起请求"): res = HttpRequest().http_request(case_info) # 断言 with allure.step("响应结果断言"): self.assert_expected(case_info, res) memberId = jmespath.search("data.member_id", res.json()) if memberId != None: loan_id = jmespath.search("data.id", res.json()) # 2、保存到环境变量中 setattr(RelyData, "loan_id", loan_id)
def run(test_data): for item in test_data: print('正在测试的用例是{0}'.format(item['title'])) res = HttpRequest().http_request(item['url'],eval(item['data']),item['method'],cookie=getattr(GetCookie,'COOKIE')) if res.cookies: setattr(GetCookie,'COOKIE',res.cookies) print('请求的结果是{0}'.format(res.json())) try: assert str(item['expected']) == res.json()['code'] TestResult = 'pass' except Exception as e: TestResult = 'failed' print('接口返回的数据为{}'.format(e)) raise e finally: ReadExcel(data_file,'recharge').write_back_data(item['case']+1,TestResult,str(res.json()))
def test_api(self, item): print("测试开始:{0}".format(item['title'])) #测试标题 res = HttpRequest().http_request(item['url'], eval(item['data']), item['http_method'], getattr(GetData, 'Cookie')) #获取请求 if res.cookies: #利用反射获取cookies setattr(GetData, 'Cookie', res.cookies) try: #进行断言 self.assertEqual(str(item['expect']), res.json()['code']) TestResult = 'PASS' except Exception as e: TestResult = 'Failed' print("执行用例出错:{}".format(e)) raise e finally: #将测试结果返回文档中 DoExcel().write_back(case_path, item['sheet_name'], item['case_id'] + 1, str(res.json()), TestResult)
def get_qrCode(surroundings, orderId, cookies): # 获取买家订单序列号 OrderDetail_url = f'http://m.{surroundings}.hobay.com.cn/ribbon-api/batchOrders/queryOrderDetail' OrderDetail_data = {"orderId": orderId, "buyOrSell": 1} OrderDetail_headers = {'login': ''} OrderDetail_res = HttpRequest().http_request(OrderDetail_url, 'post', data=OrderDetail_data, headers=OrderDetail_headers, cookies=cookies) qrCode = OrderDetail_res.json()['data']['qrCode'] return qrCode
def test_api(self, item): global TestResult res = HttpRequest().http_request(item['url'], eval(item['data']), item['http_method'], getattr(GetData, "Cookie")) actual_code = res.json()['code'] # 实际结果 if res.cookies: # 如果有cookies,那就res.cookies赋值给Cookie属性 setattr(GetData, 'Cookie', res.cookies) # 反射 try: self.assertEqual(str(item['expected_code']), actual_code) print("用例{0}正确!".format(item['case_id']), item['title']) TestResult = 'PASS' except AssertionError as e: print("用例错误!错误原因是{0}:".format(e)) TestResult = 'Failed' raise e # 异常处理完后记得抛出 finally: # 不管怎样都得写入Excel DoExcel().write_back(test_case_path, item['sheet_name'], item['case_id'] + 1, str(res.json()), TestResult) print("响应体:", "\n", res.json())
def get_productStockId(surroundings, product_name, cookies): # 卖家-商品管理 product_url = f'http://m.{surroundings}.hobay.com.cn/ribbon-api/product/queryPageProductsByType?currentPage=1&type=2&pageSize=10' product_headers = {"login": ""} product_res = HttpRequest().http_request(product_url, "get", headers=product_headers, cookies=cookies) # print("商品管理出售中的商品是:", product_res.json()) # 获取商品规格id product_data = product_res.json()['data']['result'] for i in range(0, len(product_data)): if product_data[i]['title'] == product_name: productId = product_data[i]['id'] productStockId = product_data[i]['productStockWithStockImages'][0][ 'id'] return productId, productStockId
def SaveOrder(surroundings,productId, productStockId, cookies, addressId=""): SaveOrder_headers = {"login": ""} # 获取商品类型 type_url = 'http://m.test.hobay.com.cn/ribbon-api/batchCart/immediatelyBuySettlement' type_data = {"productStockIdAndNums": [{"num": 1, "productStockId": productStockId, "productId": productId}]} type_res = HttpRequest().http_request(type_url, "post", json=type_data, cookies=cookies, headers=SaveOrder_headers) goods_type = type_res.json()['data']['type'] # 提交订单 SaveOrder_url = f'http://m.{surroundings}.hobay.com.cn/ribbon-api/batchOrders/immediatelySaveOrder' SaveOrder_data = {"message": "", "couponUserId": "", "addressId": addressId, "productStockIdAndNums": [{"num": 1, "productStockId": productStockId}], "type": goods_type} SaveOrder_res = HttpRequest().http_request(SaveOrder_url, "post", json=SaveOrder_data, cookies=cookies, headers=SaveOrder_headers) return SaveOrder_res
def boss_setting_requests(surroundings, phone, operational_setting): ''' Parameters ---------- surroundings:test/dev1/mtest phone:手机号 operational_setting:[{'个人焕商': 1000650}, {'省代理商': 1000646, '市代理商': 1000647, '区代理商': 1000648}] Returns:None ------- ''' if operational_setting == "未设置": salesRatio = "0" freeSalesRatio = "0" tcoRatio = "0" else: salesRatio = str(operational_setting['销售']) freeSalesRatio = str(operational_setting['业务焕商']) tcoRatio = str(operational_setting['TCO']) # 登录 login_url = f'http://boss.{surroundings}.hobay.com.cn/bosszuul/boss/user/login' # 登录 login_data = {"phone": phone, "password": "******"} login_res = HttpRequest().http_request(login_url, "post", data=login_data) # print("BOSS登录结果是:", login_res.json()) # 设置运营比例 agentId = login_res.json()['id'] secondPayagentRatio_url = f'http://boss.{surroundings}.hobay.com.cn/bosszuul/order/secondPayagentRatio/addOrUpdateSecondPayagentRatio' secondPayagentRatio_data = { "agentId": agentId, "freeSalesRatio": freeSalesRatio, "salesRatio": salesRatio, "tcoRatio": tcoRatio } secondPayagentRatio_res = HttpRequest().http_request( secondPayagentRatio_url, "post", data=secondPayagentRatio_data, cookies=login_res.cookies)
def setUpClass(cls) -> None: """ 登录获取(后台)token :return: """ # 获取主机地址 HOST = ReadConfig.get_config(case_config_path, 'ADDRESS', 'host') url = f'{HOST}/api/auth/oauth/user/token' param = {"username": "******", "password": "******"} header = { "Content-Type": "application/json;charset=UTF-8", "Authorization": "Basic QmFzZVBsYXRmb3JtOjEyMzQ1Ng==" } res = HttpRequest().http_request(url, param, 'post', 'params', headers=header) setattr(GetToken, "Token", res.json()['value']) # 反射设置token值 get_header = { "Content-Type": "application/json;charset=UTF-8", "Authorization": "Bearer " + getattr(GetToken, "Token") } setattr(GetToken, "header", get_header) # 反射设置header值
def test_api(self,item): ###########################获取ticket################################################### if item["data"].find("&{ticket}") != -1: item["data"] = item["data"].replace('&{ticket}', str(getattr(GetData, "ticket"))) ###########################获取项目-删除企业\通讯录-组织架构-新增一级部门\通讯录-组织架构-新增员工\加入企业 company_id################ if item["data"].find("&{company_id}") != -1: item["data"] = item["data"].replace('&{company_id}', str(getattr(GetData, "company_id"))) ###########################获取通讯录-添加好友project_id################################## if item["data"].find("&{project_id}") != -1: item["data"] = item["data"].replace('&{project_id}', str(getattr(GetData, "project_id"))) ###########################获取通讯录-一级目录departmentId/通讯录-组织架构-新增员工######################## if item["data"].find("&{departmentId}") != -1: item["data"] = item["data"].replace('&{departmentId}', str(getattr(GetData, "departmentId"))) ###########################获取通讯录-二级目录departmentId2################################## if item["data"].find("&{departmentId2}") != -1: item["data"] = item["data"].replace('&{departmentId2}', str(getattr(GetData, "departmentId2"))) ###########################获取通讯录-三级目录departmentId3################################## if item["data"].find("&{departmentId3}") != -1: item["data"] = item["data"].replace('&{departmentId3}', str(getattr(GetData, "departmentId3"))) ###########################获取通讯录-三级目录departmentId3_2用于上移下移################################## if item["data"].find("&{departmentId3_2}") != -1: item["data"] = item["data"].replace('&{departmentId3_2}', str(getattr(GetData, "departmentId3_2"))) ###########################通讯录-组织架构-新增员工/mid####################################### if item["data"].find("&{mid}") != -1: item["data"] = item["data"].replace('&{mid}', str(getattr(GetData, "mid"))) ###########################项目-企业查找(企业存在)company_no####################################### if item["data"].find("&{company_no") != -1: item["data"] = item["data"].replace('&{company_no}', str(getattr(GetData, "company_no"))) ###########################通讯录-企业审核拒绝####################################### if item["data"].find("&{companyForm_idStr1") != -1: item["data"] = item["data"].replace('&{companyForm_idStr1}', str(getattr(GetData, "companyForm_idStr1"))) if item["data"].find("&{companyForm_member_idStr1") != -1: item["data"] = item["data"].replace('&{companyForm_member_idStr1}', str(getattr(GetData, "companyForm_member_idStr1"))) ###########################通讯录-企业审核通过####################################### if item["data"].find("&{companyForm_idStr") != -1: item["data"] = item["data"].replace('&{companyForm_idStr}', str(getattr(GetData, "companyForm_idStr"))) if item["data"].find("&{companyForm_member_idStr") != -1: item["data"] = item["data"].replace('&{companyForm_member_idStr}', str(getattr(GetData, "companyForm_member_idStr"))) ###########################项项目-获取文件管理列表pjId_test####################################### if item["data"].find("&{pjId_test") != -1: item["data"] = item["data"].replace('&{pjId_test}', str(getattr(GetData, "pjId_test"))) ###########################项目-一级文件夹重命名(未重复)nodeId_dir####################################### if item["data"].find("&{nodeId_dir") != -1: item["data"] = item["data"].replace('&{nodeId_dir}', str(getattr(GetData, "nodeId_dir"))) ###########################项目-二级目录移动到根目录nodeId_dir2####################################### if item["data"].find("&{nodeId_dir2") != -1: item["data"] = item["data"].replace('&{nodeId_dir2}', str(getattr(GetData, "nodeId_dir2"))) ###########################项目-二级目录移动到根目录####################################### if item["data"].find("&{parentId_file_d") != -1: item["data"] = item["data"].replace('&{parentId_file_d}', str(getattr(GetData, "parentId_file_d"))) ###########################项目-根目录的二级文件夹移动到模型文件夹####################################### if item["data"].find("&{parentId_file_d1") != -1: item["data"] = item["data"].replace('&{parentId_file_d1}', str(getattr(GetData, "parentId_file_d1"))) ###########################切换用户时,需要清空cookies,不然有问题################################## while item["title"] == "登录-获取ticket": setattr(GetData, "ticket", None) setattr(GetData, "Cookie", None) break #*****************************************用例开始执行******************************************************* #*********************************************************************************************************** if item["title"] == "登录-获取ticket" or item["title"] == "登录-获取用户信息" or item["title"] == "项目-企业列表"\ or item["title"] == "消息-标记已读" or item["title"] == "": res = HttpRequest().http_request_json(item["url"], eval(item["data"]), item["method"],getattr(GetData, "Cookie"), eval(item["headers"])) else: res = HttpRequest().http_request_data(item["url"], (item["data"]), item["method"], getattr(GetData, "Cookie"),eval(item["headers"])) #########################存储ticket及断言############################################# while item["title"] == "登录-获取ticket" : ticket = re.findall(r'\'ticket\':\'(.*?)\'', res.text)[0] if len(ticket)!=0: DoExcel().write_back(test_case_path, item["sheet_name"], item["case_id"] + 1, ticket,"pass") setattr(GetData, "ticket", ticket) else: DoExcel().write_back(test_case_path, item["sheet_name"], item["case_id"] + 1, "ticket为空","failed") break ###########################"登录-获取ccbim_cookie"及断言################################## while item["title"] == "登录-获取ccbim_cookie" : if res.cookies: setattr(GetData, "Cookie", res.cookies) DoExcel().write_back(test_case_path,item["sheet_name"],item["case_id"]+1,str(res.cookies),"pass") else: DoExcel().write_back(test_case_path, item["sheet_name"], item["case_id"] + 1, "没有获取到ccbim_cookie", "failed") break while item["title"] != "登录-获取ticket" and item["title"] != "登录-获取ccbim_cookie": try: if item["title"] == "登录-获取用户信息": self.assertEqual(res.json()["info"]["mName"],item["expected"]) if item["title"] == "项目-获取参与项目": self.assertIsNotNone(res.json()["query"]) setattr(GetData, "project_id", res.json()["list"][0]["pjId"]) if item["title"] == "通讯录-企业审核获取请求列表": self.assertIsNotNone(res.json()["query"]) setattr(GetData, "companyForm_idStr", res.json()["list"][0]["id"]) setattr(GetData, "companyForm_member_idStr", res.json()["list"][0]["mid"]) setattr(GetData, "companyForm_idStr1", res.json()["list"][1]["id"]) setattr(GetData, "companyForm_member_idStr1", res.json()["list"][1]["mid"]) if item["title"] == "项目-创建企业": self.assertEqual(res.json()["obj"]["company_name"], item["expected"]) setattr(GetData, "company_id", res.json()["obj"]["company_id"]) setattr(GetData, "company_no", res.json()["obj"]["company_no"]) if item["title"] == "项目-删除企业": self.assertEqual(res.json()["success"], item["expected"]) if item["title"] == "项目-企业列表": type(res.json()["list"]) is list if item["title"] == "项目-企业查找(企业存在)": item["expected"] = item["expected"].replace('&{company_no}',str(getattr(GetData, "company_no"))) self.assertEqual(res.json()["list"][0]["company_no"], item["expected"]) if item["title"] == "项目-企业查找(企业不存在)": res.json()["list"] is None if item["title"] == "项目-按项目名称搜素(已存在项目)" or item["title"] == "项目-按项目名称搜素(不存在项目)" \ or item["title"] == "通讯录-审核拒绝后人员查询" or item["title"] == "通讯录-审核通过后人员查询": self.assertEqual(res.json()["query"]["totalItem"], item["expected"]) if item["title"] == "通讯录-添加朋友": self.assertEqual(res.json()["success"], item["expected"]) if item["title"] == "项目-获取所有文件夹的parentId ": type(res.json()["list"]) is list setattr(GetData, "parentId_file_d", res.json()["list"][0]["parentId"]) setattr(GetData, "parentId_file_d1", res.json()["list"][1]["nodeId"]) if item["title"] == "通讯录-同意好友请求": self.assertEqual(res.json()["fApply"]["mName"], item["expected"]) if item["title"] == "通讯录-添加已存在的用户" or item["title"] == "项目-删除企业(有成员)" or item["title"] == \ "通讯录-组织架构-删除二级部门(存在三级部门)" or item["title"] == "通讯录-企业ID只能修改一次" or item["title"] == \ "通讯录-企业ID已存在" or item["title"] == "项目-超值管理员申请加入自己企业" or item["title"] == \ "通讯录-组织架构-新增三级部门上移(已在第一位)" or item["title"] == "通讯录-组织架构-新增三级部门下移(已在最后一位)"\ or item["title"] == "项目-一级文件夹重命名(已存在文件夹)": self.assertEqual(res.json()["errorMsg"], item["expected"]) if item["title"] == "通讯录-组织架构-员工搜素": self.assertEqual(res.json()["query"]["member_name"], item["expected"]) setattr(GetData, "mid", res.json()["list"][0]["mid"]) if item["title"] == "项目-获取我参与的项目": self.assertEqual(res.json()["list"][0]["pjName"], item["expected"]) setattr(GetData, "pjId_test", res.json()["list"][0]["pjId"]) setattr(GetData, "coId_test", res.json()["query"]["coId"]) if item["title"] == "项目-获取文件管理列表": self.assertEqual(res.json()["query"]["totalItem"], item["expected"]) setattr(GetData, "nodeId_dir", res.json()["list"][0]["nodeId"]) if item["title"] == "项目-文件管理新建二级目录": self.assertEqual(res.json()["msg"], item["expected"]) if item["title"] == "项目-获取新建二级目录列表": self.assertEqual(res.json()["query"]["totalItem"], item["expected"]) setattr(GetData, "nodeId_dir2", res.json()["list"][0]["nodeId"]) if item["title"] == "通讯录-组织架构-设置企业管理员查看管理员列表": self.assertEqual(res.json()["query"]["totalItem"], item["expected"]) if item["title"] == "通讯录-查看企业信息": item["expected"] = item["expected"].replace('&{company_id}',str(getattr(GetData, "company_id"))) self.assertEqual(str(res.json()["info"]["coId"]), item["expected"]) if item["title"] == "通讯录-组织架构-设置企业管理员" or item["title"] == "通讯录-组织架构-取消企业管理员" \ or item["title"] == "通讯录-删除好友" or item["title"] == "通讯录-组织架构-新增员工" or item["title"] == \ "通讯录-组织架构-编辑用户信息" or item["title"] == "通讯录-组织架构-移动用户到一级部门" or item["title"] \ == "通讯录-组织架构-删除用户" or item["title"] == "通讯录-组织架构-新增三级部门2上移" or item["title"] == \ "通讯录-组织架构-新增三级部门2下移" or item["title"] == "通讯录-组织架构-移动用户到三级部门" \ or item["title"] == "通讯录-组织架构-删除新增用户(用户在三级部门)" or item["title"] == "通讯录-组织架构-删除三级部门" or item[ "title"] == "通讯录-组织架构-删除三级部门2" or item["title"] == "通讯录-组织架构-删除二级部门" or item["title"] == \ "通讯录-组织架构-删除一级部门" or item["title"] == "通讯录-组织架构-新增三级部门2继续下移(已在最后一位)" or item["title"] == "通讯录-组织架构-一级部门重命名" or \ item["title"] == "通讯录-修改企业信息" or item["title"] == "项目-加入企业" or item["title"] == "项目-加入企业(重复请求)" \ or item["title"] == "通讯录-企业审核拒绝" or item["title"] == "通讯录-企业审核通过" or item["title"] == "项目-新建一级文件夹" or item["title"] \ == "项目-一级文件夹重命名(未重复)" or item["title"] == "项目-二级目录移动到根目录" or item["title"] == "项目-根目录的二级文件夹移动到模型文件夹": self.assertEqual(res.json()["msg"], item["expected"]) if item["title"] == "消息-标记已读" or item["title"] == "通讯录-组织架构-新增一级部门" or item["title"] == \ "通讯录-组织架构-新增二级部门" or item["title"] == "通讯录-组织架构-新增三级部门" or item["title"] == "通讯录-组织架构-新增三级部门2": self.assertEqual(res.json()["success"], item["expected"]) if item["title"] == "通讯录-组织架构-获取一级部门ID" or item["title"] == "通讯录-组织架构-获取二级部门ID" \ or item["title"] == "通讯录-组织架构-获取三级部门ID" or item["title"] == "通讯录-组织架构-获取三级部门2ID": if res.json()["list"] is not None: if item["title"] == "通讯录-组织架构-获取一级部门ID": setattr(GetData, "departmentId", res.json()["list"][0]["departmentId"]) if item["title"] == "通讯录-组织架构-获取二级部门ID": setattr(GetData, "departmentId2", res.json()["list"][1]["departmentId"]) if item["title"] == "通讯录-组织架构-获取三级部门ID": setattr(GetData, "departmentId3", res.json()["list"][2]["departmentId"]) if item["title"] == "通讯录-组织架构-获取三级部门2ID": setattr(GetData, "departmentId3_2", res.json()["list"][3]["departmentId"]) Testresult = "pass" except Exception as e: Testresult = "Failed" my_logger.error("第{}条用例断言错误是:error is{}".format(item["case_id"], e)) raise e except IndexError as f: Testresult = "pass,但是未获取到下一个接口所用数据" my_logger.error("条用例执行返回结果未取到数据:error is{}".format(item["case_id"],f)) finally: DoExcel().write_back(test_case_path,item["sheet_name"],item["case_id"]+1,str(res.json()),Testresult) ########################执行到最后一条用例执行,保存excel################################## if test_data[-1]["title"] == item["title"]: DoExcel.save_close_excel(test_case_path) print("最后一条用例", item["title"]) print(test_data[-1]["title"]) break
def test_api(self, item): # 获取主机地址 HOST = ReadConfig.get_config(case_config_path, 'ADDRESS', 'host') item['url'] = HOST + item['url'] # 获取url #提交data为空,关联值get_value不为空 if item['data'] == None and item['get_value'] != None: if type(eval(item['get_value'])) == dict: res = HttpRequest().http_request(item['url'], None, item['method'], item['type'], headers=getattr( GetToken, "header")) if res.json()['msg'] == 'OK': get_data = eval(item['get_value']) for keys in get_data.keys(): key = keys value = get_data[key] add = 'res.json()' + value add = eval(add) OperaConfig.write_config(file_path, key, key, add) try: self.assertEqual(item['expected'], res.json()['msg']) TestResult = 'PASS' except AssertionError as e: TestResult = 'FAIL' print("执行用例出错:{0}".format(e)) raise e finally: #写回结果(str(res.json()),excel只能写字符串,数字,不能写字典 DoExcel(test_case_path, item['sheet_name']).write_back( item['case_id'] + 1, str(res.json()), TestResult) print("获取到的结果是:{0}".format(res.json())) # 提交data不为空,关联值get_value不为空(字符串:使用值) elif item['data'] != None and item['get_value'] != None and type( item['get_value']) == str: data1 = OperaConfig.read_config(file_path, item['get_value'], item['get_value']) #获取配置文件值 if item['url'].find(item['get_value']) != -1: url = item['url'].replace("{{" + item['get_value'] + "}}", data1) res = HttpRequest().http_request(url, eval(item['data']), item['method'], item['type'], headers=getattr( GetToken, "header")) elif item['data'] != None and item['data'].find( item['get_value']) != -1: data = item['data'].replace("{{" + item['get_value'] + "}}", data1) res = HttpRequest().http_request(item['url'], eval(data), item['method'], item['type'], headers=getattr( GetToken, "header")) try: self.assertEqual(item['expected'], res.json()['msg']) TestResult = 'PASS' except AssertionError as e: TestResult = 'FAIL' print("执行用例出错:{0}".format(e)) raise e finally: #写回结果(str(res.json()),excel只能写字符串,数字,不能写字典 DoExcel(test_case_path, item['sheet_name']).write_back(item['case_id'] + 1, str(res.json()), TestResult) print("获取到的结果是:{0}".format(res.json())) # 提交data为空,关联值get_value为空(普通get) elif item['data'] == None and item['get_value'] == None: res = HttpRequest().http_request(item['url'], None, item['method'], item['type'], headers=getattr( GetToken, "header")) try: self.assertEqual(item['expected'], res.json()['msg']) TestResult = 'PASS' except AssertionError as e: TestResult = 'FAIL' print("执行用例出错:{0}".format(e)) raise e finally: # 写回结果(str(res.json()),excel只能写字符串,数字,不能写字典 DoExcel(test_case_path, item['sheet_name']).write_back(item['case_id'] + 1, str(res.json()), TestResult) print("获取到的结果是:{0}".format(res.json())) # 其他 else: res = HttpRequest().http_request(item['url'], eval(item['data']), item['method'], item['type'], headers=getattr( GetToken, "header")) try: self.assertEqual(item['expected'], res.json()['msg']) TestResult = 'PASS' except AssertionError as e: TestResult = 'FAIL' print("执行用例出错:{0}".format(e)) raise e finally: #写回结果(str(res.json()),excel只能写字符串,数字,不能写字典 DoExcel(test_case_path, item['sheet_name']).write_back(item['case_id'] + 1, str(res.json()), TestResult) print("获取到的结果是:{0}".format(res.json()))