如何断言引发了HTTP异常?

时间:2020-01-01 17:00:15

标签: python unit-testing python-requests pytest

我正在使用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状态代码)时发生的行为?

1 个答案:

答案 0 :(得分:0)

使用pytest.raises上下文管理器捕获异常并对错误消息进行断言。例如:

with pytest.raises(HTTPError) as error_info:
    make_request()
    assert error_info == exception

完整示例:

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

    with pytest.raises(HTTPError) as error_info:
        make_request()
        assert error_info == exception

有关更多信息,请参见pytest - Assertions about expected exceptions