Python接口自动化实战 ( 第一阶段) - 封装接口请求类和异常处理
从零封神!Python接口自动化测试全栈落地(Requests+pytest+Allure+CI)实战班 | 学完直接扔进简历!
1.封装http接口请求
已经实现了一个简单的接口请求,接下来就要考虑封装这个请求,在后面的用例中,只需要传递参数(URL ,Params,cookie,heade,method 等)每次去调用这个请求类,
然后根据接口的请求类型来调用相应的处理,如果是get方式就调用get方法,如果是post方式就调用post方法,经过这样的设计后,测试方法中的代码结构会更加清晰有层次,也更容易维护。
代码实现:
# 导入requests包 import requestsclass HttpRequest:def http_request(self, url, params, http_method):res = ''if http_method.upper()=='POST':try:res=requests.post(url,params)print("正在进行post请求")except Exception as e:print("post请求出现了异常:{0}".format(e))elif http_method.upper()=='GET':try:res=requests.post(url,params)print("正在进行get请求")except Exception as e:print("get请求出现了异常:{0}".format(e))return resif __name__ == '__main__':url = 'http://27.154.55.14:8180/api/fcb2bcrm/webRegister'datas = {'LoginAccount': 'testapi01@emai.com', 'Password': '123456', 'Type': 'Pro'}res=HttpRequest().http_request(url, datas, 'post')print(res.json())
执行结果:
4.TestCase调用封装好的http请求,并添加异常处理。
在运行用例的时候,发现无论断言成功与否,测试报告都是全部通过,后面发现是在处理异常的时候,没有将异常抛出。
以下是test_register.py 修改后的代码:
# 导入 import unittest import requests from Common.http_request import HttpRequestclass TestRegister (unittest.TestCase): # 类必须以Test开头,继承TestCaseurl = 'http://27.154.55.14:8180/api/fcb2bcrm/webRegister'def setUp(self):print("======开始执行测试用例======")def tearDown(self):print("======测试用例执行完毕======")# 测试用例 - 正常注册def test_register_normal(self): # 每一条测试用例以test_开头# 发送请求params = {'LoginAccount': 'apitest09@emai.com', 'Password': '123456', 'Type': 'Pro'}# res = requests.post(self.url,params)res = HttpRequest().http_request(self.url,params,'post')# 断言:根据实际测试场景,可以查询数据库是否有新注册的用户、对比接口的返回信息、对比状态码等等try:self.assertEqual(200, res.status_code)print('成功测试用户:{}'.format(params['LoginAccount']))except AssertionError as e:print('Failed')raise e # 注意一定要抛出异常# 测试用例 - 重复注册def test_register_existing(self):# 发送请求params = {'LoginAccount': 'apitest05@emai.com', 'Password': '123456', 'Type': 'Pro'}# res = requests.post(self.url,params)res = HttpRequest().http_request(self.url, params, 'post')# 断言try:self.assertIn("The email has been registered", res.json()['Message'])print("执行结果:pass:", res.json()['Message'])except AssertionError as e:print('执行结果:Failed')raise e# 测试用例 - 无效的邮箱格式去注册def test_register_invalid_email(self):# 发送请求params = {'LoginAccount': 'testapi@emai', 'Password': '123456', 'Type': 'Pro'}# res = requests.post(self.url,params)res = HttpRequest().http_request(self.url, params, 'post')# 断言try:self.assertIn("valid email", res.json()['Message'])print("执行结果:pass:", res.json()['Message'])except AssertionError as e:print('执行结果:Failed')raise e
从零封神!Python接口自动化测试全栈落地(Requests+pytest+Allure+CI)实战班 | 学完直接扔进简历!