Skip to content
Myr

test_exceptions.py

This file

Path

tests/test_exceptions.py

95 lines · 2.5 KiB · Python

Last changed by

Transport API (#1522)Tom Christiebefore adoption1a6e254

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("httpcore.SyncConnectionPool.request", side_effect=connect_failed):50        with pytest.raises(httpx.ConnectError):51            httpx.get(server.url)5253    with mock.patch(54        "httpcore.SyncConnectionPool.request",55        return_value=(200, [], TimeoutStream(), {}),56    ):57        with pytest.raises(httpx.ReadTimeout):58            httpx.get(server.url)5960    with mock.patch(61        "httpcore.SyncConnectionPool.request",62        return_value=(200, [], CloseFailedStream(), {}),63    ):64        with pytest.raises(httpx.CloseError):65            httpx.get(server.url)666768def test_httpx_exceptions_exposed() -> None:69    """70    All exception classes defined in `httpx._exceptions`71    are exposed as public API.72    """7374    not_exposed = [75        value76        for name, value in vars(httpx._exceptions).items()77        if isinstance(value, type)78        and issubclass(value, Exception)79        and not hasattr(httpx, name)80    ]8182    if not_exposed:  # pragma: nocover83        pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")848586def test_request_attribute() -> None:87    # Exception without request attribute88    exc = httpx.ReadTimeout("Read operation timed out")89    with pytest.raises(RuntimeError):90        exc.request9192    # Exception with request attribute93    request = httpx.Request("GET", "https://www.example.com")94    exc = httpx.ReadTimeout("Read operation timed out", request=request)95    assert exc.request == request