Repository navigation
feat(errors): expose response headers on APIError #188
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a42cbcf
feat(errors): expose response headers on APIError
lumpinif d04492e
test: every error class carries the response headers
lumpinif ae2fa1a
docs: make the error-headers README example a complete block
lumpinif 1ff8cff
Merge branch 'main' into feat/error-response-headers
lumpinif c9f7b91
Merge remote-tracking branch 'origin/main' into feat/error-response-h…
lumpinif 4be5e34
fix(errors): accept header values outside ASCII on a hand-built APIEr…
lumpinif fe95738
Merge origin/main into feat/error-response-headers
lumpinif ff3115c
Merge remote-tracking branch 'origin/main' into feat/error-response-h…
lumpinif File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| """An APIError carries the headers of the error response. | ||
|
|
||
| The tests run the real client against a local HTTP server, and a refused | ||
| WebSocket handshake against the scripted server in realtime_server.py. | ||
| """ | ||
|
|
||
| import contextlib | ||
| import threading | ||
| from http.server import BaseHTTPRequestHandler, HTTPServer | ||
|
|
||
| import httpx | ||
| import pytest | ||
| from httpx_ws import WebSocketUpgradeError | ||
|
|
||
| from fishaudio import APIError, AsyncFishAudio, AuthenticationError, FishAudio | ||
| from fishaudio.core.client_wrapper import _raise_for_status | ||
| from fishaudio.exceptions import ( | ||
| NotFoundError, | ||
| PermissionError, | ||
| RateLimitError, | ||
| ServerError, | ||
| ) | ||
|
|
||
| from .realtime_server import RealtimeServer | ||
|
|
||
|
|
||
| class _Refuse(BaseHTTPRequestHandler): | ||
| """401 with the API's diagnostic headers on /v1, a bare 404 elsewhere.""" | ||
|
|
||
| def _respond(self): | ||
| self.rfile.read(int(self.headers.get("content-length", 0))) | ||
| if self.path.startswith("/v1/"): | ||
| body = b'{"status":401,"message":"Invalid Token"}' | ||
| self.send_response(401) | ||
| self.send_header("x-fish-trace-id", "trace-123") | ||
| self.send_header("x-fish-error-code", "invalid_api_key") | ||
| else: | ||
| body = b'{"status":404,"message":"Not found"}' | ||
| self.send_response(404) | ||
| self.send_header("x-detail", "café") | ||
| self.send_header("content-type", "application/json") | ||
| self.send_header("content-length", str(len(body))) | ||
| self.end_headers() | ||
| self.wfile.write(body) | ||
|
|
||
| do_GET = do_POST = _respond | ||
|
|
||
| def log_message(self, *args): | ||
| pass | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def refusing_server(): | ||
| server = HTTPServer(("127.0.0.1", 0), _Refuse) | ||
| thread = threading.Thread(target=server.serve_forever, daemon=True) | ||
| thread.start() | ||
| try: | ||
| yield f"http://127.0.0.1:{server.server_port}" | ||
| finally: | ||
| server.shutdown() | ||
| server.server_close() | ||
| thread.join() | ||
|
|
||
|
|
||
| def test_http_error_carries_the_response_headers(): | ||
| with ( | ||
| refusing_server() as url, | ||
| FishAudio(api_key="k", base_url=url) as client, | ||
| pytest.raises(AuthenticationError) as exc_info, | ||
| ): | ||
| client.tts.convert(text="hi") | ||
| error = exc_info.value | ||
| assert error.status == 401 | ||
| assert error.message == "Invalid Token" | ||
| assert error.headers["x-fish-trace-id"] == "trace-123" | ||
| assert error.headers["X-Fish-Error-Code"] == "invalid_api_key" # any casing | ||
|
|
||
|
|
||
| async def test_http_error_carries_the_response_headers_async(): | ||
| with refusing_server() as url: | ||
| async with AsyncFishAudio(api_key="k", base_url=url) as client: | ||
| with pytest.raises(AuthenticationError) as exc_info: | ||
| await client.tts.convert(text="hi") | ||
| assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" | ||
|
|
||
|
|
||
| def test_headers_the_response_does_not_have_are_absent(): | ||
| with ( | ||
| refusing_server() as url, | ||
| FishAudio(api_key="k", base_url=url) as client, | ||
| pytest.raises(APIError) as exc_info, | ||
| ): | ||
| client.account.get_credits() | ||
| assert exc_info.value.status == 404 | ||
| assert exc_info.value.headers["content-type"] == "application/json" | ||
| assert exc_info.value.headers.get("x-fish-trace-id") is None | ||
|
|
||
|
|
||
| async def test_headers_the_response_does_not_have_are_absent_async(): | ||
| with refusing_server() as url: | ||
| async with AsyncFishAudio(api_key="k", base_url=url) as client: | ||
| with pytest.raises(APIError) as exc_info: | ||
| await client.account.get_credits() | ||
| assert exc_info.value.status == 404 | ||
| assert exc_info.value.headers["content-type"] == "application/json" | ||
| assert exc_info.value.headers.get("x-fish-trace-id") is None | ||
|
|
||
|
|
||
| def test_a_header_value_outside_ascii_arrives_as_sent(): | ||
| with ( | ||
| refusing_server() as url, | ||
| FishAudio(api_key="k", base_url=url) as client, | ||
| pytest.raises(APIError) as exc_info, | ||
| ): | ||
| client.account.get_credits() | ||
| assert exc_info.value.headers["x-detail"] == "café" | ||
|
|
||
|
|
||
| def test_error_built_by_hand_takes_a_header_value_outside_ascii(): | ||
| error = APIError(400, "Bad Request", headers={"x-detail": "café"}) | ||
| assert error.headers["x-detail"] == "café" | ||
|
|
||
|
|
||
| def test_error_built_without_headers_has_empty_headers(): | ||
| error = APIError(400, "Bad Request") | ||
| assert error.headers.get("x-fish-trace-id") is None | ||
| assert len(error.headers) == 0 | ||
|
|
||
|
|
||
| def test_refused_tts_websocket_exposes_the_headers_on_the_upgrade_error(): | ||
| """The README's second path: tts.stream_websocket is not wrapped.""" | ||
| server = RealtimeServer(lambda conn: None, reject_status=401) | ||
| try: | ||
| with ( | ||
| FishAudio(api_key="k", base_url=server.url) as client, | ||
| pytest.raises(WebSocketUpgradeError) as exc_info, | ||
| ): | ||
| list(client.tts.stream_websocket(iter(["hi"]))) | ||
| finally: | ||
| server.close() | ||
| assert exc_info.value.response.status_code == 401 | ||
| assert exc_info.value.response.headers["x-fish-trace-id"] == "trace-123" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("status", "error_class"), | ||
| [ | ||
| (400, APIError), | ||
| (401, AuthenticationError), | ||
| (403, PermissionError), | ||
| (404, NotFoundError), | ||
| (429, RateLimitError), | ||
| (503, ServerError), | ||
| ], | ||
| ) | ||
| def test_every_error_class_carries_the_headers(status, error_class): | ||
| response = httpx.Response( | ||
| status, | ||
| headers={"x-fish-trace-id": "trace-123"}, | ||
| json={"message": "refused"}, | ||
| request=httpx.Request("GET", "https://api.fish.audio/v1/tts"), | ||
| ) | ||
|
|
||
| with pytest.raises(APIError) as caught: | ||
| _raise_for_status(response) | ||
|
|
||
| assert type(caught.value) is error_class | ||
| assert caught.value.headers["x-fish-trace-id"] == "trace-123" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("body", [b"null", b"[]", b"not json"]) | ||
| def test_an_error_whose_body_is_not_an_object_carries_the_headers(body): | ||
| response = httpx.Response( | ||
| 500, | ||
| headers={"x-fish-trace-id": "trace-123"}, | ||
| content=body, | ||
| request=httpx.Request("POST", "https://api.fish.audio/v1/tts"), | ||
| ) | ||
| with pytest.raises(APIError) as caught: | ||
| _raise_for_status(response) | ||
| assert caught.value.headers["x-fish-trace-id"] == "trace-123" |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.