接口測試:Https接口禁用證書驗證以及InsecureRequestWarning信息的過濾方法


現在接手的項目中,部分依賴的數據要從Https接口獲取,在使用requests模塊發送請求后,會拋出SSLError。但我們測試過程中如果不想驗證證書,該怎么避免報錯的情況。下面介紹一下SSLError出現的原因及的處理方法。

出現原因

requests就像web瀏覽器一樣可以請求驗證SSL證書,且SSL驗證默認是開啟的,如果證書驗證失敗,就會拋出SSLError。

解決方案:關閉證書驗證

關閉證書驗證方法很簡單,參數verify設置成False,https接口就可以請求成功。

    requests.get('https://example.com', verify=False) 

后遺症

verify設置為false后,重新發送請求,系統會捕捉到InsecureRequestWarning。

/Users/tangyuanzheng/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) 

這段waring是不是奇丑無比,移除方法如下(僅適用於py3):

import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) requests.get('https://example.com', verify=False) 

添加兩行代碼就可以避免拋出InsecureRequestWarning,這樣日志清爽了很多。

InsecureRequestWarning再現

上述后遺症的解決,是在nosetest框架中,但最近研究pytest的時候,發現InsecureRequestWarning又出現了:

=============================== warnings summary =============================== testcase/business_vip/testApiVipHttpInterface/testcaseVipInfo_for_pytest.py::TestApiVipInfo::test_mem_info_normal[傳入【當前用戶】,驗證返回的用戶信息是否正確-18215603157-200] /Users/xmly/anaconda3/envs/py36/lib/python3.6/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) -- Docs: https://docs.pytest.org/en/latest/warnings.html - generated html file: file:///Users/Documents/文稿 - tangyuanzheng的MacBook Pro/api_automation/report.html - ===================== 1 passed, 6 warnings in 2.64 seconds ===================== 

回頭檢查了一下代碼,我明明已經禁用了InsecureRequestWarning,在pytest再次出現,具體的原因沒有去研究,下面還是直接給出解決方案:

方案1:用例層禁用

修改測試用例:

@pytest.mark.filterwarnings('ignore::urllib3.exceptions.InsecureRequestWarning') def test_example_com(): requests.get('https://www.example.com', verify=False) 

方案2:配置文件禁用

新建pytest.ini文件,添加以下代碼
[pytest]
filterwarnings =ignore::urllib3.exceptions.InsecureRequestWarning

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM