test_exceptions.py
This file
Path
tests/test_exceptions.py
86 lines · 2.3 KiB · Python
Last changed by
use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
History of this fileTake 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 and value is not httpcore.ConnectionNotAvailable22 ]2324 if not_mapped: # pragma: no cover25 pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}")262728def test_httpcore_exception_mapping(server) -> None:29 """30 HTTPCore exception mapping works as expected.31 """3233 def connect_failed(*args, **kwargs):34 raise httpcore.ConnectError()3536 class TimeoutStream:37 def __iter__(self):38 raise httpcore.ReadTimeout()3940 def close(self):41 pass4243 with mock.patch(44 "httpcore.ConnectionPool.handle_request", side_effect=connect_failed45 ):46 with pytest.raises(httpx.ConnectError):47 httpx.get(server.url)4849 with mock.patch(50 "httpcore.ConnectionPool.handle_request",51 return_value=httpcore.Response(52 200, headers=[], content=TimeoutStream(), extensions={}53 ),54 ):55 with pytest.raises(httpx.ReadTimeout):56 httpx.get(server.url)575859def test_httpx_exceptions_exposed() -> None:60 """61 All exception classes defined in `httpx._exceptions`62 are exposed as public API.63 """6465 not_exposed = [66 value67 for name, value in vars(httpx._exceptions).items()68 if isinstance(value, type)69 and issubclass(value, Exception)70 and not hasattr(httpx, name)71 ]7273 if not_exposed: # pragma: no cover74 pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")757677def test_request_attribute() -> None:78 # Exception without request attribute79 exc = httpx.ReadTimeout("Read operation timed out")80 with pytest.raises(RuntimeError):81 exc.request8283 # Exception with request attribute84 request = httpx.Request("GET", "https://www.example.com")85 exc = httpx.ReadTimeout("Read operation timed out", request=request)86 assert exc.request == request