很多人會使用postman工具,或者熟悉python,但不一定會使用python來編寫測試用例腳本,postman里面可以完整的將python代碼復制出來。
(以下所有內(nèi)容以豆瓣網(wǎng)站搜索功能為例子)
打開postman,點擊右側(cè)的/>圖標,頁面右邊會顯示腳本,頂部修改導出的語言,這邊我使用的是Python-Reqyests
復制腳本,在PyCharm中打開即可,在導入使用之前如果沒有reuqests庫,可能會報錯,我們需要安裝reuqests庫。
cmd命令窗口輸入:pip install requests
導出后的腳本格式如下:
import requests url = "https://www.douban.com/search?"> payload={'q': '三體'} files=[ ] headers = { 'Cookie': 'bid=5bBvkukAbvY' } response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text)
1.下面就是轉(zhuǎn)成pytest的測試用例
import requests class TestDouban: def test_douban(self): url = "https://www.douban.com/search?"> payload = {'q': '三體'} files = [] headers = { 'Cookie': 'bid=5bBvkukAbvY' } response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text)
在一個項目中,根路由的路徑是一樣的,只是不同功能對應的具體的接口不一致,且POST和GET是目前測試用例中比較通用的方法,所以可以將根路由、POST和GET方法封裝成一個通用的類,后面直接調(diào)用即可。
import requests class Common: def __init__(self): # 豆瓣根路由 self.url_root = "https://www.douban.com>" # get請求,uri是接口具體地址,params是get請求的參數(shù),如果沒有,默認為空 def get(self, uri, params=''): # 拼湊訪問地址 url = self.url_root + uri + params # 通過get請求訪問對應地址 response = requests.get(url) # 返回request的response結(jié)果,類型為requests的Response類型 return response # post請求,uri是接口具體地址,params是post請求的參數(shù),如果沒有,默認為空 def post(self, uri, params=''): # 拼湊訪問地址 url = self.url_root + uri # 有參數(shù),則訪問對應的url,并賦值給默認參數(shù)data if len(params) > 0: response = requests.post(url, data=params) # 無參數(shù),只需要訪問對應的url即可 else: response = requests.post(url) # 返回request的response結(jié)果,類型為requests的Response類型 return response
import requests from common.common import Common class TestDouban: def setup(self): self.com = Common() def test_douban(self): uri = "/search?" payload = {'q': '三體'} response = self.com.post(uri, payload) # 由于file不需要,就將file刪除了,至于hearder是否要添加可根據(jù)需求來定
執(zhí)行結(jié)果如下:
到此這篇關(guān)于python編寫接口測試文檔的文章就介紹到這了,更多相關(guān)python編寫接口測試文檔內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!