【发布时间】:2020-04-20 14:11:08
【问题描述】:
我正在使用 requests 库发出 HTTP 请求。如果请求失败,则会引发异常。例如(截断和简化):
main.py
from requests import get
def make_request():
r = get("https://httpbin.org/get")
r.raise_for_status()
我使用 pytest 编写了一个模拟请求的测试。
test_main.py
from unittest import mock
from unittest.mock import patch
import pytest
from requests import HTTPError
from main import make_request
@patch("main.get")
def test_main_exception(mock_get):
exception = HTTPError(mock.Mock(status=404), "not found")
mock_get(mock.ANY).raise_for_status.side_effect = exception
make_request()
但是,我收到以下错误,因为在测试中引发了异常,导致测试失败。
$ pytest
...
E requests.exceptions.HTTPError: [Errno <Mock id='4352275232'>] not found
/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py:1011: HTTPError
==================================================== 1 failed in 0.52s ====================================================
如何断言引发 HTTP 异常时发生的行为(例如 404 状态代码)?
【问题讨论】:
标签: python unit-testing python-requests pytest