1.介绍:
Requests是一个很实用的Python HTTP客户端库,用来做接口测试
*做接口测试前需要pip install requests
2.get请求
一、无参请求
r = requests.get('http://www.baidu.com')
二、get传参
payload = {'key1': 'value1', 'key2': 'value2', 'key3': None}
r = requests.get('http://www.baidu.com ', params=payload)
3.post请求
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
4.requests响应
r.status_code 响应状态码
r.heards 响应头
r.cookies 响应cookies
r.text 响应文本
r. encoding 当前编码
r. content 以字节形式(二进制)返回
5.requests扩充
1)添加等待时间
requests.get(url,timeout=1) #超过等待时间则报错
2).添加请求头信息
requests.get(url,headers=headers) #设置请求头
3).添加文件
requests.post(url, files=files) #添加文件
6.requests+pytest+allure
1).步骤如下:
读取文件中的数据
requests拿到数据请求接口返回状态码
通过断言验证返回状态码和200对比
生成allure的测试报告
也可以这样说:
dataDemo(存放数据)>> readDemo(读取数据)
useRequests(发送请求)>>testDemo(生成报告)
2).读取csv数据流程
1}.通过excel另存为csv
2}.读取
import csv
class ReadCsv():
def readCsv(self):
item = []
rr = csv.reader(open("../dataDemo/123.csv"))
for csv_i in rr:
item.append(csv_i)
item =item [1:]
return item
3}.requests请求接口返回状态码
import requests
from readDataDemo.readcsv import ReadCsv
r = ReadCsv()
ee = r.readCsv()
# print(ee)
class RequestCsv():
def requestsCsv(self):
item = []
for csv_i in ee:
if csv_i[2] =="get":
rr = requests.get(csv_i[0],params=csv_i[1])
item.append(rr.status_code)
else:
rr = requests.post(csv_i[0],data=csv_i[1])
item.append(rr.status_code)
return item
4}.生成测试报告
3).读取excel文件流程
1}.新建excel文件
2}.读取数据,安装pip install openpyxl
class ReadXlsx:
def readXlsx(self):
wordbook=load_workbook("绝对路径")
sheet = wordbook["requests"]
testdata = []
for i in range(2, sheet.max_row + 1):
d = {}
for j in range(1, sheet.max_column + 1): d[sheet.cell(1, j).value] = sheet.cell(i, j).value testdata.append(d)
return testdata
3}.requests请求接口返回状态码
import requests
from requestdemo.readexcel import Readxcel
class GetStatusCode():
def getStatusCode(self):
t = Readxcel()
f = t.getTestExcel()
item = []
for excel_i in f:
if excel_i["method"] == "get":
rr = requests.get(excel_i["url"], params=excel_i["params"])
item.append(rr.status_code)
else:
rr = requests.post(excel_i["url"], data=excel_i["params"])
item.append(rr.status_code)
return item
print(GetStatusCode().getStatusCode())
4}.生成测试报告
import allure, pytest, os
from requestdemo.getStatusCode import GetStatusCode
get = GetStatusCode()
statusCodes = get.getStatusCode()
class TestReadExcel():
def testReadExcel(self):
for code in statusCodes:
assert code == 200
if __name__ == "__main__":
# 生成测试报告json
pytest.main(["-s", "-q", '--alluredir', 'report/result', 'testreadexcel.py'])
# 将测试报告转为html格式
split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
os.system(split)