简体   繁体   English

如何断言已引发 HTTP 异常?

[英]How do I assert that an HTTP exception was raised?

I'm making an HTTP request using the requests library.我正在使用请求库发出 HTTP 请求。 If the request fails, an exception is raised.如果请求失败,则会引发异常。 For example (truncated and simplified):例如(截断和简化):

main.py

from requests import get


def make_request():
    r = get("https://httpbin.org/get")
    r.raise_for_status()

I've written a test using pytest that mocks the request.我已经使用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()

However, I'm getting the following error because the exception is raised in the test—causing the test to fail.但是,我收到以下错误,因为在测试中引发了异常 - 导致测试失败。

$ 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 ====================================================

How do I assert on the behavior that occurs when an HTTP exception is raised (eg 404 status code)?如何对引发 HTTP 异常(例如 404 状态代码)时发生的行为进行断言?

Use the pytest.raises context manager to capture the exception and assert on the error message.使用pytest.raises上下文管理器捕获异常并对错误消息进行断言。 For example:例如:

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

Full example:完整示例:

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

See pytest - Assertions about expected exceptions for more info.有关更多信息,请参阅pytest - 关于预期异常的断言

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM