【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())结果:
https://cdn.nlark.com/yuque/0/2024/png/12957787/1722859889409-18fc1646-c7ad-43f3-8b46-5178611024c8.png#averageHue=%23212a34&clientId=u4262a8c6-2891-4&from=paste&height=210&id=uae588bb2&originHeight=263&originWidth=1279&originalType=binary&ratio=1.25&rotation=0&showTitle=false&size=30570&status=done&style=none&taskId=u90053bc5-df8d-4bd5-9c14-612ac41e27d&title=&width=1023.2
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())结果:
https://cdn.nlark.com/yuque/0/2024/png/12957787/1722860119143-024119cc-f0fd-4582-853d-bb7315f447a8.png#averageHue=%23222a34&clientId=u4262a8c6-2891-4&from=paste&height=275&id=u737312d0&originHeight=344&originWidth=1266&originalType=binary&ratio=1.25&rotation=0&showTitle=false&size=38870&status=done&style=none&taskId=u8eb1bed7-7589-48d0-a3f8-6a1e75d774d&title=&width=1012.8
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())结果:
https://cdn.nlark.com/yuque/0/2024/png/12957787/1722860533746-138a5f28-8583-48ea-b5d3-5e688929d95c.png#averageHue=%23222a34&clientId=u4262a8c6-2891-4&from=paste&height=253&id=u88d6aa8b&originHeight=316&originWidth=1249&originalType=binary&ratio=1.25&rotation=0&showTitle=false&size=34572&status=done&style=none&taskId=u329a034a-7a6e-42ef-b0f2-73cdd2dc51b&title=&width=999.2
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())结果:
https://cdn.nlark.com/yuque/0/2024/png/12957787/1722860612540-4c100951-9464-495c-b082-f097e45342db.png#averageHue=%23212a33&clientId=u4262a8c6-2891-4&from=paste&height=246&id=u9fea123f&originHeight=307&originWidth=999&originalType=binary&ratio=1.25&rotation=0&showTitle=false&size=25938&status=done&style=none&taskId=ub314009b-8b58-406c-a540-4d8292313a5&title=&width=799.2
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())结果:
https://cdn.nlark.com/yuque/0/2024/png/12957787/1722861059201-dec49c83-24ff-4a2a-a9ec-ec66a804cc9a.png#averageHue=%23212a33&clientId=u4262a8c6-2891-4&from=paste&height=250&id=u1a036ac8&originHeight=313&originWidth=1104&originalType=binary&ratio=1.25&rotation=0&showTitle=false&size=31923&status=done&style=none&taskId=ub57fbe98-705f-4b5e-8a92-c7cffcd916d&title=&width=883.2
官方写法:
# 读取文件内容
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())结果:
https://cdn.nlark.com/yuque/0/2024/png/12957787/1722863695755-c0345909-390d-4f88-8ad7-948bee45c1db.png#averageHue=%23202932&clientId=u4262a8c6-2891-4&from=paste&height=93&id=ufcd3f4e5&originHeight=116&originWidth=1139&originalType=binary&ratio=1.25&rotation=0&showTitle=false&size=12787&status=done&style=none&taskId=ua66f02fb-c732-4847-8151-abd55bb1bcd&title=&width=911.2
官方写法,我不知道为啥,有大侠知道,还请帮忙给个例子,小弟不胜感激呀!
写在末了
我照旧以为微软很强呀,这套框架确实比selenium略胜一筹,综合来看。
终于有时间了,来更新一篇,感觉文章对你有用,转发留言都可,谢谢!
对了,那个上传文件的为啥不行,还请前辈们帮看一下呀!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]