test_exceptions.py
This file
Path
tests/test_exceptions.py
90 lines · 2.4 KiB · Python
Last changed by
Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5
History of this fileTake it
1import typing2from unittest import mock34import httpcore5import pytest67import httpx8from httpx._transports.default import HTTPCORE_EXC_MAP910if typing.TYPE_CHECKING: # pragma: no cover11 from conftest import TestServer121314def test_httpcore_all_exceptions_mapped() -> None:15 """16 All exception classes exposed by HTTPCore are properly mapped to an HTTPX-specific17 exception class.18 """19 not_mapped = [20 value21 for name, value in vars(httpcore).items()22 if isinstance(value, type)23 and issubclass(value, Exception)24 and value not in HTTPCORE_EXC_MAP25 and value is not httpcore.ConnectionNotAvailable26 ]2728 if not_mapped: # pragma: no cover29 pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}")303132def test_httpcore_exception_mapping(server: "TestServer") -> None:33 """34 HTTPCore exception mapping works as expected.35 """3637 def connect_failed(*args, **kwargs):38 raise httpcore.ConnectError()3940 class TimeoutStream:41 def __iter__(self):42 raise httpcore.ReadTimeout()4344 def close(self):45 pass4647 with mock.patch(48 "httpcore.ConnectionPool.handle_request", side_effect=connect_failed49 ):50 with pytest.raises(httpx.ConnectError):51 httpx.get(server.url)5253 with mock.patch(54 "httpcore.ConnectionPool.handle_request",55 return_value=httpcore.Response(56 200, headers=[], content=TimeoutStream(), extensions={}57 ),58 ):59 with pytest.raises(httpx.ReadTimeout):60 httpx.get(server.url)616263def test_httpx_exceptions_exposed() -> None:64 """65 All exception classes defined in `httpx._exceptions`66 are exposed as public API.67 """6869 not_exposed = [70 value71 for name, value in vars(httpx._exceptions).items()72 if isinstance(value, type)73 and issubclass(value, Exception)74 and not hasattr(httpx, name)75 ]7677 if not_exposed: # pragma: no cover78 pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")798081def test_request_attribute() -> None:82 # Exception without request attribute83 exc = httpx.ReadTimeout("Read operation timed out")84 with pytest.raises(RuntimeError):85 exc.request8687 # Exception with request attribute88 request = httpx.Request("GET", "https://www.example.com")89 exc = httpx.ReadTimeout("Read operation timed out", request=request)90 assert exc.request == request