您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“如何用python編寫接口測試文檔”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
打開postman,點擊右側(cè)的</>圖標(biāo),頁面右邊會顯示腳本,頂部修改導(dǎo)出的語言,這邊我使用的是Python-Reqyests
復(fù)制腳本,在PyCharm中打開即可,在導(dǎo)入使用之前如果沒有reuqests庫,可能會報錯,我們需要安裝reuqests庫。
cmd命令窗口輸入:pip install requests
導(dǎo)出后的腳本格式如下:
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)
在一個項目中,根路由的路徑是一樣的,只是不同功能對應(yīng)的具體的接口不一致,且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ù),如果沒有,默認(rèn)為空 def get(self, uri, params=''): # 拼湊訪問地址 url = self.url_root + uri + params # 通過get請求訪問對應(yīng)地址 response = requests.get(url) # 返回request的response結(jié)果,類型為requests的Response類型 return response # post請求,uri是接口具體地址,params是post請求的參數(shù),如果沒有,默認(rèn)為空 def post(self, uri, params=''): # 拼湊訪問地址 url = self.url_root + uri # 有參數(shù),則訪問對應(yīng)的url,并賦值給默認(rèn)參數(shù)data if len(params) > 0: response = requests.post(url, data=params) # 無參數(shù),只需要訪問對應(yīng)的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é)果如下:
“如何用python編寫接口測試文檔”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。