From 1ffa26a2ba04c709bb3f75f88b6892def50d8f4e Mon Sep 17 00:00:00 2001 From: m-xim <170838360+m-xim@users.noreply.github.com> Date: Mon, 14 Sep 2026 23:51:35 +0300 Subject: [PATCH 1/7] feat: add NonRetryableError --- src/unihttp/clients/aiohttp.py | 49 +++++++++++++++-------- src/unihttp/clients/errors.py | 18 +++++++++ src/unihttp/clients/httpx.py | 46 ++++++++++++---------- src/unihttp/clients/httpx2.py | 46 ++++++++++++---------- src/unihttp/clients/niquests.py | 64 ++++++++++++++++-------------- src/unihttp/clients/requests.py | 43 ++++++++++++++------ src/unihttp/clients/urllib.py | 68 +++++++++++++++++--------------- src/unihttp/clients/zapros.py | 70 ++++++++++++++++----------------- src/unihttp/exceptions.py | 4 ++ 9 files changed, 243 insertions(+), 165 deletions(-) create mode 100644 src/unihttp/clients/errors.py diff --git a/src/unihttp/clients/aiohttp.py b/src/unihttp/clients/aiohttp.py index b09c553..9451705 100644 --- a/src/unihttp/clients/aiohttp.py +++ b/src/unihttp/clients/aiohttp.py @@ -7,7 +7,13 @@ from aiohttp import ClientResponse, ClientSession, FormData from unihttp.clients.base import BaseAsyncClient -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.clients.errors import ErrorMap, translate_errors +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, + UniHTTPError, +) from unihttp.http import UploadFile from unihttp.http.request import HTTPRequest from unihttp.http.response import HTTPResponse @@ -15,6 +21,25 @@ from unihttp.middlewares.base import AsyncMiddleware from unihttp.serialize import RequestDumper, ResponseLoader +# Timeout first: ServerTimeoutError is also a ClientConnectionError. +_ERROR_MAP: ErrorMap = { + RequestTimeoutError: TimeoutError, + # Explicit: status and misuse errors must fall through to plain UniHTTPError. + NetworkError: ( + aiohttp.ClientConnectionError, + aiohttp.ClientPayloadError, + aiohttp.ClientHttpProxyError, + ), + # After NetworkError: a certificate error is also a ValueError. + # ValueError: aiohttp raises it bare for forbidden characters in headers. + NonRetryableError: ( + ValueError, + aiohttp.NonHttpUrlClientError, + aiohttp.TooManyRedirects, + ), + UniHTTPError: aiohttp.ClientError, +} + class _AiohttpChunkStream(AsyncChunkStream): def __init__(self, response: ClientResponse, chunk_size: int) -> None: @@ -23,12 +48,8 @@ def __init__(self, response: ClientResponse, chunk_size: int) -> None: self._iter = response.content.iter_chunked(chunk_size) async def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return await anext(self._iter) - except aiohttp.ClientConnectionError as e: - raise NetworkError(str(e)) from e - except TimeoutError as e: - raise RequestTimeoutError(str(e)) from e async def _close_response(self) -> None: self._response.close() @@ -105,7 +126,7 @@ def _build_data(self, request: HTTPRequest) -> FormData | str | bytes | None: async def _do_request(self, request: HTTPRequest) -> ClientResponse: data = self._build_data(request) - try: + with translate_errors(_ERROR_MAP): return await self._session.request( method=request.method, url=urljoin(self.base_url, request.url), @@ -113,23 +134,17 @@ async def _do_request(self, request: HTTPRequest) -> ClientResponse: params=request.query, data=data, ) - except aiohttp.ClientConnectionError as e: - raise NetworkError(str(e)) from e - except TimeoutError as e: - raise RequestTimeoutError(str(e)) from e async def make_request(self, request: HTTPRequest) -> HTTPResponse: response = await self._do_request(request) response_data: Any = None try: - content = await response.read() - except aiohttp.ClientConnectionError as e: - response.close() - raise NetworkError(str(e)) from e - except TimeoutError as e: + with translate_errors(_ERROR_MAP): + content = await response.read() + except UniHTTPError: response.close() - raise RequestTimeoutError(str(e)) from e + raise if content: try: response_data = self.json_loads(content) diff --git a/src/unihttp/clients/errors.py b/src/unihttp/clients/errors.py new file mode 100644 index 0000000..1054862 --- /dev/null +++ b/src/unihttp/clients/errors.py @@ -0,0 +1,18 @@ +from collections.abc import Generator +from contextlib import contextmanager + +from unihttp.exceptions import UniHTTPError + +ErrorMap = dict[type[UniHTTPError], type[BaseException] | tuple[type[BaseException], ...]] + + +@contextmanager +def translate_errors(mapping: ErrorMap) -> Generator[None, None, None]: + """Re-raise backend exceptions as unihttp ones; the first matching entry wins.""" + try: + yield + except Exception as e: + for target, types in mapping.items(): + if isinstance(e, types): + raise target(str(e)) from e + raise diff --git a/src/unihttp/clients/httpx.py b/src/unihttp/clients/httpx.py index 21836c3..b4943a4 100644 --- a/src/unihttp/clients/httpx.py +++ b/src/unihttp/clients/httpx.py @@ -7,7 +7,13 @@ from httpx import AsyncClient, Client, Response from unihttp.clients.base import BaseAsyncClient, BaseSyncClient -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.clients.errors import ErrorMap, translate_errors +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, + UniHTTPError, +) from unihttp.http import UploadFile from unihttp.http.request import HTTPRequest from unihttp.http.response import HTTPResponse @@ -15,6 +21,20 @@ from unihttp.middlewares.base import AsyncMiddleware, Middleware from unihttp.serialize import RequestDumper, ResponseLoader +# Timeout first: TimeoutException is also a RequestError. +_ERROR_MAP: ErrorMap = { + RequestTimeoutError: httpx.TimeoutException, + NonRetryableError: ( + httpx.InvalidURL, + httpx.UnsupportedProtocol, + httpx.LocalProtocolError, + httpx.TooManyRedirects, + httpx.DecodingError, + ), + NetworkError: httpx.RequestError, + UniHTTPError: httpx.HTTPError, +} + class _HTTPXChunkStream(ChunkStream): def __init__(self, response: Response, chunk_size: int) -> None: @@ -23,12 +43,8 @@ def __init__(self, response: Response, chunk_size: int) -> None: self._iter = response.iter_bytes(chunk_size) def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return next(self._iter) - except httpx.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e def _close_response(self) -> None: self._response.close() @@ -43,12 +59,8 @@ def __init__(self, response: Response, chunk_size: int) -> None: self._iter = response.aiter_bytes(chunk_size) async def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return await anext(self._iter) - except httpx.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e async def _close_response(self) -> None: await self._response.aclose() @@ -111,7 +123,7 @@ def _build_content(self, request: HTTPRequest) -> Any: def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: content = self._build_content(request) - try: + with translate_errors(_ERROR_MAP): files = self._convert_files(request.file) if request.file else None built_request = self._session.build_request( method=request.method, @@ -123,10 +135,6 @@ def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: data=request.form, ) return self._session.send(built_request, stream=stream) - except httpx.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e def make_request(self, request: HTTPRequest) -> HTTPResponse: response = self._do_request(request, stream=False) @@ -220,7 +228,7 @@ def _build_content(self, request: HTTPRequest) -> Any: async def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: content = self._build_content(request) - try: + with translate_errors(_ERROR_MAP): files = self._convert_files(request.file) if request.file else None built_request = self._session.build_request( method=request.method, @@ -232,10 +240,6 @@ async def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: data=request.form, ) return await self._session.send(built_request, stream=stream) - except httpx.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e async def make_request(self, request: HTTPRequest) -> HTTPResponse: response = await self._do_request(request, stream=False) diff --git a/src/unihttp/clients/httpx2.py b/src/unihttp/clients/httpx2.py index 14a2f5b..93093c3 100644 --- a/src/unihttp/clients/httpx2.py +++ b/src/unihttp/clients/httpx2.py @@ -7,7 +7,13 @@ from httpx2 import AsyncClient, Client, Response from unihttp.clients.base import BaseAsyncClient, BaseSyncClient -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.clients.errors import ErrorMap, translate_errors +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, + UniHTTPError, +) from unihttp.http import UploadFile from unihttp.http.request import HTTPRequest from unihttp.http.response import HTTPResponse @@ -15,6 +21,20 @@ from unihttp.middlewares.base import AsyncMiddleware, Middleware from unihttp.serialize import RequestDumper, ResponseLoader +# Timeout first: TimeoutException is also a RequestError. +_ERROR_MAP: ErrorMap = { + RequestTimeoutError: httpx2.TimeoutException, + NonRetryableError: ( + httpx2.InvalidURL, + httpx2.UnsupportedProtocol, + httpx2.LocalProtocolError, + httpx2.TooManyRedirects, + httpx2.DecodingError, + ), + NetworkError: httpx2.RequestError, + UniHTTPError: httpx2.HTTPError, +} + class _HTTPX2ChunkStream(ChunkStream): def __init__(self, response: Response, chunk_size: int) -> None: @@ -23,12 +43,8 @@ def __init__(self, response: Response, chunk_size: int) -> None: self._iter = response.iter_bytes(chunk_size) def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return next(self._iter) - except httpx2.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx2.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e def _close_response(self) -> None: self._response.close() @@ -43,12 +59,8 @@ def __init__(self, response: Response, chunk_size: int) -> None: self._iter = response.aiter_bytes(chunk_size) async def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return await anext(self._iter) - except httpx2.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx2.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e async def _close_response(self) -> None: await self._response.aclose() @@ -111,7 +123,7 @@ def _build_content(self, request: HTTPRequest) -> Any: def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: content = self._build_content(request) - try: + with translate_errors(_ERROR_MAP): files = self._convert_files(request.file) if request.file else None built_request = self._session.build_request( method=request.method, @@ -123,10 +135,6 @@ def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: data=request.form, ) return self._session.send(built_request, stream=stream) - except httpx2.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx2.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e def make_request(self, request: HTTPRequest) -> HTTPResponse: response = self._do_request(request, stream=False) @@ -220,7 +228,7 @@ def _build_content(self, request: HTTPRequest) -> Any: async def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: content = self._build_content(request) - try: + with translate_errors(_ERROR_MAP): files = self._convert_files(request.file) if request.file else None built_request = self._session.build_request( method=request.method, @@ -232,10 +240,6 @@ async def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: data=request.form, ) return await self._session.send(built_request, stream=stream) - except httpx2.NetworkError as e: - raise NetworkError(str(e)) from e - except httpx2.TimeoutException as e: - raise RequestTimeoutError(str(e)) from e async def make_request(self, request: HTTPRequest) -> HTTPResponse: response = await self._do_request(request, stream=False) diff --git a/src/unihttp/clients/niquests.py b/src/unihttp/clients/niquests.py index 0a87c17..e92b5a4 100644 --- a/src/unihttp/clients/niquests.py +++ b/src/unihttp/clients/niquests.py @@ -7,7 +7,13 @@ from niquests import AsyncResponse, AsyncSession, Response, Session from unihttp.clients.base import BaseAsyncClient, BaseSyncClient -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.clients.errors import ErrorMap, translate_errors +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, + UniHTTPError, +) from unihttp.http import UploadFile from unihttp.http.request import HTTPRequest from unihttp.http.response import HTTPResponse @@ -15,6 +21,30 @@ from unihttp.middlewares.base import AsyncMiddleware, Middleware from unihttp.serialize import RequestDumper, ResponseLoader +# Timeout first: ConnectTimeout is also a ConnectionError. +_ERROR_MAP: ErrorMap = { + RequestTimeoutError: niquests.exceptions.Timeout, + NonRetryableError: ( + niquests.exceptions.MissingSchema, + niquests.exceptions.InvalidSchema, + niquests.exceptions.InvalidURL, + niquests.exceptions.InvalidHeader, + niquests.exceptions.InvalidJSONError, + niquests.exceptions.URLRequired, + niquests.exceptions.TooManyRedirects, + niquests.exceptions.ContentDecodingError, + niquests.exceptions.UnrewindableBodyError, + ), + # Explicit: status and misuse errors must fall through to plain UniHTTPError. + NetworkError: ( + niquests.exceptions.ConnectionError, + niquests.exceptions.ChunkedEncodingError, + niquests.exceptions.RetryError, + niquests.exceptions.MultiplexingError, + ), + UniHTTPError: niquests.exceptions.RequestException, +} + class _NiquestsChunkStream(ChunkStream): def __init__(self, response: Response, chunk_size: int) -> None: @@ -23,14 +53,8 @@ def __init__(self, response: Response, chunk_size: int) -> None: self._iter = response.iter_content(chunk_size=chunk_size) def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return next(self._iter) - except niquests.exceptions.ConnectionError as e: - raise NetworkError(str(e)) from e - except niquests.exceptions.Timeout as e: - raise RequestTimeoutError(str(e)) from e - except niquests.exceptions.RequestException as e: - raise NetworkError(str(e)) from e def _close_response(self) -> None: self._response.close() @@ -50,14 +74,8 @@ def __init__(self, response: AsyncResponse, chunk_iter: Any) -> None: self._iter = chunk_iter async def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return await anext(self._iter) - except niquests.exceptions.ConnectionError as e: - raise NetworkError(str(e)) from e - except niquests.exceptions.Timeout as e: - raise RequestTimeoutError(str(e)) from e - except niquests.exceptions.RequestException as e: - raise NetworkError(str(e)) from e async def _close_response(self) -> None: await self._response.close() @@ -131,7 +149,7 @@ def _build_content(self, request: HTTPRequest) -> Any: def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: content = self._build_content(request) - try: + with translate_errors(_ERROR_MAP): files = self._convert_files(request.file) if request.file else None return self._session.request( method=request.method, @@ -142,12 +160,6 @@ def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: data=content, stream=stream, ) - except niquests.exceptions.ConnectionError as e: - raise NetworkError(str(e)) from e - except niquests.exceptions.Timeout as e: - raise RequestTimeoutError(str(e)) from e - except niquests.exceptions.RequestException as e: - raise NetworkError(str(e)) from e def make_request(self, request: HTTPRequest) -> HTTPResponse: response = self._do_request(request, stream=False) @@ -259,7 +271,7 @@ async def _do_request( content = self._build_content(request) files = self._convert_files(request.file) if request.file else None - try: + with translate_errors(_ERROR_MAP): if stream: return await self._session.request( method=request.method, @@ -279,12 +291,6 @@ async def _do_request( data=content, stream=False, ) - except niquests.exceptions.ConnectionError as e: - raise NetworkError(str(e)) from e - except niquests.exceptions.Timeout as e: - raise RequestTimeoutError(str(e)) from e - except niquests.exceptions.RequestException as e: - raise NetworkError(str(e)) from e async def make_request(self, request: HTTPRequest) -> HTTPResponse: response = await self._do_request(request, stream=False) diff --git a/src/unihttp/clients/requests.py b/src/unihttp/clients/requests.py index cedda2f..212af03 100644 --- a/src/unihttp/clients/requests.py +++ b/src/unihttp/clients/requests.py @@ -5,13 +5,42 @@ from requests import Response, Session from unihttp.clients.base import BaseSyncClient -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.clients.errors import ErrorMap, translate_errors +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, + UniHTTPError, +) from unihttp.http.request import HTTPRequest from unihttp.http.response import HTTPResponse from unihttp.http.stream import ChunkStream from unihttp.middlewares.base import Middleware from unihttp.serialize import RequestDumper, ResponseLoader +# Timeout first: ConnectTimeout is also a ConnectionError. +_ERROR_MAP: ErrorMap = { + RequestTimeoutError: requests.exceptions.Timeout, + NonRetryableError: ( + requests.exceptions.MissingSchema, + requests.exceptions.InvalidSchema, + requests.exceptions.InvalidURL, + requests.exceptions.InvalidHeader, + requests.exceptions.InvalidJSONError, + requests.exceptions.URLRequired, + requests.exceptions.TooManyRedirects, + requests.exceptions.ContentDecodingError, + requests.exceptions.UnrewindableBodyError, + ), + # Explicit: status and misuse errors must fall through to plain UniHTTPError. + NetworkError: ( + requests.exceptions.ConnectionError, + requests.exceptions.ChunkedEncodingError, + requests.exceptions.RetryError, + ), + UniHTTPError: requests.exceptions.RequestException, +} + class _RequestsChunkStream(ChunkStream): def __init__(self, response: Response, chunk_size: int) -> None: @@ -20,12 +49,8 @@ def __init__(self, response: Response, chunk_size: int) -> None: self._iter = response.iter_content(chunk_size=chunk_size) def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return next(self._iter) - except requests.exceptions.ConnectionError as e: - raise NetworkError(str(e)) from e - except requests.exceptions.Timeout as e: - raise RequestTimeoutError(str(e)) from e def _close_response(self) -> None: self._response.close() @@ -68,7 +93,7 @@ def _build_content(self, request: HTTPRequest) -> Any: def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: content = self._build_content(request) - try: + with translate_errors(_ERROR_MAP): return self._session.request( method=request.method, url=urljoin(self.base_url, request.url), @@ -78,10 +103,6 @@ def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response: data=content, stream=stream, ) - except requests.exceptions.ConnectionError as e: - raise NetworkError(str(e)) from e - except requests.exceptions.Timeout as e: - raise RequestTimeoutError(str(e)) from e def make_request(self, request: HTTPRequest) -> HTTPResponse: response = self._do_request(request, stream=False) diff --git a/src/unihttp/clients/urllib.py b/src/unihttp/clients/urllib.py index e5ac1cd..aa2738a 100644 --- a/src/unihttp/clients/urllib.py +++ b/src/unihttp/clients/urllib.py @@ -4,12 +4,18 @@ import urllib.request import uuid from collections.abc import Callable +from contextlib import closing from http.cookies import SimpleCookie from typing import Any from urllib.parse import urlencode, urljoin from unihttp.clients.base import BaseSyncClient -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.clients.errors import ErrorMap, translate_errors +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, +) from unihttp.http import UploadFile from unihttp.http.request import HTTPRequest from unihttp.http.response import HTTPResponse @@ -19,6 +25,14 @@ _UrllibResponse = http.client.HTTPResponse | urllib.error.HTTPError +# Timeout first: TimeoutError is also an OSError. +_ERROR_MAP: ErrorMap = { + RequestTimeoutError: TimeoutError, + # ValueError: malformed URL or header, raised before any I/O. + NonRetryableError: (ValueError, http.client.InvalidURL), + NetworkError: (OSError, http.client.HTTPException), +} + class _UrllibChunkStream(ChunkStream): def __init__(self, raw: _UrllibResponse, chunk_size: int) -> None: @@ -27,12 +41,11 @@ def __init__(self, raw: _UrllibResponse, chunk_size: int) -> None: self._chunk_size = chunk_size def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): chunk = self._raw.read(self._chunk_size) - except TimeoutError as e: - raise RequestTimeoutError(str(e)) from e - except (OSError, http.client.HTTPException) as e: - raise NetworkError(str(e)) from e + # read(amt) returns b"" on a body cut short instead of raising. + if not chunk and self._raw.length: + raise http.client.IncompleteRead(b"", self._raw.length) if not chunk: raise StopIteration return chunk @@ -170,36 +183,29 @@ def _do_request(self, request: HTTPRequest) -> _UrllibResponse: headers = dict(request.header) body = self._prepare_body(request, headers) - req = urllib.request.Request( # noqa: S310 # base_url is developer-controlled - url=self._build_url(request), - data=body, - headers=headers, - method=request.method, - ) - - try: - return self._opener.open(req, timeout=self._timeout) - except urllib.error.HTTPError as e: - # HTTPError is itself a valid response object for non-2xx statuses. - return e - except urllib.error.URLError as e: - if isinstance(e.reason, TimeoutError): - raise RequestTimeoutError(str(e)) from e - raise NetworkError(str(e)) from e - except TimeoutError as e: - raise RequestTimeoutError(str(e)) from e + with translate_errors(_ERROR_MAP): + req = urllib.request.Request( # noqa: S310 # base_url is developer-controlled + url=self._build_url(request), + data=body, + headers=headers, + method=request.method, + ) + try: + return self._opener.open(req, timeout=self._timeout) + except urllib.error.HTTPError as e: + # HTTPError is itself a valid response object for non-2xx statuses. + return e + except urllib.error.URLError as e: + # The real cause is in `reason`: an OSError, or a string for bad input. + if isinstance(e.reason, OSError): + raise e.reason from None + raise ValueError(e.reason) from None def make_request(self, request: HTTPRequest) -> HTTPResponse: raw = self._do_request(request) - try: + with closing(raw), translate_errors(_ERROR_MAP): content = raw.read() - except TimeoutError as e: - raw.close() - raise RequestTimeoutError(str(e)) from e - except (OSError, http.client.HTTPException) as e: - raw.close() - raise NetworkError(str(e)) from e response_data: Any = None if content: diff --git a/src/unihttp/clients/zapros.py b/src/unihttp/clients/zapros.py index 2d15111..06522a7 100644 --- a/src/unihttp/clients/zapros.py +++ b/src/unihttp/clients/zapros.py @@ -5,11 +5,18 @@ from typing import Any from urllib.parse import urljoin +import h11 import zapros from zapros import AsyncClient, Client, Multipart, Part from unihttp.clients.base import BaseAsyncClient, BaseSyncClient -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.clients.errors import ErrorMap, translate_errors +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, + UniHTTPError, +) from unihttp.http import UploadFile from unihttp.http.request import HTTPRequest from unihttp.http.response import HTTPResponse @@ -17,6 +24,25 @@ from unihttp.middlewares.base import AsyncMiddleware, Middleware from unihttp.serialize import RequestDumper, ResponseLoader +# zapros lets h11 errors and URL/port ValueErrors through unwrapped. +_ERROR_MAP: ErrorMap = { + RequestTimeoutError: zapros.TimeoutError, + NonRetryableError: ( + zapros.DecodingError, + zapros.TooManyRedirectsError, + h11.LocalProtocolError, + ValueError, + ), + # Explicit: status and misuse errors must fall through to plain UniHTTPError. + NetworkError: ( + zapros.ConnectionError, + zapros.ReadError, + zapros.WriteError, + h11.RemoteProtocolError, + ), + UniHTTPError: zapros.ZaprosError, +} + class _ZaprosChunkStream(ChunkStream): def __init__(self, response: Any, chunk_size: int, stack: ExitStack) -> None: @@ -25,12 +51,8 @@ def __init__(self, response: Any, chunk_size: int, stack: ExitStack) -> None: self._stack = stack def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return next(self._iter) - except zapros.TimeoutError as e: - raise RequestTimeoutError(str(e)) from e - except zapros.ConnectionError as e: - raise NetworkError(str(e)) from e def _close_response(self) -> None: self._stack.close() @@ -45,12 +67,8 @@ def __init__(self, response: Any, chunk_size: int, stack: AsyncExitStack) -> Non self._stack = stack async def _fetch_chunk(self) -> bytes: - try: + with translate_errors(_ERROR_MAP): return await anext(self._iter) - except zapros.TimeoutError as e: - raise RequestTimeoutError(str(e)) from e - except zapros.ConnectionError as e: - raise NetworkError(str(e)) from e async def _close_response(self) -> None: await self._stack.aclose() @@ -198,7 +216,7 @@ def _build_payload( def make_request(self, request: HTTPRequest) -> HTTPResponse: body, form, multipart = self._build_payload(request) - try: + with translate_errors(_ERROR_MAP): response = self._session.request( # type: ignore[call-overload] method=request.method, url=urljoin(self.base_url, request.url), @@ -208,12 +226,7 @@ def make_request(self, request: HTTPRequest) -> HTTPResponse: body=body, multipart=multipart, ) - except zapros.TimeoutError as e: - raise RequestTimeoutError(str(e)) from e - except zapros.ConnectionError as e: - raise NetworkError(str(e)) from e - - content = response.read() + content = response.read() response_data: Any = None if content: @@ -246,12 +259,8 @@ def stream_make_request( ) stack = ExitStack() - try: + with translate_errors(_ERROR_MAP): response = stack.enter_context(stream_cm) - except zapros.TimeoutError as e: - raise RequestTimeoutError(str(e)) from e - except zapros.ConnectionError as e: - raise NetworkError(str(e)) from e return HTTPResponse( status_code=response.status, @@ -320,7 +329,7 @@ def _build_payload( async def make_request(self, request: HTTPRequest) -> HTTPResponse: body, form, multipart = self._build_payload(request) - try: + with translate_errors(_ERROR_MAP): response = await self._session.request( # type: ignore[call-overload] method=request.method, url=urljoin(self.base_url, request.url), @@ -330,12 +339,7 @@ async def make_request(self, request: HTTPRequest) -> HTTPResponse: body=body, multipart=multipart, ) - except zapros.TimeoutError as e: - raise RequestTimeoutError(str(e)) from e - except zapros.ConnectionError as e: - raise NetworkError(str(e)) from e - - content = await response.aread() + content = await response.aread() response_data: Any = None if content: @@ -368,12 +372,8 @@ async def stream_make_request( ) stack = AsyncExitStack() - try: + with translate_errors(_ERROR_MAP): response = await stack.enter_async_context(stream_cm) - except zapros.TimeoutError as e: - raise RequestTimeoutError(str(e)) from e - except zapros.ConnectionError as e: - raise NetworkError(str(e)) from e return HTTPResponse( status_code=response.status, diff --git a/src/unihttp/exceptions.py b/src/unihttp/exceptions.py index f986c68..6cbc53c 100644 --- a/src/unihttp/exceptions.py +++ b/src/unihttp/exceptions.py @@ -21,6 +21,10 @@ class RequestTimeoutError(UniHTTPError): """Request timed out.""" +class NonRetryableError(UniHTTPError): + """Deterministic failure (bad URL, redirect loop, ...) — retrying won't help.""" + + # Application errors (HTTP status based) class HTTPStatusError(UniHTTPError): """Raised for HTTP error responses.""" From 15e3f5eeda4cf453ff809efaba5faf92006716f2 Mon Sep 17 00:00:00 2001 From: m-xim <170838360+m-xim@users.noreply.github.com> Date: Mon, 14 Sep 2026 23:53:47 +0300 Subject: [PATCH 2/7] test: add comprehensive error handling tests for various HTTP clients --- tests/conftest.py | 29 + tests/test_clients/test_aiohttp.py | 61 +- tests/test_clients/test_base.py | 50 +- tests/test_clients/test_niquests.py | 8 +- tests/test_clients/test_urllib.py | 50 +- tests/test_clients/test_zapros.py | 42 +- tests/test_features/test_error_translation.py | 522 ++++++++++++++++++ tests/test_integration/test_streaming.py | 4 +- 8 files changed, 674 insertions(+), 92 deletions(-) create mode 100644 tests/test_features/test_error_translation.py diff --git a/tests/conftest.py b/tests/conftest.py index 89be908..21e2861 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,5 @@ +import socket +import threading from unittest.mock import Mock import pytest @@ -24,3 +26,30 @@ async def integration_server(aiohttp_server): app = await make_app() server = await aiohttp_server(app) return server + + +@pytest.fixture +def raw_server(): + """Start a one-shot TCP server that sends back one raw HTTP response. + + Returns its base URL. Nothing validates the response, so it can be broken + on purpose (e.g. a body shorter than Content-Length). + """ + + def start(status="200 OK", headers=(), body=b""): + head = "".join(f"{header}\r\n" for header in headers) + payload = f"HTTP/1.1 {status}\r\n{head}\r\n".encode() + body + srv = socket.socket() + srv.bind(("127.0.0.1", 0)) + srv.listen(1) + + def handle(): + conn, _ = srv.accept() + with conn, srv: + conn.recv(65536) + conn.sendall(payload) + + threading.Thread(target=handle, daemon=True).start() + return f"http://127.0.0.1:{srv.getsockname()[1]}" + + return start diff --git a/tests/test_clients/test_aiohttp.py b/tests/test_clients/test_aiohttp.py index 5c412a0..7123a1a 100644 --- a/tests/test_clients/test_aiohttp.py +++ b/tests/test_clients/test_aiohttp.py @@ -12,6 +12,22 @@ def mock_session(): return MagicMock(spec=aiohttp.ClientSession) +class FakeContent: + """`ClientResponse.content` whose iter_chunked yields the items; exceptions are raised.""" + + def __init__(self, *items): + self._items = items + + def iter_chunked(self, chunk_size): + async def gen(): + for item in self._items: + if isinstance(item, BaseException): + raise item + yield item + + return gen() + + @pytest.mark.asyncio async def test_aiohttp_make_request(mock_request_dumper, mock_response_loader, mock_session): client = AiohttpAsyncClient( @@ -272,18 +288,11 @@ async def test_aiohttp_raw_body(mock_request_dumper, mock_response_loader, mock_ @pytest.mark.asyncio async def test_aiohttp_stream_make_request(mock_request_dumper, mock_response_loader, mock_session): - class _FakeContent: - def iter_chunked(self, chunk_size): - async def gen(): - yield b"a" - yield b"b" - return gen() - response = MagicMock() response.status = 200 response.headers = {} response.cookies = {} - response.content = _FakeContent() + response.content = FakeContent(b"a", b"b") response.close = MagicMock() mock_session.request = AsyncMock(return_value=response) @@ -304,15 +313,8 @@ async def gen(): @pytest.mark.asyncio async def test_aiohttp_chunk_stream_closes_without_ever_reading(): - class _FakeContent: - def iter_chunked(self, chunk_size): - async def gen(): - yield b"a" - yield b"b" - return gen() - response = MagicMock() - response.content = _FakeContent() + response.content = FakeContent(b"a", b"b") response.close = MagicMock() stream = _AiohttpChunkStream(response, chunk_size=999) @@ -329,15 +331,8 @@ async def gen(): @pytest.mark.asyncio async def test_aiohttp_chunk_stream_early_break_closes_once(): - class _FakeContent: - def iter_chunked(self, chunk_size): - async def gen(): - yield b"a" - yield b"b" - return gen() - response = MagicMock() - response.content = _FakeContent() + response.content = FakeContent(b"a", b"b") response.close = MagicMock() stream = _AiohttpChunkStream(response, chunk_size=999) @@ -351,15 +346,8 @@ async def gen(): @pytest.mark.asyncio async def test_aiohttp_chunk_stream_mid_stream_connection_error_translated(): - class _FakeContent: - def iter_chunked(self, chunk_size): - async def gen(): - yield b"a" - raise aiohttp.ClientConnectionError("connection lost") - return gen() - response = MagicMock() - response.content = _FakeContent() + response.content = FakeContent(b"a", aiohttp.ClientConnectionError("connection lost")) stream = _AiohttpChunkStream(response, chunk_size=999) assert await anext(stream) == b"a" @@ -369,15 +357,8 @@ async def gen(): @pytest.mark.asyncio async def test_aiohttp_chunk_stream_mid_stream_timeout_translated(): - class _FakeContent: - def iter_chunked(self, chunk_size): - async def gen(): - yield b"a" - raise TimeoutError("timed out") - return gen() - response = MagicMock() - response.content = _FakeContent() + response.content = FakeContent(b"a", TimeoutError("timed out")) stream = _AiohttpChunkStream(response, chunk_size=999) assert await anext(stream) == b"a" diff --git a/tests/test_clients/test_base.py b/tests/test_clients/test_base.py index f361c5c..eb3f3a5 100644 --- a/tests/test_clients/test_base.py +++ b/tests/test_clients/test_base.py @@ -14,7 +14,7 @@ class SimpleMethod(BaseMethod[str]): __method__ = "GET" -class _FakeStreamMethod(StreamMethod): +class FakeStreamMethod(StreamMethod): __url__ = "/files/{id}" __method__ = "GET" @@ -61,7 +61,7 @@ async def handle(self, request, next_handler): return await next_handler(request) -class _GenChunkStream(ChunkStream): +class GenChunkStream(ChunkStream): """Test double wiring a plain generator into the ChunkStream contract.""" def __init__(self, gen, on_close): @@ -87,7 +87,7 @@ def gen(): self.closed = False self.last_request = request - return HTTPResponse(200, {}, _GenChunkStream(gen(), lambda: setattr(self, "closed", True)), {}, None) + return HTTPResponse(200, {}, GenChunkStream(gen(), lambda: setattr(self, "closed", True)), {}, None) class TestSyncClient: class MockClient(BaseSyncClient): @@ -165,7 +165,7 @@ def test_call_method_stream_full_consumption(self, mock_request_dumper, mock_res mock_request_dumper.dump.return_value = {"path": {"id": "1"}} chunks = [] - with client.call_method_stream(_FakeStreamMethod()).data as stream: + with client.call_method_stream(FakeStreamMethod()).data as stream: for chunk in stream: chunks.append(chunk) @@ -176,7 +176,7 @@ def test_call_method_stream_early_break_still_closes(self, mock_request_dumper, client = StreamClient("http://base", mock_request_dumper, mock_response_loader) mock_request_dumper.dump.return_value = {"path": {"id": "1"}} - with client.call_method_stream(_FakeStreamMethod()).data as stream: + with client.call_method_stream(FakeStreamMethod()).data as stream: for _chunk in stream: break @@ -185,18 +185,18 @@ def test_call_method_stream_early_break_still_closes(self, mock_request_dumper, def test_call_method_stream_status_not_ok_calls_on_error(self, mock_request_dumper, mock_response_loader): calls = [] - class _StreamMethodWithOnError(StreamMethod): + class StreamMethodWithOnError(StreamMethod): __url__ = "/files/{id}" __method__ = "GET" def on_error(self, response): calls.append(response.status_code) - class _ErrorClient(StreamClient): + class ErrorClient(StreamClient): def stream_make_request(self, request, chunk_size=65536): self.closed = False return HTTPResponse( - 404, {}, _GenChunkStream(iter(()), lambda: setattr(self, "closed", True)), {}, None + 404, {}, GenChunkStream(iter(()), lambda: setattr(self, "closed", True)), {}, None ) def handle_error(self, response, method): @@ -206,11 +206,11 @@ def handle_error(self, response, method): # started. raise RuntimeError(f"HTTP {response.status_code}") - client = _ErrorClient("http://base", mock_request_dumper, mock_response_loader) + client = ErrorClient("http://base", mock_request_dumper, mock_response_loader) mock_request_dumper.dump.return_value = {"path": {"id": "1"}} with pytest.raises(RuntimeError): - with client.call_method_stream(_StreamMethodWithOnError()).data as stream: + with client.call_method_stream(StreamMethodWithOnError()).data as stream: list(stream) assert calls == [404] @@ -222,12 +222,12 @@ def test_middleware_layers(self, mock_request_dumper, mock_response_loader): order = [] seen = [] - class _Client(self.MockClient): + class FakeClient(self.MockClient): def make_request(self, request): seen.append(request.header.get("Auth")) return HTTPResponse(200, {}, {}, {}, None) - client = _Client( + client = FakeClient( "http://base", mock_request_dumper, mock_response_loader, middleware=[Tag(order, "client")], ) @@ -251,7 +251,7 @@ def test_middleware_layers_stream(self, mock_request_dumper, mock_response_loade mock_request_dumper.dump.return_value = {"path": {"id": "1"}} with client.call_method_stream( - _FakeStreamMethod(), middleware=[Tag(order, "A")] + FakeStreamMethod(), middleware=[Tag(order, "A")] ).data as stream: list(stream) @@ -304,7 +304,7 @@ async def handle(self, request, next_handler): assert order == ["mw1_req", "mw2_req", "mw2_resp", "mw1_resp"] - class _AsyncGenChunkStream(AsyncChunkStream): + class AsyncGenChunkStream(AsyncChunkStream): """Test double wiring a plain async generator into the AsyncChunkStream contract.""" def __init__(self, gen, on_close): @@ -330,7 +330,7 @@ async def gen(): self.closed = False self.last_request = request return HTTPResponse( - 200, {}, TestAsyncClient._AsyncGenChunkStream(gen(), lambda: setattr(self, "closed", True)), {}, None + 200, {}, TestAsyncClient.AsyncGenChunkStream(gen(), lambda: setattr(self, "closed", True)), {}, None ) async def test_call_method_stream_full_consumption(self, mock_request_dumper, mock_response_loader): @@ -338,7 +338,7 @@ async def test_call_method_stream_full_consumption(self, mock_request_dumper, mo mock_request_dumper.dump.return_value = {"path": {"id": "1"}} chunks = [] - async with (await client.call_method_stream(_FakeStreamMethod())).data as stream: + async with (await client.call_method_stream(FakeStreamMethod())).data as stream: async for chunk in stream: chunks.append(chunk) @@ -349,7 +349,7 @@ async def test_call_method_stream_early_break_still_closes(self, mock_request_du client = self.StreamClient("http://base", mock_request_dumper, mock_response_loader) mock_request_dumper.dump.return_value = {"path": {"id": "1"}} - async with (await client.call_method_stream(_FakeStreamMethod())).data as stream: + async with (await client.call_method_stream(FakeStreamMethod())).data as stream: async for _chunk in stream: break @@ -358,7 +358,7 @@ async def test_call_method_stream_early_break_still_closes(self, mock_request_du async def test_call_method_stream_status_not_ok_calls_on_error(self, mock_request_dumper, mock_response_loader): calls = [] - class _StreamMethodWithOnError(StreamMethod): + class StreamMethodWithOnError(StreamMethod): __url__ = "/files/{id}" __method__ = "GET" @@ -369,12 +369,12 @@ async def empty_gen(): return yield # pragma: no cover - makes this an async generator - class _ErrorClient(self.StreamClient): + class ErrorClient(self.StreamClient): async def stream_make_request(self, request, chunk_size=65536): self.closed = False return HTTPResponse( 404, {}, - TestAsyncClient._AsyncGenChunkStream(empty_gen(), lambda: setattr(self, "closed", True)), + TestAsyncClient.AsyncGenChunkStream(empty_gen(), lambda: setattr(self, "closed", True)), {}, None, ) @@ -385,11 +385,11 @@ def handle_error(self, response, method): # iterator having started. raise RuntimeError(f"HTTP {response.status_code}") - client = _ErrorClient("http://base", mock_request_dumper, mock_response_loader) + client = ErrorClient("http://base", mock_request_dumper, mock_response_loader) mock_request_dumper.dump.return_value = {"path": {"id": "1"}} with pytest.raises(RuntimeError): - async with (await client.call_method_stream(_StreamMethodWithOnError())).data as stream: + async with (await client.call_method_stream(StreamMethodWithOnError())).data as stream: async for _chunk in stream: pass @@ -403,7 +403,7 @@ async def test_middleware_layers(self, mock_request_dumper, mock_response_loader hooks = [] seen = [] - class _Client(self.MockClient): + class FakeClient(self.MockClient): async def make_request(self, request): seen.append(request.header.get("Auth")) return HTTPResponse(200, {}, {}, {}, None) @@ -411,7 +411,7 @@ async def make_request(self, request): def validate_response(self, response, method): hooks.append("validate") - client = _Client( + client = FakeClient( "http://base", mock_request_dumper, mock_response_loader, middleware=[AsyncTag(order, "client")], ) @@ -440,7 +440,7 @@ async def test_middleware_layers_stream(self, mock_request_dumper, mock_response mock_request_dumper.dump.return_value = {"path": {"id": "1"}} async with (await client.call_method_stream( - _FakeStreamMethod(), middleware=[AsyncTag(order, "A")] + FakeStreamMethod(), middleware=[AsyncTag(order, "A")] )).data as stream: async for _chunk in stream: pass diff --git a/tests/test_clients/test_niquests.py b/tests/test_clients/test_niquests.py index 6e15f47..1d02781 100644 --- a/tests/test_clients/test_niquests.py +++ b/tests/test_clients/test_niquests.py @@ -7,7 +7,7 @@ from unihttp.clients.base import BaseSyncClient, BaseAsyncClient from unihttp.clients.niquests import NiquestsSyncClient, NiquestsAsyncClient, _NiquestsChunkStream, \ _NiquestsAsyncChunkStream -from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.exceptions import NetworkError, RequestTimeoutError, UniHTTPError from unihttp.http import HTTPRequest from unihttp.serialize import RequestDumper, ResponseLoader @@ -180,8 +180,9 @@ def test_generic_request_exception(self, sync_client: BaseSyncClient, mocker): request = HTTPRequest( url="/path", method="GET", header={}, path={}, query={}, body=None, file={}, form=None ) - with pytest.raises(NetworkError, match="Generic Error"): + with pytest.raises(UniHTTPError, match="Generic Error") as info: client.make_request(request) + assert type(info.value) is UniHTTPError def test_raw_body(self, sync_client: BaseSyncClient, mocker): mock_response = Mock(status_code=200, headers={}, cookies={}, content=b"{}") @@ -402,8 +403,9 @@ async def test_generic_request_exception(self, async_client: BaseAsyncClient, mo request = HTTPRequest( url="/path", method="GET", header={}, path={}, query={}, body=None, file={}, form=None ) - with pytest.raises(NetworkError, match="Generic Error"): + with pytest.raises(UniHTTPError, match="Generic Error") as info: await client.make_request(request) + assert type(info.value) is UniHTTPError @pytest.mark.asyncio async def test_stream_make_request(self, async_client: BaseAsyncClient, mocker): diff --git a/tests/test_clients/test_urllib.py b/tests/test_clients/test_urllib.py index 2b67991..6d91968 100644 --- a/tests/test_clients/test_urllib.py +++ b/tests/test_clients/test_urllib.py @@ -32,6 +32,9 @@ def __init__(self, status=200, headers=None, body=b"", cookies=None): def read(self): return self._body + def close(self): + pass + @pytest.fixture def mock_opener(): @@ -90,7 +93,10 @@ def test_urllib_context_manager(mock_request_dumper, mock_response_loader, mock_ def test_urllib_network_error(mock_request_dumper, mock_response_loader, mock_opener): client = make_client(mock_request_dumper, mock_response_loader, mock_opener) - mock_opener.open.side_effect = urllib.error.URLError("Connection refused") + # A string reason would be a NonRetryableError. + mock_opener.open.side_effect = urllib.error.URLError( + ConnectionRefusedError("Connection refused") + ) request = HTTPRequest("/url", "GET", {}, {}, {}, {}, {}, {}) @@ -326,6 +332,7 @@ def test_urllib_stream_make_request(mock_request_dumper, mock_response_loader): fake_response.headers.items.return_value = [] fake_response.headers.get_all.return_value = [] fake_response.read.side_effect = [b"a", b"b", b""] + fake_response.length = 0 opener = MagicMock() opener.open.return_value = fake_response @@ -394,3 +401,44 @@ def test_urllib_chunk_stream_mid_stream_timeout_translated(): assert next(stream) == b"a" with pytest.raises(RequestTimeoutError): next(stream) + + +def read_stream(base_url, method="GET"): + client = UrllibSyncClient(base_url, MagicMock(), MagicMock(), timeout=5) + request = HTTPRequest("/", method, {}, {}, {}, {}, {}, {}) + with client.stream_make_request(request, chunk_size=4).data as stream: + return b"".join(stream) + + +def test_urllib_real_stream_raises_on_truncated_body(raw_server): + base_url = raw_server(headers=["Content-Length: 100"], body=b"x" * 10) + + with pytest.raises(NetworkError): + read_stream(base_url) + + +def test_urllib_real_stream_raises_on_truncated_error_body(raw_server): + # A 4xx response comes back as urllib.error.HTTPError, not HTTPResponse. + base_url = raw_server("404 Not Found", headers=["Content-Length: 100"], body=b"x" * 10) + + with pytest.raises(NetworkError): + read_stream(base_url) + + +def test_urllib_real_stream_reads_full_body(raw_server): + base_url = raw_server(headers=["Content-Length: 10"], body=b"x" * 10) + + assert read_stream(base_url) == b"x" * 10 + + +def test_urllib_real_stream_reads_body_without_content_length(raw_server): + base_url = raw_server(headers=["Connection: close"], body=b"x" * 10) + + assert read_stream(base_url) == b"x" * 10 + + +def test_urllib_real_stream_head_is_not_truncation(raw_server): + # HEAD carries Content-Length but never a body. + base_url = raw_server(headers=["Content-Length: 100"]) + + assert read_stream(base_url, method="HEAD") == b"" diff --git a/tests/test_clients/test_zapros.py b/tests/test_clients/test_zapros.py index e79ecad..3f8fd99 100644 --- a/tests/test_clients/test_zapros.py +++ b/tests/test_clients/test_zapros.py @@ -19,7 +19,7 @@ from unihttp.http import HTTPRequest, UploadFile -class _FakeStreamCM: +class FakeStreamCM: """Real `__enter__`/`__exit__` methods, not `Mock`-assigned ones. `ExitStack.enter_context` looks up `type(cm).__exit__` (to match `with` @@ -40,8 +40,8 @@ def __exit__(self, *exc_info): self.exit_calls.append(exc_info) -class _FakeAsyncStreamCM: - """Async counterpart of `_FakeStreamCM` — see its docstring.""" +class FakeAsyncStreamCM: + """Async counterpart of `FakeStreamCM` — see its docstring.""" def __init__(self, response): self._response = response @@ -123,7 +123,7 @@ def test_empty_mapping(self): assert _stringify_pairs({}) == [] -def _mock_response(*, status: int = 200, content: bytes = b"{}") -> Mock: +def make_response(*, status: int = 200, content: bytes = b"{}") -> Mock: response = Mock(spec=zapros.Response) response.status = status response.headers = {} @@ -156,7 +156,7 @@ async def async_client(mock_request_dumper, mock_response_loader) -> AsyncGenera class TestZaprosSyncClient: def test_make_request(self, sync_client: BaseSyncClient, mocker): - mock_response = _mock_response(content=b'{"key": "value"}') + mock_response = make_response(content=b'{"key": "value"}') mock_request = mocker.patch("zapros.Client.request", return_value=mock_response) client = cast(ZaprosSyncClient, sync_client) @@ -186,7 +186,7 @@ def test_make_request(self, sync_client: BaseSyncClient, mocker): ) def test_request_with_body(self, sync_client: BaseSyncClient, mocker): - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -202,7 +202,7 @@ def test_request_with_body(self, sync_client: BaseSyncClient, mocker): assert request.header["Content-Type"] == "application/json" def test_request_with_form(self, sync_client: BaseSyncClient, mocker): - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -218,7 +218,7 @@ def test_request_with_form(self, sync_client: BaseSyncClient, mocker): def test_form_coerces_non_string_values(self, sync_client: BaseSyncClient, mocker): """Form values get the same coercion as query (bool/int/None/list).""" - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -237,7 +237,7 @@ def test_form_coerces_non_string_values(self, sync_client: BaseSyncClient, mocke ] def test_query_coerces_non_string_values(self, sync_client: BaseSyncClient, mocker): - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -257,7 +257,7 @@ def test_query_coerces_non_string_values(self, sync_client: BaseSyncClient, mock ] def test_request_with_files_builds_multipart(self, sync_client: BaseSyncClient, mocker): - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -308,7 +308,7 @@ def test_request_with_files_builds_multipart(self, sync_client: BaseSyncClient, def test_file_part_variants(self, sync_client: BaseSyncClient, mocker): """Cover BinaryIO read-path and raw-bytes value path in `_add_file_part`.""" - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -330,7 +330,7 @@ def test_file_part_variants(self, sync_client: BaseSyncClient, mocker): def test_non_json_response_kept_as_bytes(self, sync_client: BaseSyncClient, mocker): mocker.patch( "zapros.Client.request", - return_value=_mock_response(content=b"not json"), + return_value=make_response(content=b"not json"), ) client = cast(ZaprosSyncClient, sync_client) @@ -344,7 +344,7 @@ def test_non_json_response_kept_as_bytes(self, sync_client: BaseSyncClient, mock def test_empty_body_with_file_does_not_error(self, sync_client: BaseSyncClient, mocker): """Dumper defaults `body` to `{}` — that must not preempt file uploads.""" - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -400,7 +400,7 @@ def test_init_with_session(self, mock_request_dumper, mock_response_loader): client.close() def test_raw_body(self, sync_client: BaseSyncClient, mocker): - mock_request = mocker.patch("zapros.Client.request", return_value=_mock_response()) + mock_request = mocker.patch("zapros.Client.request", return_value=make_response()) client = cast(ZaprosSyncClient, sync_client) request = HTTPRequest( @@ -417,7 +417,7 @@ def test_stream_make_request(self, sync_client: BaseSyncClient, mocker): response.headers = {} response.iter_bytes.return_value = iter([b"a", b"b"]) - stream_cm = _FakeStreamCM(response) + stream_cm = FakeStreamCM(response) mocker.patch("zapros.Client.stream", return_value=stream_cm) client = cast(ZaprosSyncClient, sync_client) @@ -494,7 +494,7 @@ def gen(): class TestZaprosAsyncClient: @pytest.mark.asyncio async def test_make_request(self, async_client: BaseAsyncClient, mocker): - mock_response = _mock_response(content=b'{"key": "value"}') + mock_response = make_response(content=b'{"key": "value"}') mock_request = mocker.patch( "zapros.AsyncClient.request", new_callable=AsyncMock, @@ -527,7 +527,7 @@ async def test_request_with_form(self, async_client: BaseAsyncClient, mocker): mock_request = mocker.patch( "zapros.AsyncClient.request", new_callable=AsyncMock, - return_value=_mock_response(), + return_value=make_response(), ) client = cast(ZaprosAsyncClient, async_client) @@ -544,7 +544,7 @@ async def test_request_with_files_builds_multipart(self, async_client: BaseAsync mock_request = mocker.patch( "zapros.AsyncClient.request", new_callable=AsyncMock, - return_value=_mock_response(), + return_value=make_response(), ) client = cast(ZaprosAsyncClient, async_client) @@ -573,7 +573,7 @@ async def test_non_json_response_kept_as_bytes(self, async_client: BaseAsyncClie mocker.patch( "zapros.AsyncClient.request", new_callable=AsyncMock, - return_value=_mock_response(content=b"not json"), + return_value=make_response(content=b"not json"), ) client = cast(ZaprosAsyncClient, async_client) @@ -618,7 +618,7 @@ async def test_network_error(self, async_client: BaseAsyncClient, mocker): @pytest.mark.asyncio async def test_raw_body(self, async_client: BaseAsyncClient, mocker): mock_request = mocker.patch( - "zapros.AsyncClient.request", new_callable=AsyncMock, return_value=_mock_response() + "zapros.AsyncClient.request", new_callable=AsyncMock, return_value=make_response() ) client = cast(ZaprosAsyncClient, async_client) @@ -659,7 +659,7 @@ async def gen(): response.headers = {} response.async_iter_bytes.return_value = gen() - stream_cm = _FakeAsyncStreamCM(response) + stream_cm = FakeAsyncStreamCM(response) mocker.patch("zapros.AsyncClient.stream", return_value=stream_cm) client = cast(ZaprosAsyncClient, async_client) diff --git a/tests/test_features/test_error_translation.py b/tests/test_features/test_error_translation.py new file mode 100644 index 0000000..74ac1e0 --- /dev/null +++ b/tests/test_features/test_error_translation.py @@ -0,0 +1,522 @@ +import http.client +import urllib.error +from contextlib import AsyncExitStack, ExitStack, contextmanager +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import aiohttp +import httpx +import httpx2 +import niquests +import pytest +import requests +import zapros +from unihttp.clients.aiohttp import AiohttpAsyncClient, _AiohttpChunkStream +from unihttp.clients.httpx import ( + HTTPXAsyncClient, + HTTPXSyncClient, + _HTTPXAsyncChunkStream, + _HTTPXChunkStream, +) +from unihttp.clients.httpx2 import ( + HTTPX2AsyncClient, + HTTPX2SyncClient, + _HTTPX2AsyncChunkStream, + _HTTPX2ChunkStream, +) +from unihttp.clients.niquests import ( + NiquestsAsyncClient, + NiquestsSyncClient, + _NiquestsAsyncChunkStream, + _NiquestsChunkStream, +) +from unihttp.clients.requests import RequestsSyncClient, _RequestsChunkStream +from unihttp.clients.urllib import UrllibSyncClient, _UrllibChunkStream +from unihttp.clients.zapros import ( + ZaprosAsyncClient, + ZaprosSyncClient, + _ZaprosAsyncChunkStream, + _ZaprosChunkStream, +) +from unihttp.exceptions import ( + NetworkError, + NonRetryableError, + RequestTimeoutError, + UniHTTPError, +) +from unihttp.http.request import HTTPRequest + + +def http_request(url="/x"): + return HTTPRequest( + url=url, method="GET", header={}, path={}, query={}, body={}, file={}, form={} + ) + + +def make_client(cls, base_url="http://test", **kwargs): + return cls( + base_url=base_url, request_dumper=MagicMock(), response_loader=MagicMock(), **kwargs + ) + + +def case_id(value): + if isinstance(value, BaseException): + return type(value).__name__ + return getattr(value, "__name__", None) + + +@contextmanager +def raises_exactly(expected, cause=None): + # pytest.raises(UniHTTPError) would also pass for its subclass NetworkError. + with pytest.raises(expected) as info: + yield + assert type(info.value) is expected + if cause is not None: + assert info.value.__cause__ is cause + + +def one_chunk_then(exc): + yield b"a" + raise exc + + +async def one_async_chunk_then(exc): + yield b"a" + raise exc + + +def assert_second_chunk_raises(stream, exc, expected): + assert next(stream) == b"a" + with raises_exactly(expected, cause=exc): + next(stream) + + +async def assert_second_async_chunk_raises(stream, exc, expected): + assert await anext(stream) == b"a" + with raises_exactly(expected, cause=exc): + await anext(stream) + + +TRUNCATED = {"headers": ["Content-Length: 100"], "body": b"x" * 10} + + +@pytest.fixture( + params=[ + SimpleNamespace( + exceptions=requests.exceptions, + client=RequestsSyncClient, + stream=_RequestsChunkStream, + ), + SimpleNamespace( + exceptions=niquests.exceptions, + client=NiquestsSyncClient, + stream=_NiquestsChunkStream, + ), + ], + ids=["requests", "niquests"], +) +def requests_like(request): + return request.param + + +REQUESTS_CASES = pytest.mark.parametrize( + ("name", "expected"), + [ + ("ConnectTimeout", RequestTimeoutError), # also a ConnectionError + ("ReadTimeout", RequestTimeoutError), + ("ConnectionError", NetworkError), + ("ProxyError", NetworkError), + ("SSLError", NetworkError), + ("ChunkedEncodingError", NetworkError), + ("RetryError", NetworkError), + ("MissingSchema", NonRetryableError), + ("InvalidSchema", NonRetryableError), + ("InvalidURL", NonRetryableError), + ("InvalidHeader", NonRetryableError), + ("InvalidJSONError", NonRetryableError), + ("URLRequired", NonRetryableError), + ("TooManyRedirects", NonRetryableError), + ("ContentDecodingError", NonRetryableError), + ("UnrewindableBodyError", NonRetryableError), + # Status, misuse and unknown errors: plain UniHTTPError, never retried. + ("HTTPError", UniHTTPError), + ("StreamConsumedError", UniHTTPError), + ("RequestException", UniHTTPError), + ], + ids=case_id, +) + + +@REQUESTS_CASES +def test_requests_like_errors(requests_like, name, expected): + exc = getattr(requests_like.exceptions, name)("x") + session = MagicMock() + session.request.side_effect = exc + + with raises_exactly(expected, cause=exc): + make_client(requests_like.client, session=session).make_request(http_request()) + + +@REQUESTS_CASES +async def test_niquests_async_errors(name, expected): + exc = getattr(niquests.exceptions, name)("x") + session = MagicMock() + session.request = AsyncMock(side_effect=exc) + + with raises_exactly(expected, cause=exc): + await make_client(NiquestsAsyncClient, session=session).make_request(http_request()) + + +def test_niquests_multiplexing_error(): + exc = niquests.exceptions.MultiplexingError("x") + session = MagicMock() + session.request.side_effect = exc + + with raises_exactly(NetworkError, cause=exc): + make_client(NiquestsSyncClient, session=session).make_request(http_request()) + + +@pytest.mark.parametrize( + ("name", "expected"), + [("ChunkedEncodingError", NetworkError), ("ContentDecodingError", NonRetryableError)], + ids=case_id, +) +def test_requests_like_stream_errors(requests_like, name, expected): + exc = getattr(requests_like.exceptions, name)("x") + response = MagicMock() + response.iter_content.return_value = one_chunk_then(exc) + + stream = requests_like.stream(response, chunk_size=5) + assert_second_chunk_raises(stream, exc, expected) + + +async def test_niquests_async_stream_error(): + exc = niquests.exceptions.ChunkedEncodingError("x") + stream = _NiquestsAsyncChunkStream(MagicMock(), one_async_chunk_then(exc)) + + await assert_second_async_chunk_raises(stream, exc, NetworkError) + + +@pytest.fixture( + params=[ + SimpleNamespace( + module=httpx, + client=HTTPXSyncClient, + async_client=HTTPXAsyncClient, + stream=_HTTPXChunkStream, + async_stream=_HTTPXAsyncChunkStream, + ), + SimpleNamespace( + module=httpx2, + client=HTTPX2SyncClient, + async_client=HTTPX2AsyncClient, + stream=_HTTPX2ChunkStream, + async_stream=_HTTPX2AsyncChunkStream, + ), + ], + ids=["httpx", "httpx2"], +) +def httpx_like(request): + return request.param + + +HTTPX_CASES = pytest.mark.parametrize( + ("name", "expected"), + [ + ("ConnectTimeout", RequestTimeoutError), # also a RequestError + ("ReadTimeout", RequestTimeoutError), + ("ConnectError", NetworkError), + ("ReadError", NetworkError), + ("RemoteProtocolError", NetworkError), # server hung up + ("ProxyError", NetworkError), + ("InvalidURL", NonRetryableError), + ("UnsupportedProtocol", NonRetryableError), + ("LocalProtocolError", NonRetryableError), # our malformed request + ("TooManyRedirects", NonRetryableError), + ("DecodingError", NonRetryableError), + ("HTTPStatusError", UniHTTPError), + ], + ids=case_id, +) + +HTTPX_STREAM_CASES = pytest.mark.parametrize( + ("name", "expected"), + [("RemoteProtocolError", NetworkError), ("DecodingError", NonRetryableError)], + ids=case_id, +) + + +def make_httpx_error(module, name): + if name == "HTTPStatusError": + return module.HTTPStatusError("x", request=MagicMock(), response=MagicMock()) + return getattr(module, name)("x") + + +@HTTPX_CASES +def test_httpx_like_errors(httpx_like, name, expected): + exc = make_httpx_error(httpx_like.module, name) + session = MagicMock() + session.send.side_effect = exc + + with raises_exactly(expected, cause=exc): + make_client(httpx_like.client, session=session).make_request(http_request()) + + +@HTTPX_CASES +async def test_httpx_like_async_errors(httpx_like, name, expected): + exc = make_httpx_error(httpx_like.module, name) + session = MagicMock() + session.send = AsyncMock(side_effect=exc) + + with raises_exactly(expected, cause=exc): + await make_client(httpx_like.async_client, session=session).make_request(http_request()) + + +# A real session: a null byte makes build_request (not send) raise InvalidURL. +def test_httpx_like_real_invalid_url(httpx_like): + with httpx_like.module.Client() as session, raises_exactly(NonRetryableError): + make_client(httpx_like.client, session=session).make_request(http_request(url="a\x00")) + + +async def test_httpx_like_async_real_invalid_url(httpx_like): + async with httpx_like.module.AsyncClient() as session: + client = make_client(httpx_like.async_client, session=session) + with raises_exactly(NonRetryableError): + await client.make_request(http_request(url="a\x00")) + + +@HTTPX_STREAM_CASES +def test_httpx_like_stream_errors(httpx_like, name, expected): + exc = getattr(httpx_like.module, name)("x") + response = MagicMock() + response.iter_bytes.return_value = one_chunk_then(exc) + + stream = httpx_like.stream(response, chunk_size=5) + assert_second_chunk_raises(stream, exc, expected) + + +@HTTPX_STREAM_CASES +async def test_httpx_like_async_stream_errors(httpx_like, name, expected): + exc = getattr(httpx_like.module, name)("x") + response = MagicMock() + response.aiter_bytes.return_value = one_async_chunk_then(exc) + + stream = httpx_like.async_stream(response, chunk_size=5) + await assert_second_async_chunk_raises(stream, exc, expected) + + +ZAPROS_CASES = pytest.mark.parametrize( + ("exc", "expected"), + [ + (zapros.ConnectTimeoutError("x"), RequestTimeoutError), + (zapros.ConnectionError("x"), NetworkError), + (zapros.SSLError("x"), NetworkError), + (zapros.ReadError("x"), NetworkError), + (zapros.WriteError("x"), NetworkError), + (zapros.DecodingError("x"), NonRetryableError), + (zapros.TooManyRedirectsError("x"), NonRetryableError), + (zapros.UnhandledRequestError("x"), NonRetryableError), # cassette miss + (zapros.StatusCodeError(MagicMock()), UniHTTPError), + ], + ids=case_id, +) + + +@ZAPROS_CASES +def test_zapros_errors(exc, expected): + session = MagicMock() + session.request.side_effect = exc + + with raises_exactly(expected, cause=exc): + make_client(ZaprosSyncClient, session=session).make_request(http_request()) + + +@ZAPROS_CASES +async def test_zapros_async_errors(exc, expected): + session = MagicMock() + session.request = AsyncMock(side_effect=exc) + + with raises_exactly(expected, cause=exc): + await make_client(ZaprosAsyncClient, session=session).make_request(http_request()) + + +def test_zapros_body_read_error(): + exc = zapros.ReadError("x") + session = MagicMock() + session.request.return_value.read.side_effect = exc + + with raises_exactly(NetworkError, cause=exc): + make_client(ZaprosSyncClient, session=session).make_request(http_request()) + + +async def test_zapros_async_body_read_error(): + exc = zapros.ReadError("x") + session = MagicMock() + session.request = AsyncMock(return_value=MagicMock(aread=AsyncMock(side_effect=exc))) + + with raises_exactly(NetworkError, cause=exc): + await make_client(ZaprosAsyncClient, session=session).make_request(http_request()) + + +def test_zapros_stream_open_error(): + exc = zapros.ReadError("x") + session = MagicMock() + session.stream.return_value.__enter__.side_effect = exc + + with raises_exactly(NetworkError, cause=exc): + make_client(ZaprosSyncClient, session=session).stream_make_request(http_request()) + + +async def test_zapros_async_stream_open_error(): + exc = zapros.ReadError("x") + session = MagicMock() + session.stream.return_value.__aenter__.side_effect = exc + + with raises_exactly(NetworkError, cause=exc): + await make_client(ZaprosAsyncClient, session=session).stream_make_request(http_request()) + + +def test_zapros_stream_error(): + exc = zapros.DecodingError("x") + response = MagicMock() + response.iter_bytes.return_value = one_chunk_then(exc) + + stream = _ZaprosChunkStream(response, chunk_size=5, stack=ExitStack()) + assert_second_chunk_raises(stream, exc, NonRetryableError) + + +async def test_zapros_async_stream_error(): + exc = zapros.ReadError("x") + response = MagicMock() + response.async_iter_bytes.return_value = one_async_chunk_then(exc) + + stream = _ZaprosAsyncChunkStream(response, chunk_size=5, stack=AsyncExitStack()) + await assert_second_async_chunk_raises(stream, exc, NetworkError) + + +# Real zapros: it lets h11 errors and URL ValueErrors through unwrapped. +def test_zapros_real_truncated_body(raw_server): + with make_client(ZaprosSyncClient, base_url=raw_server(**TRUNCATED)) as client: + with raises_exactly(NetworkError): + client.make_request(http_request()) + + +def test_zapros_real_truncated_stream(raw_server): + with make_client(ZaprosSyncClient, base_url=raw_server(**TRUNCATED)) as client: + with raises_exactly(NetworkError), client.stream_make_request(http_request()).data as stream: + b"".join(stream) + + +async def test_zapros_async_real_truncated_body(raw_server): + async with make_client(ZaprosAsyncClient, base_url=raw_server(**TRUNCATED)) as client: + with raises_exactly(NetworkError): + await client.make_request(http_request()) + + +def test_zapros_real_invalid_header(raw_server): + request = http_request() + request.header["X Y"] = "v" + + with make_client(ZaprosSyncClient, base_url=raw_server()) as client: + with raises_exactly(NonRetryableError): + client.make_request(request) + + +@pytest.mark.parametrize("base_url", ["gopher://x/", "http://exa mple.com/"]) +def test_zapros_real_invalid_url(base_url): + with make_client(ZaprosSyncClient, base_url=base_url) as client: + with raises_exactly(NonRetryableError): + client.make_request(http_request()) + +@pytest.mark.parametrize( + ("exc", "expected"), + [ + # Also ClientConnectionErrors: the timeout must win. + (aiohttp.ServerTimeoutError("x"), RequestTimeoutError), + (aiohttp.ConnectionTimeoutError("x"), RequestTimeoutError), + (aiohttp.SocketTimeoutError("x"), RequestTimeoutError), + (TimeoutError("x"), RequestTimeoutError), + (aiohttp.ClientConnectionError("x"), NetworkError), + (aiohttp.ClientPayloadError("x"), NetworkError), + (aiohttp.ClientHttpProxyError(MagicMock(), ()), NetworkError), + # Also a ValueError: the network entry must win. + (aiohttp.ClientConnectorCertificateError(MagicMock(), Exception("x")), NetworkError), + (aiohttp.TooManyRedirects(MagicMock(), ()), NonRetryableError), + (aiohttp.InvalidUrlClientError("http://x"), NonRetryableError), + (aiohttp.NonHttpUrlClientError("ftp://x"), NonRetryableError), + (ValueError("x"), NonRetryableError), + (aiohttp.ClientResponseError(MagicMock(), (), status=404), UniHTTPError), + ], + ids=case_id, +) +async def test_aiohttp_errors(exc, expected): + session = MagicMock() + session.request = AsyncMock(side_effect=exc) + + with raises_exactly(expected, cause=exc): + await make_client(AiohttpAsyncClient, session=session).make_request(http_request()) + + +async def test_aiohttp_real_invalid_header(raw_server): + request = http_request() + request.header["X"] = "a\r\nb" + + async with make_client(AiohttpAsyncClient, base_url=raw_server()) as client: + with raises_exactly(NonRetryableError): + await client.make_request(request) + + +async def test_aiohttp_stream_error(): + exc = aiohttp.ClientPayloadError("x") + response = MagicMock() + response.content.iter_chunked.return_value = one_async_chunk_then(exc) + + stream = _AiohttpChunkStream(response, chunk_size=5) + await assert_second_async_chunk_raises(stream, exc, NetworkError) + + +@pytest.mark.parametrize( + ("exc", "expected"), + [ + (urllib.error.URLError(TimeoutError("x")), RequestTimeoutError), + (urllib.error.URLError(ConnectionRefusedError("x")), NetworkError), + (urllib.error.URLError("unknown url type: ftp"), NonRetryableError), + # getresponse() raises these without wrapping them in URLError. + (TimeoutError("x"), RequestTimeoutError), + (http.client.RemoteDisconnected("x"), NetworkError), + (http.client.BadStatusLine("x"), NetworkError), + (http.client.InvalidURL("x"), NonRetryableError), + ], + ids=lambda v: repr(v) if isinstance(v, BaseException) else case_id(v), +) +def test_urllib_errors(exc, expected): + opener = MagicMock() + opener.open.side_effect = exc + + with raises_exactly(expected): + make_client(UrllibSyncClient, opener=opener).make_request(http_request()) + + +def test_urllib_malformed_url(): + # An empty base_url leaves the URL relative, which urllib.request.Request rejects. + with raises_exactly(NonRetryableError): + make_client(UrllibSyncClient, base_url="", opener=MagicMock()).make_request(http_request()) + + +def test_urllib_stream_error(): + exc = http.client.IncompleteRead(b"") + response = MagicMock() + response.read.side_effect = [b"a", exc] + + assert_second_chunk_raises(_UrllibChunkStream(response, chunk_size=5), exc, NetworkError) + + +def test_urllib_read_interrupted_closes_response(): + response = MagicMock() + response.read.side_effect = KeyboardInterrupt + opener = MagicMock() + opener.open.return_value = response + + with pytest.raises(KeyboardInterrupt): + make_client(UrllibSyncClient, opener=opener).make_request(http_request()) + response.close.assert_called_once() diff --git a/tests/test_integration/test_streaming.py b/tests/test_integration/test_streaming.py index 353fd0a..6d9a3e1 100644 --- a/tests/test_integration/test_streaming.py +++ b/tests/test_integration/test_streaming.py @@ -50,7 +50,7 @@ def make_client(client_cls, base_url, dumper, loader): return client_cls(base_url=base_url, request_dumper=dumper, response_loader=loader) -class _StreamHandler(BaseHTTPRequestHandler): +class StreamHandler(BaseHTTPRequestHandler): """Mirrors tests/server.py's /stream/{total_bytes}: writes `total_bytes` in 4096-byte pieces, misaligned with CHUNK_SIZE on purpose.""" @@ -76,7 +76,7 @@ def log_message(self, format, *args): @pytest.fixture def threaded_server(): - server = ThreadingHTTPServer(("127.0.0.1", 0), _StreamHandler) + server = ThreadingHTTPServer(("127.0.0.1", 0), StreamHandler) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() From 83ef33b2a693d5a09d809e5dc97a62657f05d6e3 Mon Sep 17 00:00:00 2001 From: m-xim <170838360+m-xim@users.noreply.github.com> Date: Tue, 15 Sep 2026 00:03:45 +0300 Subject: [PATCH 3/7] docs: update error handling documentation for HTTP exceptions and retries --- .../unihttp-client/references/openapi-to-unihttp.md | 4 +++- site/guides/errors.md | 13 +++++++++++++ site/guides/streaming.md | 4 ++++ site/recipes/retries.md | 3 ++- site/reference/middleware.md | 2 +- 5 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.agents/skills/unihttp-client/references/openapi-to-unihttp.md b/.agents/skills/unihttp-client/references/openapi-to-unihttp.md index 8c5598f..3a02bec 100644 --- a/.agents/skills/unihttp-client/references/openapi-to-unihttp.md +++ b/.agents/skills/unihttp-client/references/openapi-to-unihttp.md @@ -143,7 +143,9 @@ Prefer a single auth middleware (`AsyncMiddleware` for async clients, - If the API has a structured error body, model it as a dataclass and raise a typed exception carrying it. - Reuse the built-in exceptions where they fit: - `unihttp.exceptions.{ClientError, ServerError, HTTPStatusError, NetworkError, RequestTimeoutError}`. + `unihttp.exceptions.{ClientError, ServerError, HTTPStatusError, NetworkError, RequestTimeoutError, NonRetryableError, UniHTTPError}`. +- Retry only `NetworkError` and `RequestTimeoutError`; `NonRetryableError` fails + the same way on every attempt. ## Pagination diff --git a/site/guides/errors.md b/site/guides/errors.md index 28063a4..2a74fec 100644 --- a/site/guides/errors.md +++ b/site/guides/errors.md @@ -112,12 +112,25 @@ The error types describe different stages: | Failure | What to handle | | --- | --- | | Network failure or timeout | `NetworkError` or `RequestTimeoutError`; do not assume an HTTP response exists. | +| Request that cannot succeed as sent, for example an unsupported URL scheme | `NonRetryableError`; fix the request instead of retrying. | +| Any other failure inside the HTTP backend | Plain `UniHTTPError`. | | Unsuccessful HTTP status | Exceptions configured by your mapper or error hooks. | | API error inside a successful HTTP response | Your own exception from `validate_response`, as below. | | Body does not match the declared result | The configured serializer's loading exception; this is not an HTTP status error. | Avoid treating all of these as “user not found” or retrying every exception. +Every [client backend](../integrations/backends.md)'s exceptions are translated +into these types, so you never need to catch backend exceptions. All inherit from +`UniHTTPError`; the original is kept as `__cause__`. Rare edge cases can map +differently between backends. + +Handle statuses with unihttp, not with the backend. If the backend session raises +on error statuses itself (for example `aiohttp.ClientSession(raise_for_status=True)`), +hooks and middleware never see the response, and you get a plain `UniHTTPError`. +Use an [error mapper](#map-statuses-across-endpoints) or override +`client.handle_error` to call `response.raise_for_status()` instead. + ## Validate an error inside HTTP 200 Some APIs return `{"ok": false, "error": "Account disabled"}` with status `200`. diff --git a/site/guides/streaming.md b/site/guides/streaming.md index 4369131..805763f 100644 --- a/site/guides/streaming.md +++ b/site/guides/streaming.md @@ -85,6 +85,10 @@ For the helpers above, catch around the entire `download_checksum(...)` call - `HTTPStatusError` covers rejected statuses, including the `ClientError` and `ServerError` subclasses raised by this method. - `NetworkError` and `RequestTimeoutError` can occur while opening or reading. + A body cut short by the server raises `NetworkError`; the stream does not + just end early. +- `NonRetryableError` means the request cannot succeed as sent, for example an + unsupported URL scheme. - Exceptions from your own consumer also propagate; the stream context still closes the response. diff --git a/site/recipes/retries.md b/site/recipes/retries.md index 5ce4b40..3f2d60e 100644 --- a/site/recipes/retries.md +++ b/site/recipes/retries.md @@ -79,7 +79,8 @@ The default is three retries, or four attempts total. By default, status retries cover `500`, `502`, `503`, and `504`. Pass a non-empty `status_codes` list to choose another set. Exceptions are not retried unless included in `exceptions`; the example opts into `NetworkError` and -`RequestTimeoutError`. +`RequestTimeoutError`. Do not add `NonRetryableError`, which fails the same way +on every attempt, or the base `UniHTTPError`, which also covers it. The delay before retry number `attempt + 1` is `backoff * 2**attempt`, starting at `attempt = 0`. Here the base delays are 0.5 and 1 second. With `jitter=True`, diff --git a/site/reference/middleware.md b/site/reference/middleware.md index 314c26d..edba7c9 100644 --- a/site/reference/middleware.md +++ b/site/reference/middleware.md @@ -7,7 +7,7 @@ description: Middleware handlers, retry and status-mapping configuration, loggin Sync `Handler` and async `AsyncHandler` are callable aliases exported by `unihttp.middlewares`. Match the middleware variant to the client. See [middleware ordering](../guides/middleware.md) and [retry behavior](../recipes/retries.md). -`HTTPStatusError` exposes `response` and `status_code`. Status errors require explicit handling; default response hooks do not raise automatically. Network exception normalization depends on the transport. +`HTTPStatusError` exposes `response` and `status_code`. Status errors require explicit handling; default response hooks do not raise automatically. Every client backend translates its own exceptions into `NetworkError`, `RequestTimeoutError`, `NonRetryableError`, or plain `UniHTTPError`, keeping the original as `__cause__`. ::: unihttp.middlewares.base.Middleware From 57834c8faae6bd3b5a0bb07660dcd850746953fc Mon Sep 17 00:00:00 2001 From: m-xim <170838360+m-xim@users.noreply.github.com> Date: Tue, 15 Sep 2026 00:23:39 +0300 Subject: [PATCH 4/7] fix: enhance error mapping for various HTTP clients and improve test coverage for invalid base URLs --- src/unihttp/clients/httpx.py | 5 +- src/unihttp/clients/httpx2.py | 5 +- src/unihttp/clients/niquests.py | 2 + src/unihttp/clients/requests.py | 2 + src/unihttp/clients/urllib.py | 5 +- tests/test_features/test_error_translation.py | 47 +++++++++++++++++++ 6 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/unihttp/clients/httpx.py b/src/unihttp/clients/httpx.py index b4943a4..1de5aed 100644 --- a/src/unihttp/clients/httpx.py +++ b/src/unihttp/clients/httpx.py @@ -24,7 +24,9 @@ # Timeout first: TimeoutException is also a RequestError. _ERROR_MAP: ErrorMap = { RequestTimeoutError: httpx.TimeoutException, + # ValueError: a base_url that urljoin rejects. NonRetryableError: ( + ValueError, httpx.InvalidURL, httpx.UnsupportedProtocol, httpx.LocalProtocolError, @@ -32,7 +34,8 @@ httpx.DecodingError, ), NetworkError: httpx.RequestError, - UniHTTPError: httpx.HTTPError, + # StreamError and CookieConflict are misuse errors outside HTTPError. + UniHTTPError: (httpx.HTTPError, httpx.StreamError, httpx.CookieConflict), } diff --git a/src/unihttp/clients/httpx2.py b/src/unihttp/clients/httpx2.py index 93093c3..6c6255b 100644 --- a/src/unihttp/clients/httpx2.py +++ b/src/unihttp/clients/httpx2.py @@ -24,7 +24,9 @@ # Timeout first: TimeoutException is also a RequestError. _ERROR_MAP: ErrorMap = { RequestTimeoutError: httpx2.TimeoutException, + # ValueError: base_url that urljoin rejects. NonRetryableError: ( + ValueError, httpx2.InvalidURL, httpx2.UnsupportedProtocol, httpx2.LocalProtocolError, @@ -32,7 +34,8 @@ httpx2.DecodingError, ), NetworkError: httpx2.RequestError, - UniHTTPError: httpx2.HTTPError, + # StreamError and CookieConflict are misuse errors outside HTTPError. + UniHTTPError: (httpx2.HTTPError, httpx2.StreamError, httpx2.CookieConflict), } diff --git a/src/unihttp/clients/niquests.py b/src/unihttp/clients/niquests.py index e92b5a4..363360e 100644 --- a/src/unihttp/clients/niquests.py +++ b/src/unihttp/clients/niquests.py @@ -24,7 +24,9 @@ # Timeout first: ConnectTimeout is also a ConnectionError. _ERROR_MAP: ErrorMap = { RequestTimeoutError: niquests.exceptions.Timeout, + # ValueError: a base_url that urljoin rejects. NonRetryableError: ( + ValueError, niquests.exceptions.MissingSchema, niquests.exceptions.InvalidSchema, niquests.exceptions.InvalidURL, diff --git a/src/unihttp/clients/requests.py b/src/unihttp/clients/requests.py index 212af03..b0400d7 100644 --- a/src/unihttp/clients/requests.py +++ b/src/unihttp/clients/requests.py @@ -21,7 +21,9 @@ # Timeout first: ConnectTimeout is also a ConnectionError. _ERROR_MAP: ErrorMap = { RequestTimeoutError: requests.exceptions.Timeout, + # ValueError: a base_url that urljoin rejects. NonRetryableError: ( + ValueError, requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema, requests.exceptions.InvalidURL, diff --git a/src/unihttp/clients/urllib.py b/src/unihttp/clients/urllib.py index aa2738a..f7ea41f 100644 --- a/src/unihttp/clients/urllib.py +++ b/src/unihttp/clients/urllib.py @@ -15,6 +15,7 @@ NetworkError, NonRetryableError, RequestTimeoutError, + UniHTTPError, ) from unihttp.http import UploadFile from unihttp.http.request import HTTPRequest @@ -28,9 +29,11 @@ # Timeout first: TimeoutError is also an OSError. _ERROR_MAP: ErrorMap = { RequestTimeoutError: TimeoutError, + # Before ValueError: a certificate error is both an OSError and a ValueError. + NetworkError: (OSError, http.client.IncompleteRead, http.client.BadStatusLine), # ValueError: malformed URL or header, raised before any I/O. NonRetryableError: (ValueError, http.client.InvalidURL), - NetworkError: (OSError, http.client.HTTPException), + UniHTTPError: http.client.HTTPException, } diff --git a/tests/test_features/test_error_translation.py b/tests/test_features/test_error_translation.py index 74ac1e0..5230373 100644 --- a/tests/test_features/test_error_translation.py +++ b/tests/test_features/test_error_translation.py @@ -1,4 +1,5 @@ import http.client +import ssl import urllib.error from contextlib import AsyncExitStack, ExitStack, contextmanager from types import SimpleNamespace @@ -235,6 +236,8 @@ def httpx_like(request): ("TooManyRedirects", NonRetryableError), ("DecodingError", NonRetryableError), ("HTTPStatusError", UniHTTPError), + ("StreamConsumed", UniHTTPError), + ("CookieConflict", UniHTTPError), ], ids=case_id, ) @@ -249,6 +252,8 @@ def httpx_like(request): def make_httpx_error(module, name): if name == "HTTPStatusError": return module.HTTPStatusError("x", request=MagicMock(), response=MagicMock()) + if name == "StreamConsumed": + return module.StreamConsumed() return getattr(module, name)("x") @@ -481,11 +486,14 @@ async def test_aiohttp_stream_error(): (urllib.error.URLError(TimeoutError("x")), RequestTimeoutError), (urllib.error.URLError(ConnectionRefusedError("x")), NetworkError), (urllib.error.URLError("unknown url type: ftp"), NonRetryableError), + # Also a ValueError: the network entry must win. + (urllib.error.URLError(ssl.SSLCertVerificationError(1, "x")), NetworkError), # getresponse() raises these without wrapping them in URLError. (TimeoutError("x"), RequestTimeoutError), (http.client.RemoteDisconnected("x"), NetworkError), (http.client.BadStatusLine("x"), NetworkError), (http.client.InvalidURL("x"), NonRetryableError), + (http.client.LineTooLong("x"), UniHTTPError), ], ids=lambda v: repr(v) if isinstance(v, BaseException) else case_id(v), ) @@ -520,3 +528,42 @@ def test_urllib_read_interrupted_closes_response(): with pytest.raises(KeyboardInterrupt): make_client(UrllibSyncClient, opener=opener).make_request(http_request()) response.close.assert_called_once() + + +# urljoin rejects this base_url before any backend code runs. +BAD_BASE_URL = "http://[::1/" + + +@pytest.mark.parametrize( + "client_cls", + [ + RequestsSyncClient, + NiquestsSyncClient, + HTTPXSyncClient, + HTTPX2SyncClient, + ZaprosSyncClient, + UrllibSyncClient, + ], + ids=case_id, +) +def test_invalid_base_url(client_cls): + with make_client(client_cls, base_url=BAD_BASE_URL) as client: + with raises_exactly(NonRetryableError): + client.make_request(http_request()) + + +@pytest.mark.parametrize( + "client_cls", + [ + NiquestsAsyncClient, + HTTPXAsyncClient, + HTTPX2AsyncClient, + ZaprosAsyncClient, + AiohttpAsyncClient, + ], + ids=case_id, +) +async def test_async_invalid_base_url(client_cls): + async with make_client(client_cls, base_url=BAD_BASE_URL) as client: + with raises_exactly(NonRetryableError): + await client.make_request(http_request()) From fe3c87eb34483105c3a8ebf4e0f3b220080b636b Mon Sep 17 00:00:00 2001 From: m-xim <170838360+m-xim@users.noreply.github.com> Date: Tue, 15 Sep 2026 16:12:30 +0300 Subject: [PATCH 5/7] fix: update zapros dependency version to 0.12.0 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fca7777..9f5d73e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,7 @@ httpx2 = ["httpx2>=2.0.0"] requests = ["requests>=2.32.0"] aiohttp = ["aiohttp>=3.10.0"] niquests = ["niquests>=3.17.0"] -zapros = ["zapros>=0.11.0"] +zapros = ["zapros>=0.12.0"] pydantic = ["pydantic>=2.0.0"] adaptix = ["adaptix>=3.0.0b12"] msgspec = ["msgspec>=0.18.0"] From e038089e179607368be5decca9373556033a7fc8 Mon Sep 17 00:00:00 2001 From: m-xim <170838360+m-xim@users.noreply.github.com> Date: Tue, 15 Sep 2026 16:17:16 +0300 Subject: [PATCH 6/7] test: add error handling tests for stream_make_request method --- src/unihttp/clients/zapros.py | 38 +++++++++---------- tests/test_features/test_error_translation.py | 4 ++ 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/src/unihttp/clients/zapros.py b/src/unihttp/clients/zapros.py index 06522a7..b2de12d 100644 --- a/src/unihttp/clients/zapros.py +++ b/src/unihttp/clients/zapros.py @@ -248,18 +248,17 @@ def stream_make_request( ) -> HTTPResponse[ChunkStream]: body, form, multipart = self._build_payload(request) - stream_cm = self._session.stream( # type: ignore[call-overload] - method=request.method, - url=urljoin(self.base_url, request.url), - headers=request.header, - params=_stringify_pairs(request.query), - form=form, - body=body, - multipart=multipart, - ) - stack = ExitStack() with translate_errors(_ERROR_MAP): + stream_cm = self._session.stream( # type: ignore[call-overload] + method=request.method, + url=urljoin(self.base_url, request.url), + headers=request.header, + params=_stringify_pairs(request.query), + form=form, + body=body, + multipart=multipart, + ) response = stack.enter_context(stream_cm) return HTTPResponse( @@ -361,18 +360,17 @@ async def stream_make_request( ) -> HTTPResponse[AsyncChunkStream]: body, form, multipart = self._build_payload(request) - stream_cm = self._session.stream( # type: ignore[call-overload] - method=request.method, - url=urljoin(self.base_url, request.url), - headers=request.header, - params=_stringify_pairs(request.query), - form=form, - body=body, - multipart=multipart, - ) - stack = AsyncExitStack() with translate_errors(_ERROR_MAP): + stream_cm = self._session.stream( # type: ignore[call-overload] + method=request.method, + url=urljoin(self.base_url, request.url), + headers=request.header, + params=_stringify_pairs(request.query), + form=form, + body=body, + multipart=multipart, + ) response = await stack.enter_async_context(stream_cm) return HTTPResponse( diff --git a/tests/test_features/test_error_translation.py b/tests/test_features/test_error_translation.py index 5230373..00c169b 100644 --- a/tests/test_features/test_error_translation.py +++ b/tests/test_features/test_error_translation.py @@ -550,6 +550,8 @@ def test_invalid_base_url(client_cls): with make_client(client_cls, base_url=BAD_BASE_URL) as client: with raises_exactly(NonRetryableError): client.make_request(http_request()) + with raises_exactly(NonRetryableError): + client.stream_make_request(http_request()) @pytest.mark.parametrize( @@ -567,3 +569,5 @@ async def test_async_invalid_base_url(client_cls): async with make_client(client_cls, base_url=BAD_BASE_URL) as client: with raises_exactly(NonRetryableError): await client.make_request(http_request()) + with raises_exactly(NonRetryableError): + await client.stream_make_request(http_request()) From 88ca854a3d725045444a4a45e801d64764149d78 Mon Sep 17 00:00:00 2001 From: m-xim <170838360+m-xim@users.noreply.github.com> Date: Tue, 15 Sep 2026 16:17:51 +0300 Subject: [PATCH 7/7] docs(errors): improve clarity on backend exception handling --- site/guides/errors.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/site/guides/errors.md b/site/guides/errors.md index 2a74fec..02834a8 100644 --- a/site/guides/errors.md +++ b/site/guides/errors.md @@ -120,10 +120,12 @@ The error types describe different stages: Avoid treating all of these as “user not found” or retrying every exception. -Every [client backend](../integrations/backends.md)'s exceptions are translated -into these types, so you never need to catch backend exceptions. All inherit from -`UniHTTPError`; the original is kept as `__cause__`. Rare edge cases can map -differently between backends. +Every [client backend](../integrations/backends.md) translates failures of +sending a request and reading its response into these types, so you do not need +to catch backend exceptions for them. All inherit from `UniHTTPError`; the +original is kept as `__cause__`. Rare edge cases can map differently between +backends. Misuse is not translated: a request on a closed client raises the +backend's own error, for example `RuntimeError`. Handle statuses with unihttp, not with the backend. If the backend session raises on error statuses itself (for example `aiohttp.ClientSession(raise_for_status=True)`),