接口测试: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

总结

通常来讲,调用https接口需要传入证书以保证安全性,但是通常在test环境测试时,证书验证并不是我首要关注的问题,而且会造成很多的麻烦,禁用反而会让测试进度通畅无比。以上时自己对于https接口的处理方案,希望对大家有所帮助吧。

你可能感兴趣的:(接口测试:Https接口禁用证书验证以及InsecureRequestWarning信息的过滤方法)