我的代码如下:
import pytest
import requests
from unittest import mock
@mock.patch('requests.get')
def test_verify(mock_request):
mock_resp = mock.Mock()
mock_resp.status_code = 404
mock_request.return_value = mock_resp
r = requests.get()
with pytest.raises(requests.exceptions.HTTPError) as err_msg:
r.raise_for_status()
print(err_msg)
由于响应的状态码设置为404,所以我希望会引发HTTPError。但是,显示错误
Failed: DID NOT RAISE <class 'requests.exceptions.HTTPError'>
输出如下:
=========================================测试会话开始==== ==================================平台darwin-Python 3.6.4,pytest-3.7.0 ,py-1.5.2,pluggy-0.7.1 rootdir:/ Users / michael / Code / youtube-data-api,inifile:插件: requests-mock-1.5.2收集了1个项目
temp_test.py F
[100%]============================================失败= ============================================= ____________________________________________ test_verify ____________________________________________
mock_request =
@mock.patch('requests.get') def test_verify(mock_request): mock_resp = mock.Mock() mock_resp.status_code = 404 mock_request.return_value = mock_resp r = requests.get() #print(r.status_code) with pytest.raises(requests.exceptions.HTTPError) as err_msg: r.raise_for_status() E Failed: DID NOT RAISE <class 'requests.exceptions.HTTPError'>
temp_test.py:15:失败 ===================================== 1在0.12秒内失败======== =============================
答案 0 :(得分:0)
mock_resp
是mock.Mock()
对象。调用raise_for_status()
只会返回另一个Mock()
。
您需要使用保留原始raise_for_status()
的响应。试试这个:
import pytest
import requests
from unittest import mock
@mock.patch('requests.get')
def test_verify(mock_request):
mock_resp = requests.models.Response()
mock_resp.status_code = 404
mock_request.return_value = mock_resp
res = requests.get()
with pytest.raises(requests.exceptions.HTTPError) as err_msg:
res.raise_for_status()
print(err_msg)