我们提供安全,免费的手游软件下载!
Playwright
也可以用于接口测试,但个人认为它还不如
requests
库强大。与
selenium
相比,Playwright稍微胜出,因为它支持API登录,也就是说可以直接调用接口操作,无需交互。
也不像有些博主那样懒,直接贴官方例子,这样岂不是我用你的例子再帮我复制一次?
下面,我们来说明一下如何使用Playwright进行API测试?
playwright.request.new_context()
没错,实例化后就可以调用API。看吧,其实也不是很难是不是?
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())
效果:
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())
效果:
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())
效果:
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())
效果:
示例代码:
def test_upload_file(playwright: Playwright):
'''
上传文件
:param playwright:
:return:
'''
// 省略部分代码
效果:
官方写法:
// 读取文件内容
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())
效果:
官方写法,我不知道为啥,有大侠知道,还请帮忙给个例子,小弟不胜感激呀!
热门资讯