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.读取
importcsv
classReadCsv():
defreadCsv(self):
item= []
rr=csv.reader(open("../dataDemo/123.csv"))
forcsv_iinrr:
item.append(csv_i)
item=item[1:]
returnitem
3.requests请求接口返回状态码
importrequests
fromreadDataDemo.readcsvimportReadCsv
r=ReadCsv()
ee=r.readCsv()
# print(ee)
classRequestCsv():
defrequestsCsv(self):
item= []
forcsv_iinee:
ifcsv_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)
returnitem
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请求接口返回状态码
importrequests
fromrequestdemo.readexcelimportReadxcel
classGetStatusCode():
defgetStatusCode(self):
t=Readxcel()
f=t.getTestExcel()
item= []
forexcel_iinf:
ifexcel_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)
returnitem
print(GetStatusCode().getStatusCode())
4.生成测试报告
importallure,pytest,os
fromrequestdemo.getStatusCodeimportGetStatusCode
get=GetStatusCode()
statusCodes=get.getStatusCode()
classTestReadExcel():
deftestReadExcel(self):
forcodeinstatusCodes:
assertcode==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)