【问题标题】:How do I assert that an HTTP exception was raised?如何断言引发了 HTTP 异常?
【发布时间】: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


    【解决方案1】:

    使用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 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 2019-01-28
      • 1970-01-01
      • 2023-03-03
      • 2012-04-07
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多