智能摘要 AI
Playwright 支持 API 测试,虽然不如 requests 库强大,但比 Selenium 更方便,支持直接调用接口。本文介绍了如何用 Playwright 进行 API 测试,包括实例化 request 对象、GET、POST、PUT、DELETE 请求及文件上传的示例代码。虽然官方文件上传方法存在问题,但通过模拟构造入参解决了问题。总体而言,Playwright 在功能上略胜 Selenium。
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):
"""
新增学生
"""
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):
'''
上传文件
'''
request_context = playwright.request.new_context()
upload_url = "http://localhost:8090/fileUpload"
file_path = "d:/demo.txt"
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()
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}',
}
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略胜一筹,综合来看。
终于有时间更新一篇文章,觉得有用的话,转发留言都可以,谢谢!对了,那个上传文件的问题,还请前辈们帮忙看看呀!





评论 (0)