From d5ed41e9292c459a7441ec65e7f285e10ea66fdd Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:43:53 -0800 Subject: [PATCH 1/3] fix: raise APIError for every error response body _raise_for_status raised something other than APIError for some error bodies that a gateway or proxy can send: - JSON that is not an object (null, a number, a boolean, a string, a list): AttributeError from .get. - Bytes that are not valid UTF-8, such as 0xff: UnicodeDecodeError from response.json(), which was not caught. - A body declared as charset=utf-16 without a byte order mark: UnicodeError from response.text. Now every error response raises the APIError subclass for its status. The message is the message, else detail, field of a JSON object; for any other body it is the body text, or the status phrase when the body is empty. body is the decoded text, as before; a body that cannot be decoded with its charset is decoded as UTF-8 with replacement characters. --- src/fishaudio/core/client_wrapper.py | 38 ++++++-- tests/unit/test_error_body.py | 141 +++++++++++++++++++++++++++ 2 files changed, 171 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_error_body.py diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index c95784e..c960df7 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -4,7 +4,6 @@ import platform import re import sys -from json import JSONDecodeError from typing import Any, Optional, Union import httpx @@ -37,18 +36,41 @@ def _api_error(status: int, message: str, body: Optional[str] = None) -> APIErro return APIError(status, message, body) +def _response_text(response: httpx.Response) -> str: + """The body as text, even when it cannot be decoded as its charset says. + + httpx replaces bytes that are invalid in the charset, but Python's UTF-16 and + UTF-32 decoders still raise when a body declared as ``charset=utf-16`` has no + byte order mark. Such a body is decoded as UTF-8 with replacement instead. + """ + try: + return response.text + except UnicodeError: + return response.content.decode("utf-8", errors="replace") + + def _raise_for_status(response: httpx.Response) -> None: - """Raise appropriate exception based on status code.""" + """Raise the APIError subclass for the response's status. + + The message is the ``message`` or else ``detail`` field of a JSON object body. + For any other body (not JSON, not valid text, or JSON that is not an object, + such as null, a number, a boolean, a string or a list) it is the body text, + or the status phrase when the body is empty. + """ status = response.status_code + text = _response_text(response) - # Try to extract error message from response try: error_data = response.json() - message = error_data.get("message") or error_data.get("detail") or response.text - except JSONDecodeError: - message = response.text or httpx.codes.get_reason_phrase(status) - - raise _api_error(status, message, response.text) + except ValueError: # not JSON, or bytes that are not valid text + error_data = None + message = None + if isinstance(error_data, dict): + message = error_data.get("message") or error_data.get("detail") + + raise _api_error( + status, message or text or httpx.codes.get_reason_phrase(status), text + ) PRODUCT = f"fish-audio-python/{__version__}" diff --git a/tests/unit/test_error_body.py b/tests/unit/test_error_body.py new file mode 100644 index 0000000..799dbd7 --- /dev/null +++ b/tests/unit/test_error_body.py @@ -0,0 +1,141 @@ +"""Every error response raises the APIError subclass for its status. + +The body may be anything a gateway or proxy sends: not an object, not JSON, not +valid text. +""" + +from typing import Optional + +import httpx +import pytest + +from fishaudio.core import AsyncClientWrapper, ClientWrapper +from fishaudio.exceptions import APIError, ServerError + +UTF16_NO_BOM = '{"message": "bad"}'.encode("utf-16-be") + +# (body, content type, expected message, expected body text) +BODIES = [ + pytest.param(b"null", "application/json", "null", "null", id="null"), + pytest.param(b"[]", "application/json", "[]", "[]", id="empty-list"), + pytest.param( + b'["bad", "request"]', + "application/json", + '["bad", "request"]', + '["bad", "request"]', + id="list", + ), + pytest.param( + b'"quota exceeded"', + "application/json", + '"quota exceeded"', + '"quota exceeded"', + id="string", + ), + pytest.param(b"42", "application/json", "42", "42", id="number"), + pytest.param(b"true", "application/json", "true", "true", id="boolean"), + # Not valid UTF-8: httpx replaces the byte in the text. + pytest.param(b"\xff", "application/json", "\ufffd", "\ufffd", id="invalid-utf8"), + pytest.param( + b"\x80not utf-8", + "text/plain", + "\ufffdnot utf-8", + "\ufffdnot utf-8", + id="invalid-utf8-text", + ), + # Declared UTF-16 without a byte order mark: decoding the text raises + # UnicodeError, while the JSON itself still parses. + pytest.param( + UTF16_NO_BOM, + "application/json; charset=utf-16", + "bad", + UTF16_NO_BOM.decode("utf-8", errors="replace"), + id="utf16-without-bom", + ), + # Empty body: the status phrase. + pytest.param(b"", "text/plain", None, "", id="empty"), +] + +# (JSON object body, expected message) +OBJECTS = [ + ({"message": "bad voice"}, "bad voice"), + ({"detail": "bad voice"}, "bad voice"), + ({"message": "from message", "detail": "from detail"}, "from message"), + ({"message": "", "detail": "from detail"}, "from detail"), + ({"status": 400}, '{"status":400}'), +] + + +def _transport(status: int, body: bytes, content_type: str) -> httpx.MockTransport: + return httpx.MockTransport( + lambda request: httpx.Response( + status, content=body, headers={"content-type": content_type} + ) + ) + + +def _sync_error(status: int, body: bytes, content_type: str, stream: bool) -> APIError: + client = ClientWrapper( + api_key="test-key", + httpx_client=httpx.Client( + base_url="https://api.example", + transport=_transport(status, body, content_type), + ), + ) + with pytest.raises(APIError) as exc: + client.request("GET", "/v1/anything", stream=stream) + return exc.value + + +async def _async_error( + status: int, body: bytes, content_type: str, stream: bool +) -> APIError: + client = AsyncClientWrapper( + api_key="test-key", + httpx_client=httpx.AsyncClient( + base_url="https://api.example", + transport=_transport(status, body, content_type), + ), + ) + with pytest.raises(APIError) as exc: + await client.request("GET", "/v1/anything", stream=stream) + return exc.value + + +def _check( + error: APIError, + error_class: type, + status: int, + message: Optional[str], + body_text: str, +) -> None: + assert type(error) is error_class + assert error.status == status + assert error.message == ( + message if message is not None else httpx.codes.get_reason_phrase(status) + ) + assert error.body == body_text + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("body,content_type,message,body_text", BODIES) +def test_sync_any_body_raises_api_error(body, content_type, message, body_text, stream): + error = _sync_error(400, body, content_type, stream) + _check(error, APIError, 400, message, body_text) + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("body,content_type,message,body_text", BODIES) +async def test_async_any_body_raises_api_error( + body, content_type, message, body_text, stream +): + error = await _async_error(503, body, content_type, stream) + _check(error, ServerError, 503, message, body_text) + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("obj,message", OBJECTS) +def test_object_body_message_then_detail(obj, message, stream): + body = httpx.Response(400, json=obj).content + error = _sync_error(400, body, "application/json", stream) + _check(error, APIError, 400, message, body.decode()) From a4e6b3a39f51df7c6f8196ea9998c042974aa201 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:50:23 -0800 Subject: [PATCH 2/3] fix: read an error response's body behind one boundary that cannot raise Reviews kept finding one more exception type that escaped _raise_for_status: RecursionError for JSON nested deeper than the parser's limit, and TypeError or AssertionError for a charset that names a codec that is not a text encoding (rot_13, base64_codec, zlib_codec, hex_codec, ...). Decoding and parsing the body now happen in one function that never raises: any failure (Exception) means "no parsed JSON" and a best-effort text, UTF-8 with replacement characters as the last resort, or empty text if the body cannot be read at all. _raise_for_status raises the APIError subclass for the status whatever the body is. How the message is chosen is unchanged. Tests: the reviewers' cases (nested JSON, non-text codecs, BOM-less UTF-16 and UTF-32 with non-ASCII text), an unread body, and a seeded test that sends 300 random bodies with random charsets (every stdlib codec name, an unknown name, none) through each of the four request paths and accepts only APIError. --- src/fishaudio/core/client_wrapper.py | 43 ++++++------ tests/unit/test_error_body.py | 98 ++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+), 20 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index c960df7..6db5d73 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -36,37 +36,40 @@ def _api_error(status: int, message: str, body: Optional[str] = None) -> APIErro return APIError(status, message, body) -def _response_text(response: httpx.Response) -> str: - """The body as text, even when it cannot be decoded as its charset says. +def _read_error_body(response: httpx.Response) -> tuple[Any, str]: + """The parsed JSON and the text of an error response's body. Never raises. - httpx replaces bytes that are invalid in the charset, but Python's UTF-16 and - UTF-32 decoders still raise when a body declared as ``charset=utf-16`` has no - byte order mark. Such a body is decoded as UTF-8 with replacement instead. + The text is decoded with the response's charset; if that fails in any way, + the body is decoded as UTF-8 with replacement characters. The JSON is None + when the body cannot be parsed for any reason. """ try: - return response.text - except UnicodeError: - return response.content.decode("utf-8", errors="replace") + text = response.text + except Exception: + try: + text = response.content.decode("utf-8", errors="replace") + except Exception: + text = "" + try: + data = response.json() + except Exception: + data = None + return data, text def _raise_for_status(response: httpx.Response) -> None: - """Raise the APIError subclass for the response's status. + """Raise the APIError subclass for the response's status, whatever the body is. - The message is the ``message`` or else ``detail`` field of a JSON object body. - For any other body (not JSON, not valid text, or JSON that is not an object, - such as null, a number, a boolean, a string or a list) it is the body text, - or the status phrase when the body is empty. + If the body is a JSON object with a truthy ``message`` field, that is the + message; otherwise its truthy ``detail`` field. In every other case the + message is the body text, or the status phrase when the text is empty. """ status = response.status_code - text = _response_text(response) + data, text = _read_error_body(response) - try: - error_data = response.json() - except ValueError: # not JSON, or bytes that are not valid text - error_data = None message = None - if isinstance(error_data, dict): - message = error_data.get("message") or error_data.get("detail") + if isinstance(data, dict): + message = data.get("message") or data.get("detail") raise _api_error( status, message or text or httpx.codes.get_reason_phrase(status), text diff --git a/tests/unit/test_error_body.py b/tests/unit/test_error_body.py index 799dbd7..cf1ab42 100644 --- a/tests/unit/test_error_body.py +++ b/tests/unit/test_error_body.py @@ -4,15 +4,23 @@ valid text. """ +import encodings +import encodings.aliases +import pkgutil +import random from typing import Optional import httpx import pytest from fishaudio.core import AsyncClientWrapper, ClientWrapper +from fishaudio.core.client_wrapper import _raise_for_status from fishaudio.exceptions import APIError, ServerError UTF16_NO_BOM = '{"message": "bad"}'.encode("utf-16-be") +CAFE_UTF16_NO_BOM = "caf\u00e9".encode("utf-16-be") +CAFE_UTF32_NO_BOM = "caf\u00e9".encode("utf-32-be") +NESTED = b"[" * 2000 + b"0" + b"]" * 2000 # (body, content type, expected message, expected body text) BODIES = [ @@ -52,6 +60,35 @@ UTF16_NO_BOM.decode("utf-8", errors="replace"), id="utf16-without-bom", ), + # Declared UTF-16 without a byte order mark, with bytes that are not valid + # UTF-8 either: the fallback must replace them, not fail. + pytest.param( + CAFE_UTF16_NO_BOM, + "text/plain; charset=utf-16", + CAFE_UTF16_NO_BOM.decode("utf-8", errors="replace"), + CAFE_UTF16_NO_BOM.decode("utf-8", errors="replace"), + id="utf16-without-bom-non-ascii", + ), + pytest.param( + CAFE_UTF32_NO_BOM, + "text/plain; charset=utf-32", + CAFE_UTF32_NO_BOM.decode("utf-8", errors="replace"), + CAFE_UTF32_NO_BOM.decode("utf-8", errors="replace"), + id="utf32-without-bom", + ), + # Codecs that are not text encodings: decoding raises TypeError or + # AssertionError inside httpx. + pytest.param(b"bad", "text/plain; charset=rot_13", "bad", "bad", id="rot13"), + pytest.param(b"bad", "text/plain; charset=base64_codec", "bad", "bad", id="base64"), + pytest.param(b"bad", "text/plain; charset=zlib_codec", "bad", "bad", id="zlib"), + pytest.param(b"bad", "text/plain; charset=hex_codec", "bad", "bad", id="hex"), + # JSON nested deeper than the parser's recursion limit: RecursionError. + pytest.param( + NESTED, "application/json", NESTED.decode(), NESTED.decode(), id="nested" + ), + pytest.param( + b"[" * 2000, "application/json", "[" * 2000, "[" * 2000, id="nested-open" + ), # Empty body: the status phrase. pytest.param(b"", "text/plain", None, "", id="empty"), ] @@ -139,3 +176,64 @@ def test_object_body_message_then_detail(obj, message, stream): body = httpx.Response(400, json=obj).content error = _sync_error(400, body, "application/json", stream) _check(error, APIError, 400, message, body.decode()) + + +# Every stdlib codec name, a name that is no codec, and no charset at all. +CHARSETS = sorted( + set(encodings.aliases.aliases.values()) + | {m.name for m in pkgutil.iter_modules(encodings.__path__)} - {"aliases"} +) + ["no-such-codec", None] + + +def _random_bodies(seed: int, count: int) -> list: + rng = random.Random(seed) + makers = [ + lambda: bytes(rng.randrange(256) for _ in range(rng.randrange(65))), + lambda: b"[" * rng.randrange(5000) + b"0" + b"]" * rng.randrange(5000), + lambda: ( + rng.choice([b"null", b"true", b"1e999", b'"x"', b"{}", b"[]"]) + + bytes(rng.randrange(256) for _ in range(rng.randrange(4))) + ), + lambda: rng.choice(["caf\u00e9", "\u4f60\u597d", "\U0001f41f"]).encode( + rng.choice(["utf-8", "utf-16-le", "utf-16-be", "utf-32-be", "latin-1"]), + errors="replace", + ), + ] + return [ + (rng.choice(makers)(), rng.choice(CHARSETS), rng.choice([400, 404, 429, 503])) + for _ in range(count) + ] + + +def _content_type(charset: Optional[str]) -> str: + return "application/json" if charset is None else f"text/plain; charset={charset}" + + +# Random bytes decoded as unicode_escape make the stdlib warn about escapes. +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +@pytest.mark.parametrize("stream", [False, True]) +def test_sync_random_bodies_only_raise_api_error(stream): + for body, charset, status in _random_bodies(seed=196, count=300): + error = _sync_error(status, body, _content_type(charset), stream) + assert error.status == status + assert isinstance(error.body, str) + + +# Random bytes decoded as unicode_escape make the stdlib warn about escapes. +@pytest.mark.filterwarnings("ignore::DeprecationWarning") +@pytest.mark.parametrize("stream", [False, True]) +async def test_async_random_bodies_only_raise_api_error(stream): + for body, charset, status in _random_bodies(seed=197, count=300): + error = await _async_error(status, body, _content_type(charset), stream) + assert error.status == status + assert isinstance(error.body, str) + + +def test_unread_body_still_raises_api_error(): + # A streamed body that was never read: even response.content raises. + response = httpx.Response( + 502, stream=httpx.ByteStream(b"never read"), request=httpx.Request("GET", "/") + ) + with pytest.raises(ServerError) as exc: + _raise_for_status(response) + _check(exc.value, ServerError, 502, None, "") From 1bdb12e988285ee55232ceab81caba7b6ca03186 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:13:25 -0800 Subject: [PATCH 3/3] docs: say exactly which error responses raise APIError The docstrings and the test module said every error response raises APIError and that reading the body never raises. Errors while the body is being received (a transport error, a body that fails to decompress) are raised by httpx before the SDK sees the response, and BaseExceptions such as cancellation propagate on purpose. Say only that. --- src/fishaudio/core/client_wrapper.py | 14 +++++++++----- tests/unit/test_error_body.py | 8 +++++--- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 6db5d73..4bda311 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -37,11 +37,12 @@ def _api_error(status: int, message: str, body: Optional[str] = None) -> APIErro def _read_error_body(response: httpx.Response) -> tuple[Any, str]: - """The parsed JSON and the text of an error response's body. Never raises. + """The parsed JSON and the text of an error response's body. - The text is decoded with the response's charset; if that fails in any way, - the body is decoded as UTF-8 with replacement characters. The JSON is None - when the body cannot be parsed for any reason. + The text is decoded with the response's charset; if that raises an + exception, the body is decoded as UTF-8 with replacement characters, or is + empty if it was never read. The JSON is None if parsing raises an exception. + BaseExceptions such as KeyboardInterrupt and cancellation propagate. """ try: text = response.text @@ -58,7 +59,10 @@ def _read_error_body(response: httpx.Response) -> tuple[Any, str]: def _raise_for_status(response: httpx.Response) -> None: - """Raise the APIError subclass for the response's status, whatever the body is. + """Raise the APIError subclass for the response's status, whatever the body contains. + + Errors while the body is being received, such as a transport error or a body + that fails to decompress, happen before this is called and propagate. If the body is a JSON object with a truthy ``message`` field, that is the message; otherwise its truthy ``detail`` field. In every other case the diff --git a/tests/unit/test_error_body.py b/tests/unit/test_error_body.py index cf1ab42..240c344 100644 --- a/tests/unit/test_error_body.py +++ b/tests/unit/test_error_body.py @@ -1,7 +1,9 @@ -"""Every error response raises the APIError subclass for its status. +"""An error response raises the APIError subclass for its status, whatever its +body contains: not an object, not JSON, not valid text in its charset. -The body may be anything a gateway or proxy sends: not an object, not JSON, not -valid text. +Not covered: errors while the body is being received (a transport error, a body +that fails to decompress), which httpx raises before the SDK sees the response, +and cancellation. """ import encodings