pip install requests
pip install xlrd
pip install json
pip install unittest
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,依次类推
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)
也可以对需要拿到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页验证的这些代码做清除,否则的话永远都是调的这些接口
这里我添加了一个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
# 读取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 #最终返回为字典形式 有键和值
为什么要转换格式呢?
这里就涉及到了怎么设计一个自动化接口用例
用例的参数值要用json格式写入,不要有空格
预期结果的出参也要用json格式写入
不要有' '值都要用" "包起来
# 封装一个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)
其余还有需要补充的可以继续添加,我这里三个基本够用
import unittest
import ddt
import 自动化接口测试.common.commons as common
from 自动化接口测试.base.Base_Page import Base
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) # 进行断言 看用例是否通过
if __name__ == '__main__':
load = unittest.TestLoader().loadTestsFromTestCase(TestLogin) #使用loader加载方式 来找寻所有已test开头的用例
suite = unittest.TestSuite([load,])
common.Common().GetHtmlResult(suite,'登录测试用例')
如果对软件测试、接口测试、自动化测试、面试经验交流。感兴趣可以加软件测试交流:1085991341,还会有同行一起技术交流。
最后我们run一下
控制台是这样的
为什么会有400呢?因为有一些接口是异常的,比如url错误的,少传入参数、空参,所以会出错,常理之中
在pycharm中是这样的
然后我们copy下他的路径到浏览器中查看
根据我追踪的信息,第一条失败是因为sessionId是可以变的,每一次的值都是不一样,在这里也希望大家能够找到BUG,并妥善处理好每一个问题。
最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:
这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取