Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 38 additions & 9 deletions src/fishaudio/core/client_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import platform
import re
import sys
from json import JSONDecodeError
from typing import Any, Optional, Union

import httpx
Expand Down Expand Up @@ -37,18 +36,48 @@ def _api_error(status: int, message: str, body: Optional[str] = None) -> APIErro
return APIError(status, message, body)


def _read_error_body(response: httpx.Response) -> tuple[Any, str]:
"""The parsed JSON and the text of an error response's body.

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
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 appropriate exception based on status code."""
"""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
message is the body text, or the status phrase when the text is empty.
"""
status = response.status_code
data, text = _read_error_body(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)
message = None
if isinstance(data, dict):
message = data.get("message") or data.get("detail")

raise _api_error(status, message, response.text)
raise _api_error(
status, message or text or httpx.codes.get_reason_phrase(status), text
)


PRODUCT = f"fish-audio-python/{__version__}"
Expand Down
241 changes: 241 additions & 0 deletions tests/unit/test_error_body.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
"""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.

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
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 = [
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",
),
# 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"),
]

# (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())


# 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, "")