Skip to content
Myr

test_exceptions.py

This file

Path

tests/test_exceptions.py

97 lines 路 2.5 KiB 路 Python

Last changed by

Support HTTPCore 0.13 (#1588)Tom Christiebefore adoptiond98e9e7

History of this file

Take it

1from unittest import mock23import httpcore4import pytest56import httpx7from httpx._transports.default import HTTPCORE_EXC_MAP8910def test_httpcore_all_exceptions_mapped() -> None:11    """12    All exception classes exposed by HTTPCore are properly mapped to an HTTPX-specific13    exception class.14    """15    not_mapped = [16        value17        for name, value in vars(httpcore).items()18        if isinstance(value, type)19        and issubclass(value, Exception)20        and value not in HTTPCORE_EXC_MAP21    ]2223    if not_mapped:  # pragma: nocover24        pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}")252627def test_httpcore_exception_mapping(server) -> None:28    """29    HTTPCore exception mapping works as expected.30    """3132    def connect_failed(*args, **kwargs):33        raise httpcore.ConnectError()3435    class TimeoutStream:36        def __iter__(self):37            raise httpcore.ReadTimeout()3839        def close(self):40            pass4142    class CloseFailedStream:43        def __iter__(self):44            yield b""4546        def close(self):47            raise httpcore.CloseError()4849    with mock.patch(50        "httpcore.SyncConnectionPool.handle_request", side_effect=connect_failed51    ):52        with pytest.raises(httpx.ConnectError):53            httpx.get(server.url)5455    with mock.patch(56        "httpcore.SyncConnectionPool.handle_request",57        return_value=(200, [], TimeoutStream(), {}),58    ):59        with pytest.raises(httpx.ReadTimeout):60            httpx.get(server.url)6162    with mock.patch(63        "httpcore.SyncConnectionPool.handle_request",64        return_value=(200, [], CloseFailedStream(), {}),65    ):66        with pytest.raises(httpx.CloseError):67            httpx.get(server.url)686970def test_httpx_exceptions_exposed() -> None:71    """72    All exception classes defined in `httpx._exceptions`73    are exposed as public API.74    """7576    not_exposed = [77        value78        for name, value in vars(httpx._exceptions).items()79        if isinstance(value, type)80        and issubclass(value, Exception)81        and not hasattr(httpx, name)82    ]8384    if not_exposed:  # pragma: nocover85        pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")868788def test_request_attribute() -> None:89    # Exception without request attribute90    exc = httpx.ReadTimeout("Read operation timed out")91    with pytest.raises(RuntimeError):92        exc.request9394    # Exception with request attribute95    request = httpx.Request("GET", "https://www.example.com")96    exc = httpx.ReadTimeout("Read operation timed out", request=request)97    assert exc.request == request