自己自學接口自動化過程遇到的問題及解決方法記錄
首先是一個簡單的請求
import requests#這是一個簡單是get請求
def test_get():geturl = 'https://so.csdn.net/api/v1/relevant-search?query=pycharm%E5%AE%89%E8%A3%85requests%E5%BA%93&platform=pc'getr = requests.get(url=geturl)print(getr.text)assert getr.status_code == 200#這是一個post請求
def test_post():posturl = 'https://so.csdn.net/api/v1/get_landing_word'postjson={'url':'https://blog.csdn.net/qq_43779149/article/details/122488766'}postr=requests.post(url=posturl,json=postjson)print(postr.text)list_postr = list(postr)# assert list_postr[1] == 200assert postr.status_code == 200
利用request庫發送請求
然后用pytest的命名規范寫了上述代碼,后面我需要用allure生成報告
問題一:allure是什么
? ? ? ? allure是第三方的命令行工具,無法直接通過python來安裝,需要去官網下載
問題二:allure-pytest是什么
? ? ? ? allure-pytest是Python 插件,用于生成測試數據,可以直接用pip來安裝
遇到的問題:
? ? ? ?一:官網下載的allure沒用bin目錄,無法用命令行去執行,最后還是在csdn上的某個博客上找到了個人分享的allure壓縮包
分享者是:@旺仔牛奶
分享鏈接是:pycharm中Allure的安裝及其環境配置_pycharm安裝allure-CSDN博客
????????鏈接:https://pan.baidu.com/s/1tMWm5p4sYXgcj5AP4GeRbg?pwd=284i?
????????提取碼:284i?
下載好allure后,需要找到bin目錄,并將其配置環境變量
????????點擊電腦,選擇屬性—>高級系統設置—>環境變量設置—>系統變量—>Path環境,然后
????????選中Path點擊編輯,然后選擇新建,然后將復制的Allure的bin目錄的路徑粘貼即可,然后點擊確定
上述兩個下載好之后進行驗證
驗證命令:pip show allure-pytest
驗證命令:allure --version
之后重啟PyCharm即可使用allure
之后使用代碼?
# 運行要進行測試的py文件,生成測試數據到當前目錄下的allure-results文件夾pytest.main(["-s", "alluredpytest.py", "--alluredir=allure-results"])# 執行allure服務,將allure-results文件夾的測試數據轉html,并自動打開網頁subprocess.run("allure serve allure-results", shell=True)# 服務處于開啟狀態,關閉服務則鏈接失效,不可查看報告
allure裝飾器的應用?
@allure.feature("CSDN接口測試") # 模塊/功能分類
class TestCSDNAPI: # 測試類@allure.story("GET接口測試") # 子功能/用戶場景分類@allure.title("搜索相關文章接口") # 用例標題(默認是函數名,可自定義)@allure.description("驗證GET請求返回狀態碼200") # 用例描述
?將上面的請求加上裝飾器的完整代碼如下
import allure
import requests@allure.feature("CSDN接口測試") # 模塊/功能分類
class TestCSDNAPI:@allure.story("GET接口測試") # 子功能/用戶場景分類@allure.title("搜索相關文章接口") # 用例標題(默認是函數名,可自定義)@allure.description("驗證GET請求返回狀態碼200") # 用例描述def test_get(self):with allure.step("步驟1:發送GET請求"): # 記錄詳細步驟geturl = 'https://so.csdn.net/api/v1/relevant-search?query=pycharm%E5%AE%89%E8%A3%85requests%E5%BA%93&platform=pc'getr = requests.get(url=geturl)allure.attach(f"請求URL: {geturl}", "請求詳情") # 附加請求信息到報告allure.attach(f"響應狀態碼: {getr.status_code}", "響應詳情")with allure.step("步驟2:驗證狀態碼"):print(getr.text)assert getr.status_code == 200, "狀態碼非200" # 斷言失敗時顯示自定義錯誤信息@allure.story("POST接口測試")@allure.title("獲取落地頁關鍵詞接口")def test_post(self):posturl = 'https://so.csdn.net/api/v1/get_landing_word'postjson = {'url': 'https://blog.csdn.net/qq_43779149/article/details/122488766'}with allure.step("發送POST請求"):postr = requests.post(url=posturl, json=postjson)# 將請求和響應數據附加到Allure報告allure.attach(str(postjson), "請求Body", allure.attachment_type.JSON)allure.attach(postr.text, "響應Body", allure.attachment_type.JSON)with allure.step("驗證狀態碼"):# 移除有問題的 list_postr = list(postr)(Response對象不能直接轉為list)assert postr.status_code == 200, f"狀態碼錯誤,實際為{postr.status_code}"
運行allure服務,并且自動打開測試報告頁面,查看詳細報告
?
?