前面2篇文章已經簡單的介紹接口測試相關概念和HTTP協(xié)議基礎,本篇文章主要就“使用python實現(xiàn)接口測試基礎知識”進行展開講解,包括使用requests庫構建相應的HTTP請求、傳遞URL參數(shù)、定制請求頭、請求消息體以及獲取響應內容等。希望感興趣的小伙伴可以堅持看下去同時歡迎提出寶貴的意見讓我們一起進步!
01:構建相應的HTTP請求準備工作
1)構建相應的HTTP請求可選擇的庫:本次主要使用requests庫。
①內置的庫:httplib、urllib2
②第三方庫:urllib3、requests、pyCurl
2)安裝requests庫:pip install requests
02:構建各種HTTP請求方法
1)G E T請求:r=requests.get('http://localhost/xxx/')
2)POST請求:r=requests.post('http://localhost/xxx/')
3)P U T請求:r=requests.put('http://localhost/xxx/')
4)DELETE請求:r=requests.delete('http://localhost/xxx/')
import requests
(1)構建GET請求
res=requests.get('http://localhost/api/mgr/sq_mgr/?action=list_course&pagenum=1&pagesize=20')
(2)構建POST請求
res = requests.post('http://localhost/api/mgr/sq_mgr/')
(3)構建PUT請求
res=requests.put('http://localhost/api/mgr/sq_mgr/')
(4)構建DELETE請求
res=requests.delete('http://localhost/api/mgr/sq_mgr/')
03:傳遞URL參數(shù)(params)
1)概述:如果手工構建 URL,那么數(shù)據(jù)會以鍵/值對的形式置于 URL 中,跟在一個問號的后面。
2)關鍵字:params
接口文檔URL參數(shù)如下:
(1)請求語法:GET /api/mgr/sq_mgr/?action=list_course&pagenum=1&pagesize=20 HTTP/1.1
(2)url請求參數(shù):
action 填寫list_course,表明是要列出所有課程信息
pagenum 表示當前要顯示的是第幾頁,目前固定填寫1
pagesize 表示一頁最多顯示多少條課程信息,目前固定填寫20
(3)python代碼實現(xiàn)傳遞URL參數(shù):
res=requests.get('http://localhost/api/mgr/sq_mgr/',
#傳遞URL請求參數(shù):params
params={
'action': 'list_course',
'pagenum': '1',
'pagesize': '20',
})
pprint.pprint(res.json())
04:定制請求頭(headers)
1)概述:如果為請求添加 HTTP 頭部,只要簡單地傳遞一個 dict給headers參數(shù)就可以。
2)關鍵字:headers
接口文檔URL參數(shù)如下:
(1)請求語法:POST/api/mgr/sq_mgr/ HTTP/1.1
(2)請 求 頭:Content-Type: application/x-www-form-urlencoded
(3)python代碼實現(xiàn)傳遞HTTP請求頭:
res=requests.post('http://localhost/api/mgr/sq_mgr/',
#傳遞HTTP請求頭:headers
headers={
'Content-Type': 'application/x-www-form-urlencoded',
})
05:定制請求消息體(data、json)
1)請求體類型為“Content-Type: application/x-www-form-urlencoded”或“xml”
①實現(xiàn)方式:只需簡單地傳遞一個字典給 data 參數(shù)。
②關鍵字:data
2)請求體類型為“Content-Type: application/json”
①實現(xiàn)方式:只需簡單地將字典直接傳遞給json參數(shù)。
②關鍵字:json
③請注意:如果消息體內容是json則傳遞的是一個數(shù)據(jù)對象,會自動把數(shù)據(jù)對象轉換為json格式的字符串。
接口文檔請求體內容如下:
(1)請求語法:POST /api/mgr/sq_mgr/ HTTP/1.1
(2)請求體類型:Content-Type: application/x-www-form-urlencoded
(3)請求體內容:
action 必填 填寫add_course,表明是為了創(chuàng)建課程
data 必填 存儲創(chuàng)建課程的信息,包括名稱、描述、顯示次序。為json格式。例如:
{
"name":"python",
"desc":"python基礎課程",
"display_idx":"4"
}
(4)python代碼實現(xiàn)傳遞HTTP消息體:
res = requests.post('http://localhost/api/mgr/sq_mgr/',
#傳遞HTTP消息體:data
data={
'action':'add_course',
'data':'''
{
"name":"selenium",
"desc":"selenium基礎課程",
"display_idx":"1"
}'''},
#傳遞HTTP消息體:json(直接傳遞)
json = {
"action": "add_course_json",
"data" : {
"name" :"初中政治",
"desc" :"初中政治基礎",
"display_idx" :"2"}
})
06:獲取響應內容
1)獲取響應狀態(tài)碼:res.status_code
2)獲取響應消息頭:res.headers
3)獲取響應消息頭部分字段:res.headers['Content-Type']
4)獲取JSON響應消息體內容:res.json()
5)獲取原始響應消息體內容:res.text