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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值