Python使用Playwright進行API接口測試
在當今的自動化測試領(lǐng)域,結(jié)合Web UI和API接口測試已成為提升測試覆蓋率和效率的關(guān)鍵。Playwright作為一個強大的自動化測試工具,除了在Web UI測試中大放異彩,還能與Python結(jié)合,實現(xiàn)強大的API接口測試功能。本文將帶你探索如何使用Playwright和Python進行高效的API接口測試。
Playwright除了在Web UI測試中的出色表現(xiàn),如何通過與Python結(jié)合,開展API接口測試,并實現(xiàn)高效的自動化測試?
playwright也是可以做接口測試的,但個人覺得還是沒有requests庫強大,但和selenium相比的話,略勝一籌,畢竟支持API登錄,也就是說可以不用交互直接調(diào)用接口操作了。
怎么用
既然是API的測試了,那肯定就別搞UI自動化那套,搞什么瀏覽器交互,那叫啥API測試,純屬扯淡。
也不像有些博主更懶,直接貼的官方例子,難道我用你再幫我復制一次?
來下面,說明下使用playwright如何做API測試?
實例化request對象
示例代碼如下:
playwright.request.new_context()
沒錯,實例化后,就是調(diào)API,看吧,其實也不是很難是不是?
實戰(zhàn)舉栗
這里用我自己寫的學生管理系統(tǒng)的部分接口來做演示,并對部分常用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、上傳文件
這個是特例吧,按照官方給的方法,我真的是死活也不能成功,一直都是提示上上傳文件不能為空,也不到為啥,結(jié)果我用了一個替代方案,就是抓包模擬的構(gòu)造入?yún)?,才成功,也是曲折呀?/p>
示例代碼:
def test_upload_file(playwright: Playwright):
'''
上傳文件
:param playwright:
:return:
'''
# 創(chuàng)建請求上下文
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'
# 讀取文件內(nèi)容
with open(file_path, 'rb') as file:
file_content = file.read()
# 構(gòu)造multipart/form-data的邊界字符串
boundary = '---------------------' + str(random.randint(1e28, 1e29 - 1))
# 構(gòu)造請求體
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')
# 設(shè)置請求頭
headers = {
'Content-Type': f'multipart/form-data; boundary={boundary}',
}
# 發(fā)起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())
效果:

官方寫法:
# 讀取文件內(nèi)容
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())
效果:

官方寫法,我不知道為啥就是不成功,有大俠知道嗎,還請幫忙給個例子,小弟不勝感激!
寫在最后
隨著Web應用的發(fā)展,API接口測試的重要性日益突出。開發(fā)人員和測試人員必須確保API接口的可靠性和穩(wěn)定性,以保證應用的正常運行和用戶體驗的提升。通過使用Playwright進行全面的API接口測試,可以有效提高測試效率和覆蓋率。
使用Playwright進行API接口測試,不僅能夠高效地驗證API的各項功能,還能確保Web應用的整體性能和可靠性。通過本文的介紹,你已經(jīng)掌握了如何使用Playwright進行GET、POST、PUT、DELETE和上傳文件的API接口測試。
通過本文的詳細解析,我們展示了如何使用Playwright進行各種常見的API接口測,掌握Playwright,讓你的API測試如虎添翼,輕松應對各種復雜的測試場景。
到此這篇關(guān)于Python使用Playwright進行API接口測試的文章就介紹到這了,更多相關(guān)Python Playwright API接口測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python使用代理IP爬取貓眼電影專業(yè)評分數(shù)據(jù)
在編寫爬蟲程序的過程中,IP封鎖無疑是一個常見且棘手的問題,盡管網(wǎng)絡(luò)上存在大量的免費IP代理網(wǎng)站,但其質(zhì)量往往參差不齊,令人堪憂,本篇文章中介紹一下如何使用Python的Requests庫和BeautifulSoup庫來抓取貓眼電影網(wǎng)站上的專業(yè)評分數(shù)據(jù),需要的朋友可以參考下2024-03-03
selenium 安裝與chromedriver安裝的方法步驟
這篇文章主要介紹了selenium 安裝與chromedriver安裝的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06

