【Playwright+Python】系列教程(七)使用Playwright进行API接口测试
playwright也是可以做接口测试的,但个人觉得还是没有requests库强大,但和selenium相比的话,略胜一筹,毕竟支持API登录,也就是说可以不用交互直接调用接口操作了。
怎么用
既然是API的测试了,那肯定就别搞UI自动化那套,搞什么浏览器交互,那叫啥API测试,纯属扯淡。
也不像有些博主更懒,直接贴的官方例子,难道我用你再帮我复制一次?
来下面,说明下使用playwright如何做API测试?
实例化request对象
示例代码如下:
playwright.request.new_context()
没错,实例化后,就是调API,看吧,其实也不是很难是不是?
实战举栗
这里用我自己写的学生管理系统的部分接口来做演示,并对部分常用api做以说明,代码示例都是用同步的写法。
1、GET请求
示例如下:
def testQueryStudent(playwright: Playwright):
"""
查询学生
"""
url = 'http://localhost:8090/studentFindById'
param = {
'id': 105
}
request_context = playwright.request.new_context()
response = request_context.get(url=url, params=param)
assert response.ok
assert response.json()
print('\n', response.json())
效果:

2、POST请求
示例代码:
def testAddStudent(playwright: Playwright):
"""
新增学生
:return:
"""
url = 'http://localhost:8090/studentAdd'
request_body = {
"className": "banji",
"courseName": "wuli",
"email": "ales@qq.com",
"name": "ales",
"score": 70,
"sex": "boy",
"studentId": "92908290"
}
header = {"Content-Type": "application/json"}
request_context = playwright.request.new_context()
response = request_context.post(url=url, headers=header, data=request_body)
assert response.ok
assert response.json()
print('\n', response.json())
效果:

3、PUT请求
示例代码:
def testUpdateStudents(playwright: Playwright):
"""
修改学生
"""
url = 'http://localhost:8090/studentUpdate/100'
param = {
'studentId': "id" + str(100),
'name': "name" + str(100),
'score': 100,
"sex": "girl",
"className": "class" + str(100),
"courseName": "course" + str(100),
"email": str(100) + "email@qq.com"
}
request_context = playwright.request.new_context()
response = request_context.put(url=url, form=param)
assert response.ok
assert response.json()
print('\n', response.json())
效果:

4、DELETE请求
示例代码:
def testDeleteStudents(playwright: Playwright):
"""
删除学生
"""
url = 'http://localhost:8090/studentDelete/' + str(105)
request_context = playwright.request.new_context()
response = request_context.delete(url=url)
assert response.ok
assert response.json()
print('\n', response.json())
效果:

5、上传文件
这个是特例吧,按照官方给的方法,我真的是死活也不能成功,一直都是提示上上传文件不能为空,也不到为啥,结果我用了一个替代方案,就是抓包模拟的构造入参,才成功,也是曲折呀。
示例代码:
def test_upload_file(playwright: Playwright):
'''
上传文件
:param playwright:
:return:
'''
# 创建请求上下文
request_context = playwright.request.new_context()
# 定义上传文件的URL
upload_url = "http://localhost:8090/fileUpload"
# 文件路径
file_path = "d:/demo.txt"
# 获取文件名和MIME类型
filename = file_path.split('/')[-1]
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type:
mime_type = 'application/octet-stream'
# 读取文件内容
with open(file_path, 'rb') as file:
file_content = file.read()
# 构造multipart/form-data的边界字符串
boundary = '---------------------' + str(random.randint(1e28, 1e29 - 1))
# 构造请求体
body = (
f'--{boundary}\r\n'
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
f'Content-Type: {mime_type}\r\n\r\n'
f'{file_content.decode("utf-8") if mime_type.startswith("text/") else file_content.hex()}'
f'\r\n--{boundary}--\r\n'
).encode('utf-8')
# 设置请求头
headers = {
'Content-Type': f'multipart/form-data; boundary={boundary}',
}
# 发起POST请求
response = request_context.post(upload_url, data=body, headers=headers)
# 检查响应
assert response.status == 200, f"Upload failed with status: {response.status}"
assert response.ok
assert response.json()
print('\n', response.json())
效果:

官方写法:
# 读取文件内容
with open(file_path, 'rb') as file:
file_content = file.read()
response = request_context.post(upload_url, multipart={
"fileField": {
"name": "demo.txt",
"mimeType": "text/plain",
"buffer": file_content,
}
})
print('\n', response.json())
效果:

官方写法,我不知道为啥,有大侠知道,还请帮忙给个例子,小弟不胜感激呀!
写在最后
我还是觉得微软很强呀,这套框架确实比selenium略胜一筹,综合来看。
终于有时间了,来更新一篇,感觉文章对你有用,转发留言都可,谢谢!
对了,那个上传文件的为啥不行,还请前辈们帮看一下呀!
【Playwright+Python】系列教程(七)使用Playwright进行API接口测试的更多相关文章
- 【转】PyQt5系列教程(七)控件
PyQt5系列教程(七)控件 软硬件环境 Windows 10 Python 3.4.2 PyQt 5.5.1 PyCharm 5.0.4 前言 控件是PyQt应用程序的基石.PyQt5自带很多不 ...
- CRL快速开发框架系列教程七(使用事务)
本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...
- ASP.NET 5系列教程(七)完结篇-解读代码
在本文中,我们将一起查看TodoController 类代码. [Route] 属性定义了Controller的URL 模板: [Route("api/[controller]") ...
- 黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block
原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block 使用企业库异常处理应用程序模块的 ...
- webpack4 系列教程(七): SCSS提取和懒加载
教程所示图片使用的是 github 仓库图片,网速过慢的朋友请移步>>> (原文)webpack4 系列教程(七): SCSS 提取和懒加载. 个人技术小站: https://god ...
- (转)NGUI系列教程七(序列帧动画UITexture 和 UIsprit)
NGUI系列教程七(序列帧动画) 今天我给大家讲一下如何使用NGUI做序列帧动画.本节主要包括两方面内容,分别是使用UIspirit和使用UITexture 做序列帧动画.废话不说了,下面开始.还 ...
- Python系列教程-详细版 | 图文+代码,快速搞定Python编程(附全套速查表)
作者:韩信子@ShowMeAI 教程地址:http://showmeai.tech/article-detail/python-tutorial 声明:版权所有,转载请联系平台与作者并注明出处 引言 ...
- Unity3D脚本中文系列教程(七)
http://dong2008hong.blog.163.com/blog/static/4696882720140311445677/?suggestedreading&wumii Unit ...
- Python系列教程大汇总
Python初级教程 Python快速教程 (手册) Python基础01 Hello World! Python基础02 基本数据类型 Python基础03 序列 Python基础04 运算 Pyt ...
- NGUI系列教程七(序列帧动画)
今天我给大家讲一下如何使用NGUI做序列帧动画.本节主要包括两方面内容,分别是使用UIspirit和使用UITexture 做序列帧动画.废话不说了,下面开始.还要在啰嗦一句,首先大家要准备一些序列帧 ...
随机推荐
- Centos7部署FytSoa项目至Docker——第二步:安装Mysql、Redis
FytSoa项目地址:https://gitee.com/feiyit/FytSoaCms 部署完成地址:http://82.156.127.60:8001/ 先到腾讯云申请一年的云服务器,我买的是一 ...
- Json字符串转换处理html编码格式,= \u003d 处理
Json字符串转换处理html编码格式,= \u003d 处理 import com.alibaba.fastjson.annotation.JSONField; import com.faster ...
- WPF/C#:如何将数据分组显示
WPF Samples中的示例 在WPF Samples中有一个关于Grouping的Demo. 该Demo结构如下: MainWindow.xaml如下: <Window x:Class=&q ...
- python webdriver.remote远程创建火狐浏览器会话报错,Unable to create new service: GeckoDriverService
问题: 使用selenium.webdriver.remote,远程指定地址的浏览器,并创建会话对象:创建火狐浏览器会话时,报错,错误信息如下: Message: Unable to create n ...
- MYSQL8存储过程生成日历表以及异常处理
一.环境 数据库:mysql8.0.25 社区版 操作系统:windows 11 ------------------------------------ 二.创建日历表 CREATE TABLE ` ...
- 你了解Vim的增删改查吗 ?
增: 在Vim的Normal模式中输入A/I/O,a/i/o字符进行对应的增加操作. 删 在Vim的Normal模式中, 输入x 删除光标对应的一个字符(4x代表删除4个字符): 输入dd删除光标所在 ...
- Gmsh 和 FiPy 求解稳态圆柱绕流
本项目的源码保存在 github 仓库 https://github.com/cjyyx/CFD_Learning/tree/main/CFD软件学习/FiPy/cylinder.如果下载整个目录,可 ...
- Python通过GPIO从DHT11温度传感器获取数据
Python通过GPIO从DHT11温度传感器获取数据 设备:树莓派4B.DHT11.杜邦线 DHT11 DHT11是一款有已校准数字信号输出的温湿度传感器. 其精度湿度±5%RH, 温度±2℃,量程 ...
- python配置国内pypi镜像源操作步骤
使用pip config命令设置默认镜像源,使用国内的源,提高安装速度 操作步骤 临时方式pip install xxx -i https://pypi.tuna.tsinghua.edu.cn/si ...
- Spring MVC 中的拦截器的使用“拦截器基本配置” 和 “拦截器高级配置”
1. Spring MVC 中的拦截器的使用"拦截器基本配置" 和 "拦截器高级配置" @ 目录 1. Spring MVC 中的拦截器的使用"拦截器 ...