Python中requests做接口测试的方法
作者:测试萌萌 发布时间:2022-04-10 11:06:18
标签:Python,requests,接口测试
目录
一、介绍
二、前提
三、get的请求
3.1 GET无参请求
3.2 GET传参
四、post请求
五、Requests响应
六、Request扩充
七、requests+pytest+allure
7.1 流程如下
7.2 模块总览
7.3 读取csv文件流程
7.4 读取excle文件流程
一、介绍
Requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到,Requests是Python语言的第三方的库,专门用于发送HTTP请求
二、前提
pip install requests
三、get的请求
3.1 GET无参请求
r = requests.get('http://www.baidu.com')
3.2 GET传参
payload = {'key1': 'value1', 'key2': 'value2', 'key3': None}
r = requests.get('http://www.baidu.com ', params=payload)
案例:测试聚合数据
代码
import requests
class UseRequestClass():
#get传参的第一种方式
def XWTTMethod(self):
r = requests.get("http://v.juhe.cn/toutiao/index?type=guonei&key=4b72107de3a197b3bafd9adacf685790")
print(r.text)
#get传参的第二种方式
def XWTTMethod(self):
params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
r = requests.get("http://v.juhe.cn/toutiao/index",params=params)
print(r.text)
四、post请求
类似python中的表单提交
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
案例:测试聚合数据
代码
import requests
class UseRequestClass():
def XWTTPostMethod(self):
params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
r = requests.post("http://v.juhe.cn/toutiao/index",params=params)
#print(r.status_code)
return r.status_code
五、Requests响应
r.status_code 响应状态码
r.heards 响应头
r.cookies 响应cookies
r.text 响应文本
r. encoding 当前编码
r. content 以字节形式(二进制)返回
最常用的是根据响应状态码判断接口是否连通,经常用于做接口中断言判断
六、Request扩充
1.添加等待时间
requests.get(url,timeout=1) #超过等待时间则报错
2.添加请求头信息
requests.get(url,headers=headers) #设置请求头
3.添加文件
requests.post(url, files=files) #添加文件
文件传输
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
七、requests+pytest+allure
7.1 流程如下
读取文件中的数据
requests拿到数据请求接口返回状态码
通过断言验证返回状态码和200对比
生成allure的测试报告
7.2 模块总览
dataDemo(存放数据)>> readDemo(读取数据)
useRequests(发送请求)>>testDemo(生成报告)
7.3 读取csv文件流程
7.3.1 存储数据(csv)
通过excel另存为csv即可。
7.3.2 读取数据(readDemo)
代码展示
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
7.3.3 request请求接口返回状态码
代码展示
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
7.3.4 pytest断言设置并结合allure生成测试报告
代码展示
import pytest,os,allure
from userequests.userequestsDemo.requestscsv import RequestCsv
r = RequestCsv()
ee = r.requestsCsv()
print(ee)
class TestClass02():
def test001(self):
for code in ee:
assert code == 200
if __name__ == '__main__':
pytest.main(['--alluredir', 'report/result', 'test_02csv.py'])
split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
os.system(split)
7.3.5 测试报告展示
7.4 读取excle文件流程
7.4.1 存储数据(xlsx)
7.4.2 读取数据(readDemo)
from openpyxl import load_workbook
class Readxcel():
def getTestExcel(self):
# 打开表
workbook = load_workbook("G:\python\pythonProject\pytest05a\\requestdemo\\a.xlsx")
# 定位表单
sheet = workbook['Sheet1']
print(sheet.max_row) # 3 行
print(sheet.max_column) # 3 列
test_data = [] # 把所有行的数据放到列表中
for i in range(2, sheet.max_row + 1):
sub_data = {} # 把每行的数据放到字典中
for j in range(1, sheet.max_column + 1):
sub_data[sheet.cell(1, j).value] = sheet.cell(i, j).value
test_data.append(sub_data) # 拼接每行单元格的数据
return test_data
t = Readxcel()
f = t.getTestExcel()
print(f)
7.4.3 request请求接口返回状态码
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())
7.4.4 pytest断言设置并结合allure生成测试报告
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)
7.4.5:测试报告展示
来源:https://blog.csdn.net/weixin_50829653/article/details/117374597


猜你喜欢
- 目录1. 前言2. 介绍及安装3. 实战一下3-1 创建爬虫项目3-2 创建爬虫 Ai
- 1.调整内存 sp_configure 'show advanced options',1 GO RECONFIGURE G
- 在MySQL 5.6.6之前,TIMESTAMP的默认行为:■TIMESTAMP列如果没有明确声明NULL属性,默认为NOT NULL。(而
- title: Python 装饰器装饰类中的方法comments: truedate: 2017-04-17 20:44:31tags: [
- 环境:ubuntu 16.04 python3.5 pycharm包 : wave pyaudio sys上代码:AudioPlayer.p
- Error是Go语言开发中最基础也是最重要的部分,跟其他语言的try catch的作用基本一致,想想在PHP JAVA开发中,try cat
- 外联接。外联接可以是左向外联接、右向外联接或完整外部联接。 在 FROM 子句中指定外联接时,可以由下列几组关键字中的一组指定:LEFT J
- 1 引言在python内存管理中,有一个block的概念。它比较类似于SGI次级空间配置器。首先申请一块大的空间(4KB),然后把它切割成一
- 需求在4*4的图片中,比较外围黑色像素点和内圈黑色像素点个数的大小将图片分类如上图图片外围黑色像素点5个大于内圈黑色像素点1个分为0类反之1
- 是在客户端确认还是在服务器端确认? <SCRIPT LANGUAGE="VBSc
- [前言]:搭往公司的班车,遇到其他部门的同事,他问了很多关于我的工作的问题,由此引发这篇文章。这些问题,我也经常被其他人问到,其中既有我们亲
- python判断图片主色调,单个颜色:#!/usr/bin/env python# -*- coding: utf-8 -*-import
- Python操作MySQL主要使用两种方式:原生模块 pymsqlORM框架 SQLAchemypymqlpymsql是Python中操作M
- 使用Python的rename()函数重命名文件时出现问题,提示 WindowsError: [Error 2] 错误,最初代码如下:def
- 作者:JavaScript Kit译者:子乌(Sheneyan)翻译日期:2006-02-12英文原文:Conditional Compil
- 有时在项目中会遇到通过在页面中采用iframe的方式include其它页面,这时就会考虑不要因出现滚动条而影响页面效果,但include页面
- 前言前段时间做项目的时候,需要一个Markdown编辑器,在网上找了一些开源的实现,但是都不满足需求说实话,这些开源项目也很难满足需求公司项
- 1、获取秒级时间戳与毫秒级时间戳、微秒级时间戳import timeimport datetimet = time.time()print
- 想必大家都很喜欢用Word打字,用Excel进行计算和规划,用PowerPoint作幻灯片进行展示…,但是这只用到了Office系列产品的很
- 均方损失函数:这里 loss, x, y 的维度是一样的,可以是向量或者矩阵,i 是下标。很多的 loss 函数都有 size_averag