Skip to content
Myr

test_exceptions.py

This file

Path

tests/test_exceptions.py

68 lines · 1.9 KiB · Python

Last changed by

Map httpcore exceptions for `Response` read methods (#1190)Joebefore adoption03cd88c

History of this file

Take it

1from typing import Any23import httpcore4import pytest56import httpx7from httpx._exceptions 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    # Make sure we don't just map to `NetworkError`.33    with pytest.raises(httpx.ConnectError):34        httpx.get("http://doesnotexist")3536    # Make sure streaming methods also map exceptions.37    url = server.url.copy_with(path="/slow_stream_response")38    timeout = httpx.Timeout(None, read=0.1)39    with httpx.stream("GET", url, timeout=timeout) as stream:40        with pytest.raises(httpx.ReadTimeout):41            stream.read()4243    # Make sure it also works with custom transports.44    class MockTransport(httpcore.SyncHTTPTransport):45        def request(self, *args: Any, **kwargs: Any) -> Any:46            raise httpcore.ProtocolError()4748    client = httpx.Client(transport=MockTransport())49    with pytest.raises(httpx.ProtocolError):50        client.get("http://testserver")515253def test_httpx_exceptions_exposed() -> None:54    """55    All exception classes defined in `httpx._exceptions`56    are exposed as public API.57    """5859    not_exposed = [60        value61        for name, value in vars(httpx._exceptions).items()62        if isinstance(value, type)63        and issubclass(value, Exception)64        and not hasattr(httpx, name)65    ]6667    if not_exposed:  # pragma: nocover68        pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")