python+requests+unittest执行自动化接口测试
1、安装requests、xlrd、json、unittest库
<1>pip 命令安装:
pip install requests
pip install xlrd
pip install json
pip install unittest
<2> pycharm里安装
2、利用Page Object Model 设计理念创建六类Python Package(也可根据项目要求具体实施)
![](https://upload-images.jianshu.io/upload_images/23053034-21ea9dc9e429e9de.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
3、先在base包里创建一个Base_Page.py
![](https://upload-images.jianshu.io/upload_images/23053034-4e378bdf1994a168.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<1>导入模块,并创建Base类,封装各类请求方法
import requests #导入requests模块 class Base(): def method_post(self,url,params = None,data = None,headers = None,files = None): return requests.post(url = url,params = params,data = data,headers = headers,files = files) def method_get(self,url,params = None,data = None,headers = None,files = None): return requests.get(url = url,params = params,data = data,headers = headers,files = files) def method_put(self,url,params = None,data = None,headers = None,files = None): return requests.put(url = url,params = params,data = data,headers = headers,files = files) def method_delete(self,url,params = None,data = None,headers = None,files = None): return requests.delete(url = url,params = params,data = data,headers = headers,files = files)
因为每一个请求都会有params参数或是data参数,但是不可能两个都存在,所以这里用了None,依次类推
<2>适配于接口用例执行,读取Excel表时,将各类请求做判断,当符合哪一种时,就去执行哪一种
def requests_type(self,method,url,params = None,data = None,headers = None,files = None): if method =='post' or method =='POST': return self.method_post(url = url,params = params,data = data,headers = headers,files = files) elif method =='get' or method =='GET': return self.method_get(url = url,params = params,data = data,headers = headers,files = files) elif method =='put' or method =='PUT': return requests.put(url = url,params = params,data = data,headers = headers,files = files) elif method =='delete' or method =='DELETE': return requests.delete(url = url,params = params,data = data,headers = headers,files = files)
<3> 将几种请求做简单调试,调试通了,那么我们就可以进行下一项
![](https://upload-images.jianshu.io/upload_images/23053034-1e3d7eb193629000.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
也可以对需要拿到cookie的接口进行封装方法保存:
def Get_Login_cookie(self,data): res = self.method_post(url = "请求网址",data = data) return {"userId":str(res.json()['result']['userId']),"sessionId":res.json()['result']['sessionId']}
之后我们要将base页验证的这些代码做清除,否则的话永远都是调的这些接口
4、再common类下创建commons.py文件,并创建common类
![](https://upload-images.jianshu.io/upload_images/23053034-cfb1bde39cc04f3c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<1> 封装日志方法
这里我添加了一个data包,用于存放xlrd表,以及html报告存放路径、log日志存放路径
log_path = r'D:\PycharmProjects\自动化接口\自动化接口测试\report\logs' report_html = r'D:\PycharmProjects\自动化接口\自动化接口测试\report\html' read_xlrd = r'D:\PycharmProjects\自动化接口\自动化接口测试\data' class Common(): #封装日志方法 def get_logs(self,path = log_path): import logging,time logs = logging.getLogger() logs.setLevel(logging.DEBUG) path = path+'/' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.log' write_file = logging.FileHandler(path,'a+',encoding='utf-8') write_file.setLevel(logging.DEBUG) set_logs = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - %(levelname)s - %(message)s') write_file.setFormatter(set_logs) pycharm_text = logging.StreamHandler() pycharm_text.setFormatter(set_logs) logs.addHandler(write_file) logs.addHandler(pycharm_text) return logs
<2> 封装读取Excel表方法,把他转换成字典形式,方便json格式读取
# 读取Excel表方法,方便后续读取接口用例数据 def ReadExcelTypeDict(self,file_name,path = read_xlrd): path = path+'/' + file_name import xlrd work_book = xlrd.open_workbook(path) # 打开Excel表 sheets = work_book.sheet_names() # 获取所有的sheets页 DatasList = [] for sheet in sheets: sheets = work_book.sheet_by_name(sheet) nrows = sheets.nrows for i in range(0,nrows): values = sheets.row_values(i) DatasList.append(values) title_list = DatasList[0] content_list = DatasList[1:] new_list = [] for content in content_list: dic = {} for i in range(len(content)): dic[title_list[i]] = content[i] new_list.append(dic) return new_list #最终返回为字典形式 有键和值
为什么要转换格式呢?
这里就涉及到了怎么设计一个自动化接口用例
![](https://upload-images.jianshu.io/upload_images/23053034-71e7c3a5d83f614b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
用例的参数值要用json格式写入,不要有空格
预期结果的出参也要用json格式写入
不要有' '值都要用" "包起来
<3>封装一个生成HTML报告方法
# 封装一个HTML报告方法 def GetHtmlResult(self,suite,title,path = report_html): import HTMLTestReportCN,time path = path + '/' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.html' with open(path,'wb+') as f: run = HTMLTestReportCN.HTMLTestRunner(stream=f,description='用户相关接口测试报告',tester='小白',title = title) run.run(suite)
其余还有需要补充的可以继续添加,我这里三个基本够用
5、在case包下创test用例,并调用我们在base页封装好的请求api以及common中的读取Excel数据表联合使用
<1>创建test_login.py
![](https://upload-images.jianshu.io/upload_images/23053034-1844e377175d8ab5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
<2> 导入unittest、common类下的commons类、ddt数据驱动、Base下的base_page页
import unittest import ddt import 自动化接口测试.common.commons as common from 自动化接口测试.base.Base_Page import Base
<3> 搭建unittest框架内部,并填充方法
import unittest import ddt import 自动化接口测试.common.commons as common from 自动化接口测试.base.Base_Page import Base r = common.Common().ReadExcelTypeDict('cezxhi .xlsx') # 拿到具体的Excel表数据 @ddt.ddt #导入ddt模块 class TestLogin(unittest.TestCase): @classmethod def setUpClass(cls) -> None: # setupclass类方法 全部用例开始前执行一次 cls.logs = common.Common().get_logs() # 导入日志方法 cls.logs.debug('开始写入接口自动化测试用例') @classmethod def tearDownClass(cls) -> None: cls.logs.debug('自动化接口用例结束') def setUp(self) -> None: self.logs.debug('开始本条接口用例') def tearDown(self) -> None: self.logs.debug('结束本条用例') @ddt.data(*r) # 引入ddt模块,读取拿到的数据 def test_logins(self,pars): # 用例方法名开头必须已test pars参数为接收的表数据值 import json #导入json模块 dic = json.loads(pars['body参数值']) # 将Excel数据中的参数值转变为json格式 url = pars['接口地址'] # 拿到请求url yuqi = pars['预期结果'] # 拿到预期结果 fs = pars['请求方式'] # 拿到请求方式 result = Base().requests_type(method = fs,url = url,data = dic) # 填充base页的请求api self.assertEqual(result.text,yuqi) # 进行断言 看用例是否通过
<4> 执行用例后生成测试报告:
if __name__ == '__main__': load = unittest.TestLoader().loadTestsFromTestCase(TestLogin) #使用loader加载方式 来找寻所有已test开头的用例 suite = unittest.TestSuite([load,]) common.Common().GetHtmlResult(suite,'登录测试用例')
如果对软件测试、接口测试、自动化测试、面试经验交流。感兴趣可以加软件测试交流:1085991341,还会有同行一起技术交流。
<5> copy当前要执行的脚本路径,添加到运行方式为python里
![](https://upload-images.jianshu.io/upload_images/23053034-ceca1bda6e2f6c64.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/23053034-c741998859597b5a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/23053034-1462c5748b58a4f8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/23053034-78b19701a1987e68.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最后我们run一下
![](https://upload-images.jianshu.io/upload_images/23053034-3ba2104397f1a849.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
控制台是这样的
![](https://upload-images.jianshu.io/upload_images/23053034-ef08edd888601368.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
为什么会有400呢?因为有一些接口是异常的,比如url错误的,少传入参数、空参,所以会出错,常理之中
<6> 看下生成的测试报告
在pycharm中是这样的
![](https://upload-images.jianshu.io/upload_images/23053034-5eabbdd288a4f0e2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
然后我们copy下他的路径到浏览器中查看
![](https://upload-images.jianshu.io/upload_images/23053034-8e1277a754e59010.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/23053034-3e33ad45552239c3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
根据我追踪的信息,第一条失败是因为sessionId是可以变的,每一次的值都是不一样,在这里也希望大家能够找到BUG,并妥善处理好每一个问题。
以上内容希望对你有帮助,有被帮助到的朋友欢迎点赞,评论。