From af488e1ba858ed33620a90af27ff3bcc957de936 Mon Sep 17 00:00:00 2001 From: baraline Date: Mon, 23 Nov 2026 00:44:03 +0100 Subject: [PATCH 1/3] Raise GlpiResponseBodyError, a GlpiProtocolError, when a success response body is not JSON, instead of a bare json.JSONDecodeError. Every decode of a success body on the v2 transport, the v1 session and the token manager goes through decode_json_body. It carries the status, URL, content type, body length and a bounded excerpt, chains the decode error, and is not retried. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 21 ++++ docs/api_reference.rst | 4 + docs/user_guide.rst | 30 ++++++ glpi_python_client/__init__.py | 2 + glpi_python_client/_async/auth/_v1_session.py | 6 +- glpi_python_client/_async/auth/auth.py | 22 +++- .../_async/auth/tests/test_auth.py | 54 ++++++++++ .../_async/auth/tests/test_v1_session.py | 52 +++++++++ .../_async/clients/commons/_http.py | 63 ++++++++++- .../_async/clients/commons/_transport.py | 5 +- .../_async/clients/commons/tests/test_http.py | 101 +++++++++++++++++- .../clients/commons/tests/test_transport.py | 52 +++++++++ glpi_python_client/_errors.py | 86 ++++++++++++++- glpi_python_client/_sync/auth/_v1_session.py | 6 +- glpi_python_client/_sync/auth/auth.py | 22 +++- .../_sync/auth/tests/test_auth.py | 54 ++++++++++ .../_sync/auth/tests/test_v1_session.py | 52 +++++++++ .../_sync/clients/commons/_http.py | 63 ++++++++++- .../_sync/clients/commons/_transport.py | 5 +- .../_sync/clients/commons/tests/test_http.py | 101 +++++++++++++++++- .../clients/commons/tests/test_transport.py | 52 +++++++++ .../testing/tests/test_raise_site_audit.py | 1 + 22 files changed, 833 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a654cc2..99fa3eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,27 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## Unreleased + +### Fixed + +- **A success response whose body is not JSON now raises `GlpiProtocolError` + instead of a bare `json.JSONDecodeError`.** A server or a proxy answering + 200 with an HTML page or a garbled body used to surface a `ValueError` + that read like bad input. Every decode of a success body, on the v2 + transport, the v1 session and the OAuth token manager, now goes through + one helper that raises the new `GlpiResponseBodyError` (a subclass of + `GlpiProtocolError`) with `status_code`, `url`, `content_type`, + `body_length` and a bounded `body_excerpt`, and chains the decode error as + `__cause__`. The body is kept out of the message. It is not retried: a + 2xx means the request was processed. Empty answers on routes that accept + them (204, `DELETE`, v1 calls without a payload) are unchanged; an empty + 200 on a route that must return JSON raises the same error. + +### Added + +- **`GlpiResponseBodyError`**, exported from the package root. + ## 0.6.10 — 2026-11-16 A minor addition: the GLPI v2 `/Dropdowns/ITILCategory` routes, so a caller diff --git a/docs/api_reference.rst b/docs/api_reference.rst index cbe0340..e4d2d1e 100644 --- a/docs/api_reference.rst +++ b/docs/api_reference.rst @@ -82,6 +82,10 @@ guide for the full picture, including which methods raise which type. :members: :show-inheritance: +.. autoexception:: GlpiResponseBodyError + :members: + :show-inheritance: + .. autoexception:: GlpiContentError :members: :show-inheritance: diff --git a/docs/user_guide.rst b/docs/user_guide.rst index 41de66a..d87b189 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -1810,6 +1810,7 @@ The hierarchy lets you narrow as far as you need: │ reaches you) ├── GlpiValidationError the client rejected your argument ├── GlpiProtocolError GLPI answered 2xx with an unusable body + │ └── GlpiResponseBodyError the 2xx body is not JSON └── GlpiContentError a rich-text body could not be converted between HTML and Markdown @@ -1827,6 +1828,35 @@ usually want: print(exc.url) # the absolute URL that was requested print(exc.response_text) # the response body +A success status does not guarantee a usable body. When a server, or a +proxy in front of it, answers 2xx with an HTML page, a garbled body or +nothing at all on a route that must return a payload, the client raises +:class:`~glpi_python_client.GlpiResponseBodyError`, a +:class:`~glpi_python_client.GlpiProtocolError`, instead of a bare +``json.JSONDecodeError``. The request was sent and answered, so the failure +is the response, not your arguments: + +.. code-block:: python + + from glpi_python_client import GlpiResponseBodyError + + try: + ticket = client.get_ticket(1) + except GlpiResponseBodyError as exc: + print(exc.status_code) # 200 + print(exc.url) # the absolute URL that was requested + print(exc.content_type) # for example "text/html" + print(exc.body_length) # body size in bytes + print(exc.body_excerpt) # first 200 characters, for diagnostics + +The decode error is chained as ``__cause__``. The message names the status, +URL, content type and length but never the body, which may carry data. The +error is **not** retried: a 2xx means the request was processed, and +sending a write again could apply it twice. Routes that deliberately accept +an empty answer (a 204, a ``DELETE``, a v1 call with no payload) still +return normally; an empty 200 on a route that must return a payload raises +the same error with ``body_length == 0``. + .. note:: :class:`~glpi_python_client.GlpiStatusError`, diff --git a/glpi_python_client/__init__.py b/glpi_python_client/__init__.py index 6676651..f31e210 100644 --- a/glpi_python_client/__init__.py +++ b/glpi_python_client/__init__.py @@ -24,6 +24,7 @@ GlpiError, GlpiNotFoundError, GlpiProtocolError, + GlpiResponseBodyError, GlpiServerError, GlpiStatusError, GlpiTimeoutError, @@ -202,6 +203,7 @@ "GlpiNotFoundError", "GlpiPriority", "GlpiProtocolError", + "GlpiResponseBodyError", "GlpiServerError", "GlpiSolutionStatus", "GlpiStatusError", diff --git a/glpi_python_client/_async/auth/_v1_session.py b/glpi_python_client/_async/auth/_v1_session.py index 0c2304d..855d2bb 100644 --- a/glpi_python_client/_async/auth/_v1_session.py +++ b/glpi_python_client/_async/auth/_v1_session.py @@ -45,6 +45,7 @@ from glpi_python_client._async.clients.commons._config import build_http_session from glpi_python_client._async.clients.commons._http import ( + decode_json_body, ensure_response_status, finalize_request_response, response_json_or_empty, @@ -165,7 +166,8 @@ async def _init_session(self) -> None: failure_message="GLPI v1 initSession failed", ) - token = response.json().get("session_token") + body = decode_json_body(response) + token = body.get("session_token") if isinstance(body, dict) else None if not token: raise GlpiProtocolError("GLPI v1 initSession returned no session_token") @@ -441,7 +443,7 @@ async def upload_document( success_statuses=(200, 201), failure_message="GLPI v1 document upload failed", ) - payload = response.json() + payload = decode_json_body(response) if not isinstance(payload, dict): raise GlpiProtocolError( "GLPI v1 document upload returned unexpected payload: " diff --git a/glpi_python_client/_async/auth/auth.py b/glpi_python_client/_async/auth/auth.py index 64d7c32..4010713 100644 --- a/glpi_python_client/_async/auth/auth.py +++ b/glpi_python_client/_async/auth/auth.py @@ -9,12 +9,16 @@ import logging from datetime import UTC, datetime, timedelta +from typing import cast import httpx from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed from glpi_python_client._async.clients.commons._config import build_http_session -from glpi_python_client._async.clients.commons._http import transport_error_from +from glpi_python_client._async.clients.commons._http import ( + decode_json_body, + transport_error_from, +) from glpi_python_client._errors import ( GlpiServerError, GlpiTransportError, @@ -218,6 +222,18 @@ def _build_token_request_data(self) -> dict[str, str]: return data + def _decode_token_body(self, response: httpx.Response) -> dict[str, object]: + """Decode a successful token response, raising a library error if not JSON. + + Raises + ------ + GlpiResponseBodyError + When the 2xx body is not JSON. Not retried: the endpoint answered. + """ + + payload = decode_json_body(response, url=self._token_url) + return cast(dict[str, object], payload) + def _store_token_data( self, token_data: dict[str, object], label: str = "acquired" ) -> None: @@ -312,7 +328,7 @@ async def _acquire_token(self) -> None: data = self._build_token_request_data() response = await self._post_token_request(data) if 200 <= response.status_code < 300: - self._store_token_data(response.json()) + self._store_token_data(self._decode_token_body(response)) return try: error_detail = response.json() @@ -381,7 +397,7 @@ async def _refresh_access_token(self) -> None: data["client_secret"] = self._client_secret response = await self._post_token_request(data) if 200 <= response.status_code < 300: - self._store_token_data(response.json(), label="refreshed") + self._store_token_data(self._decode_token_body(response), label="refreshed") return logger.warning("Token refresh failed, acquiring new token...") await self._acquire_token() diff --git a/glpi_python_client/_async/auth/tests/test_auth.py b/glpi_python_client/_async/auth/tests/test_auth.py index b7050e2..8cf00ed 100644 --- a/glpi_python_client/_async/auth/tests/test_auth.py +++ b/glpi_python_client/_async/auth/tests/test_auth.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json from datetime import UTC, datetime, timedelta from typing import cast @@ -9,6 +10,7 @@ from glpi_python_client import ( GlpiAuthError, + GlpiResponseBodyError, GlpiServerError, GlpiTransportError, GlpiValidationError, @@ -435,3 +437,55 @@ async def post( await manager.ensure_token() assert len(session.calls) == 3 + + +@pytest.mark.parametrize("refresh", [False, True]) +@pytest.mark.parametrize( + ("content", "content_type"), + [ + (b"Gateway page", "text/html"), + (b"\xff\xfe\x00garbled", "application/json"), + ], +) +async def test_token_success_body_that_is_not_json_raises_protocol_error_once( + refresh: bool, content: bytes, content_type: str +) -> None: + """A non-JSON 200 from the token endpoint is a protocol error, not retried. + + On the refresh path it is not swallowed into a silent re-acquire either: + the endpoint answered, and the answer is what failed. + """ + + url = "https://glpi.example.test/api.php/token" + session = _FakeSession( + response=cast( + FakeResponse, + httpx.Response( + 200, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("POST", url), + ), + ) + ) + manager = GLPITokenManager( + token_url=url, + client_id="client-id", + client_secret="client-secret", + session=cast(httpx.AsyncClient, session), + ) + if refresh: + manager.access_token = "old" + manager.refresh_token = "refresh" + with pytest.raises(GlpiResponseBodyError) as excinfo: + if refresh: + await manager._refresh_access_token() + else: + await manager.ensure_token() + + error = excinfo.value + assert isinstance(error.__cause__, (json.JSONDecodeError, UnicodeDecodeError)) + assert (error.status_code, error.content_type) == (200, content_type) + assert error.body_length == len(content) + assert error.url == url + assert len(session.calls) == 1 diff --git a/glpi_python_client/_async/auth/tests/test_v1_session.py b/glpi_python_client/_async/auth/tests/test_v1_session.py index effda30..6fcbba5 100644 --- a/glpi_python_client/_async/auth/tests/test_v1_session.py +++ b/glpi_python_client/_async/auth/tests/test_v1_session.py @@ -11,6 +11,7 @@ from glpi_python_client import ( GlpiProtocolError, + GlpiResponseBodyError, GlpiServerError, GlpiTransportError, GlpiValidationError, @@ -559,3 +560,54 @@ async def test_session_token_invalid_marker_triggers_renew() -> None: result = await session.upload_document("a.txt", b"x", "text/plain") assert result == {"id": 2} + + +def _non_json(content: bytes, content_type: str) -> httpx.Response: + return httpx.Response( + 200, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("GET", "https://glpi.example.test/apirest.php/x"), + ) + + +_NON_JSON_BODIES = [ + (b"Gateway page", "text/html"), + (b"\xff\xfe\x00garbled", "application/json"), +] + + +@pytest.mark.parametrize(("content", "content_type"), _NON_JSON_BODIES) +@pytest.mark.parametrize("step", ["init", "upload", "json"]) +async def test_v1_success_body_that_is_not_json_raises_protocol_error_once( + step: str, content: bytes, content_type: str +) -> None: + """A non-JSON 200 raises ``GlpiResponseBodyError`` and is not retried.""" + + bad = cast(FakeResponse, _non_json(content, content_type)) + good_init = FakeResponse(status_code=200, payload={"session_token": "tk"}) + responses: dict[str, list[FakeResponse]] = { + "init": [good_init], + "upload": [], + "json": [], + "kill": [FakeResponse(status_code=200, payload={})], + } + responses["init" if step == "init" else step] = [bad] + http = _FakeV1Http(responses=responses) + session = _make(http) + + with pytest.raises(GlpiResponseBodyError) as excinfo: + if step == "init": + await session._init_session() + elif step == "upload": + await session.upload_document("a.txt", b"x", "text/plain") + else: + await session.request_json("GET", "Ticket/1") + + error = excinfo.value + assert isinstance(error, GlpiProtocolError) + assert isinstance(error.__cause__, (jsonlib.JSONDecodeError, UnicodeDecodeError)) + assert (error.status_code, error.content_type) == (200, content_type) + assert error.body_length == len(content) + target = {"init": "/initSession", "upload": "/Document", "json": "/Ticket/1"}[step] + assert len([c for c in http.calls if c["url"].endswith(target)]) == 1 diff --git a/glpi_python_client/_async/clients/commons/_http.py b/glpi_python_client/_async/clients/commons/_http.py index 7f75887..7425b9b 100644 --- a/glpi_python_client/_async/clients/commons/_http.py +++ b/glpi_python_client/_async/clients/commons/_http.py @@ -7,6 +7,7 @@ from __future__ import annotations +import json import logging from collections.abc import Mapping @@ -15,6 +16,7 @@ from glpi_python_client._async.clients.commons._constants import RequestParamValue from glpi_python_client._errors import ( GlpiProtocolError, + GlpiResponseBodyError, GlpiServerError, GlpiTimeoutError, GlpiTransportError, @@ -285,6 +287,62 @@ def ensure_response_status( ) +#: Longest body excerpt kept on a :class:`GlpiResponseBodyError`. +_BODY_EXCERPT_LIMIT = 200 + + +def decode_json_body(response: httpx.Response, *, url: str | None = None) -> object: + """Decode one success response body as JSON, or raise a library error. + + Every decode of a success body goes through this helper, so a server or + a proxy answering 2xx with an HTML page or a garbled body surfaces as + :class:`~glpi_python_client.GlpiResponseBodyError` (a + :class:`~glpi_python_client.GlpiProtocolError`) instead of a bare + :class:`json.JSONDecodeError`. The request was answered, so the failure + is the response, and it is not retried. + + An empty body is not valid JSON and raises too: this helper is for + routes that must return a payload. Routes that deliberately accept an + empty answer use :func:`response_json_or_empty` or + :func:`response_json_mapping`. + + Parameters + ---------- + response : httpx.Response + A response whose status was already accepted as a success. + url : str, optional + URL to report; defaults to the response's own request URL. + + Returns + ------- + object + The decoded JSON value. + + Raises + ------ + GlpiResponseBodyError + When the body is not valid JSON or not valid text. + """ + + try: + return response.json() + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + content = response.content + content_type = str(response.headers.get("content-type", "")) + status = response.status_code + reported_url = url if url is not None else str(response.url) + raise GlpiResponseBodyError( + f"GLPI answered {status} with a body that is not JSON " + f"(content type {content_type or 'none'!r}, {len(content)} bytes) " + f"from {reported_url}", + status_code=status, + url=reported_url, + content_type=content_type, + body_length=len(content), + body_excerpt=content[:_BODY_EXCERPT_LIMIT].decode("utf-8", "replace"), + ) from exc + + def response_json_or_empty(response: httpx.Response) -> object: """Return the parsed JSON body or an empty mapping for empty responses. @@ -295,7 +353,7 @@ def response_json_or_empty(response: httpx.Response) -> object: if not response.content or not response.text.strip(): return {} - return response.json() + return decode_json_body(response) def response_json_mapping(response: httpx.Response) -> Mapping[str, object]: @@ -306,7 +364,7 @@ def response_json_mapping(response: httpx.Response) -> Mapping[str, object]: expected keys. """ - result = response.json() if response.content else {} + result = decode_json_body(response) if response.content else {} return result if isinstance(result, Mapping) else {} @@ -438,6 +496,7 @@ def unwrap_timeline_items(payload: object) -> list[dict[str, object]]: "build_request_headers", "build_request_url", "coerce_response_int", + "decode_json_body", "ensure_response_status", "finalize_request_response", "list_payload_items", diff --git a/glpi_python_client/_async/clients/commons/_transport.py b/glpi_python_client/_async/clients/commons/_transport.py index a0706c3..58b98d3 100644 --- a/glpi_python_client/_async/clients/commons/_transport.py +++ b/glpi_python_client/_async/clients/commons/_transport.py @@ -36,6 +36,7 @@ from glpi_python_client._async.clients.commons._http import ( build_request_headers, build_request_url, + decode_json_body, ensure_response_status, finalize_request_response, list_payload_items, @@ -446,7 +447,7 @@ async def _resource_list( success_statuses=success_statuses, failure_message=failure_message or f"Failed to list {endpoint}", ) - payload = response.json() + payload = decode_json_body(response) items = ( unwrap_timeline_items(payload) if unwrap_envelope @@ -492,7 +493,7 @@ async def _resource_get( failure_message=failure_message, ) return model_from_payload( - model, response.json(), server_timezone=self.server_timezone + model, decode_json_body(response), server_timezone=self.server_timezone ) def _body(self, model: GlpiModel) -> dict[str, object]: diff --git a/glpi_python_client/_async/clients/commons/tests/test_http.py b/glpi_python_client/_async/clients/commons/tests/test_http.py index 989276e..e3fabcc 100644 --- a/glpi_python_client/_async/clients/commons/tests/test_http.py +++ b/glpi_python_client/_async/clients/commons/tests/test_http.py @@ -8,12 +8,19 @@ import json +import httpx import pytest -from glpi_python_client import GlpiNotFoundError, GlpiProtocolError, GlpiValidationError +from glpi_python_client import ( + GlpiNotFoundError, + GlpiProtocolError, + GlpiResponseBodyError, + GlpiValidationError, +) from glpi_python_client._async.clients.commons._http import ( build_request_headers, build_request_url, + decode_json_body, ensure_response_status, list_payload_items, request_param_value, @@ -21,6 +28,7 @@ require_access_token, require_response_int, response_json_mapping, + response_json_or_empty, ) from glpi_python_client.testing.utils import FakeResponse @@ -244,3 +252,94 @@ def test_require_response_int_falls_back_to_the_location_header() -> None: ) assert require_response_int(response, keys=("id",), missing_message="x") == 4242 + + +_BODY_URL = "https://glpi.example.test/api.php/Assistance/Ticket/1" + + +def _body_response( + content: bytes, *, content_type: str = "text/html", status: int = 200 +) -> httpx.Response: + """Build a real ``httpx`` response, so ``json()`` really tries to decode.""" + + return httpx.Response( + status, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("GET", _BODY_URL), + ) + + +@pytest.mark.parametrize( + ("content", "content_type"), + [ + (b"Bad gateway page", "text/html; charset=utf-8"), + (b"\xff\xfe\x00garbled", "application/json"), + (b"", "application/json"), + ], +) +def test_decode_json_body_raises_protocol_error_on_an_unusable_body( + content: bytes, content_type: str +) -> None: + """A success body that is not JSON is the response's fault, not a bad value.""" + + response = _body_response(content, content_type=content_type) + with pytest.raises(GlpiResponseBodyError) as excinfo: + decode_json_body(response) + + error = excinfo.value + assert isinstance(error, GlpiProtocolError) + assert isinstance(error.__cause__, (json.JSONDecodeError, UnicodeDecodeError)) + assert error.status_code == 200 + assert error.url == _BODY_URL + assert error.content_type == content_type + assert error.body_length == len(content) + + +def test_decode_json_body_bounds_the_excerpt_and_keeps_it_out_of_the_message() -> None: + """The body may carry data: it is kept as a bounded attribute only.""" + + content = b"" + b"x" * 5000 + with pytest.raises(GlpiResponseBodyError) as excinfo: + decode_json_body(_body_response(content)) + + assert excinfo.value.body_excerpt == content[:200].decode() + assert "xxxx" not in str(excinfo.value) + assert str(excinfo.value.status_code) in str(excinfo.value) + + +def test_decode_json_body_returns_valid_json_untouched() -> None: + assert decode_json_body(_body_response(b'{"id": 1}', content_type="a/b")) == { + "id": 1 + } + + +def test_lenient_helpers_keep_an_empty_body_empty_but_reject_html() -> None: + """Deliberately empty answers stay empty; a non-empty non-JSON body raises.""" + + assert response_json_or_empty(_body_response(b"")) == {} + assert response_json_mapping(_body_response(b"")) == {} + with pytest.raises(GlpiResponseBodyError): + response_json_or_empty(_body_response(b"")) + with pytest.raises(GlpiResponseBodyError): + response_json_mapping(_body_response(b"")) + + +def test_response_body_error_survives_pickle_round_trip() -> None: + import pickle + + error = GlpiResponseBodyError( + "boom", + status_code=200, + url="https://x", + content_type="text/html", + body_length=7, + body_excerpt="", + ) + clone = pickle.loads(pickle.dumps(error)) + assert (clone.status_code, clone.url, clone.content_type) == ( + 200, + "https://x", + "text/html", + ) + assert (clone.body_length, clone.body_excerpt, str(clone)) == (7, "", "boom") diff --git a/glpi_python_client/_async/clients/commons/tests/test_transport.py b/glpi_python_client/_async/clients/commons/tests/test_transport.py index 677f0c5..0056de3 100644 --- a/glpi_python_client/_async/clients/commons/tests/test_transport.py +++ b/glpi_python_client/_async/clients/commons/tests/test_transport.py @@ -14,6 +14,7 @@ from __future__ import annotations +import json from collections.abc import AsyncIterator from typing import Any @@ -24,6 +25,8 @@ from glpi_python_client import ( AsyncGlpiClient, GlpiError, + GlpiProtocolError, + GlpiResponseBodyError, GlpiServerError, GlpiStatusError, GlpiTimeoutError, @@ -453,3 +456,52 @@ async def _request(method: str, url: str, **kw: Any) -> FakeResponse: retry_client._session.request = _request with pytest.raises(GlpiTimeoutError): await retry_client._get_request("Assistance/Ticket") + + +def _non_json_response(content: bytes, content_type: str) -> httpx.Response: + return httpx.Response( + 200, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("GET", "https://glpi.example.test/api.php/Ticket"), + ) + + +@pytest.mark.parametrize( + ("content", "content_type"), + [ + (b"Gateway page", "text/html"), + (b"\xff\xfe\x00garbled", "application/json"), + ], +) +@pytest.mark.parametrize("surface", ["list", "get"]) +async def test_success_body_that_is_not_json_raises_protocol_error_once( + transport_client: Any, surface: str, content: bytes, content_type: str +) -> None: + """A 200 that is not JSON is a protocol error and is never retried. + + A 2xx means the server processed the request; sending it again could + apply a write twice, so exactly one request is made. + """ + + sent: list[str] = [] + + async def _send(method: str, url: str, **kw: Any) -> httpx.Response: + sent.append(url) + return _non_json_response(content, content_type) + + transport_client._send_request = _send + + with pytest.raises(GlpiProtocolError) as excinfo: + if surface == "list": + await transport_client.search_tickets() + else: + await transport_client.get_ticket(1) + + error = excinfo.value + assert isinstance(error, GlpiResponseBodyError) + assert isinstance(error.__cause__, (json.JSONDecodeError, UnicodeDecodeError)) + assert error.status_code == 200 + assert error.content_type == content_type + assert error.body_length == len(content) + assert len(sent) == 1 diff --git a/glpi_python_client/_errors.py b/glpi_python_client/_errors.py index a04bff3..8fcb864 100644 --- a/glpi_python_client/_errors.py +++ b/glpi_python_client/_errors.py @@ -135,10 +135,93 @@ class GlpiProtocolError(GlpiError, ValueError): Raised when the server returns a success status but the payload is missing a documented field or has an unusable shape. The caller did nothing wrong, so this is deliberately distinct from - :class:`GlpiValidationError`. + :class:`GlpiValidationError`. A body that is not JSON at all raises the + narrower :class:`GlpiResponseBodyError`. """ +class GlpiResponseBodyError(GlpiProtocolError): + """GLPI answered successfully with a body that is not JSON. + + Raised when a 2xx response, expected to carry JSON, holds an HTML page + (typically a proxy or gateway answering in GLPI's place), a garbled + body, bytes that are not valid text, or nothing at all on a route that + must return a payload. The request was sent and processed, so it is + never retried: retrying a write could apply it twice. The underlying + decode error is attached as ``__cause__``. + + The body itself is kept out of the message, which only names the + status, URL, content type and length; a bounded excerpt is available as + ``body_excerpt`` for diagnostics. + + Parameters + ---------- + message : str + Human-readable description of the failure. + status_code : int + The HTTP status code of the response. + url : str + The absolute URL that was requested. + content_type : str, optional + The ``Content-Type`` header of the response, ``""`` when absent. + body_length : int, optional + The length of the body in bytes. + body_excerpt : str, optional + The first characters of the body, for diagnostics. + + Attributes + ---------- + status_code : int + The HTTP status code of the response. + url : str + The absolute URL that was requested. + content_type : str + The ``Content-Type`` header of the response, ``""`` when absent. + body_length : int + The length of the body in bytes. + body_excerpt : str + The first characters of the body, for diagnostics. + """ + + status_code: int + url: str + content_type: str + body_length: int + body_excerpt: str + + def __init__( + self, + message: str, + *, + status_code: int, + url: str, + content_type: str = "", + body_length: int = 0, + body_excerpt: str = "", + ) -> None: + super().__init__(message) + self.status_code = status_code + self.url = url + self.content_type = content_type + self.body_length = body_length + self.body_excerpt = body_excerpt + + def __reduce__(self) -> tuple[Any, ...]: + """Support :mod:`pickle` and :mod:`copy` for keyword-only arguments.""" + + return ( + partial( + type(self), + status_code=self.status_code, + url=self.url, + content_type=self.content_type, + body_length=self.body_length, + body_excerpt=self.body_excerpt, + ), + (str(self),), + ) + + class GlpiContentError(GlpiError): """A rich-text content value could not be converted. @@ -199,6 +282,7 @@ def status_error_class(status_code: int) -> type[GlpiStatusError]: "GlpiError", "GlpiNotFoundError", "GlpiProtocolError", + "GlpiResponseBodyError", "GlpiServerError", "GlpiStatusError", "GlpiTimeoutError", diff --git a/glpi_python_client/_sync/auth/_v1_session.py b/glpi_python_client/_sync/auth/_v1_session.py index 222afcd..a13b9ba 100644 --- a/glpi_python_client/_sync/auth/_v1_session.py +++ b/glpi_python_client/_sync/auth/_v1_session.py @@ -45,6 +45,7 @@ from glpi_python_client._sync.clients.commons._config import build_http_session from glpi_python_client._sync.clients.commons._http import ( + decode_json_body, ensure_response_status, finalize_request_response, response_json_or_empty, @@ -165,7 +166,8 @@ def _init_session(self) -> None: failure_message="GLPI v1 initSession failed", ) - token = response.json().get("session_token") + body = decode_json_body(response) + token = body.get("session_token") if isinstance(body, dict) else None if not token: raise GlpiProtocolError("GLPI v1 initSession returned no session_token") @@ -441,7 +443,7 @@ def upload_document( success_statuses=(200, 201), failure_message="GLPI v1 document upload failed", ) - payload = response.json() + payload = decode_json_body(response) if not isinstance(payload, dict): raise GlpiProtocolError( "GLPI v1 document upload returned unexpected payload: " diff --git a/glpi_python_client/_sync/auth/auth.py b/glpi_python_client/_sync/auth/auth.py index a4ba60f..cd54db2 100644 --- a/glpi_python_client/_sync/auth/auth.py +++ b/glpi_python_client/_sync/auth/auth.py @@ -9,12 +9,16 @@ import logging from datetime import UTC, datetime, timedelta +from typing import cast import httpx from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed from glpi_python_client._sync.clients.commons._config import build_http_session -from glpi_python_client._sync.clients.commons._http import transport_error_from +from glpi_python_client._sync.clients.commons._http import ( + decode_json_body, + transport_error_from, +) from glpi_python_client._errors import ( GlpiServerError, GlpiTransportError, @@ -218,6 +222,18 @@ def _build_token_request_data(self) -> dict[str, str]: return data + def _decode_token_body(self, response: httpx.Response) -> dict[str, object]: + """Decode a successful token response, raising a library error if not JSON. + + Raises + ------ + GlpiResponseBodyError + When the 2xx body is not JSON. Not retried: the endpoint answered. + """ + + payload = decode_json_body(response, url=self._token_url) + return cast(dict[str, object], payload) + def _store_token_data( self, token_data: dict[str, object], label: str = "acquired" ) -> None: @@ -312,7 +328,7 @@ def _acquire_token(self) -> None: data = self._build_token_request_data() response = self._post_token_request(data) if 200 <= response.status_code < 300: - self._store_token_data(response.json()) + self._store_token_data(self._decode_token_body(response)) return try: error_detail = response.json() @@ -381,7 +397,7 @@ def _refresh_access_token(self) -> None: data["client_secret"] = self._client_secret response = self._post_token_request(data) if 200 <= response.status_code < 300: - self._store_token_data(response.json(), label="refreshed") + self._store_token_data(self._decode_token_body(response), label="refreshed") return logger.warning("Token refresh failed, acquiring new token...") self._acquire_token() diff --git a/glpi_python_client/_sync/auth/tests/test_auth.py b/glpi_python_client/_sync/auth/tests/test_auth.py index 221297a..17bdeba 100644 --- a/glpi_python_client/_sync/auth/tests/test_auth.py +++ b/glpi_python_client/_sync/auth/tests/test_auth.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json from datetime import UTC, datetime, timedelta from typing import cast @@ -9,6 +10,7 @@ from glpi_python_client import ( GlpiAuthError, + GlpiResponseBodyError, GlpiServerError, GlpiTransportError, GlpiValidationError, @@ -435,3 +437,55 @@ def post( manager.ensure_token() assert len(session.calls) == 3 + + +@pytest.mark.parametrize("refresh", [False, True]) +@pytest.mark.parametrize( + ("content", "content_type"), + [ + (b"Gateway page", "text/html"), + (b"\xff\xfe\x00garbled", "application/json"), + ], +) +def test_token_success_body_that_is_not_json_raises_protocol_error_once( + refresh: bool, content: bytes, content_type: str +) -> None: + """A non-JSON 200 from the token endpoint is a protocol error, not retried. + + On the refresh path it is not swallowed into a silent re-acquire either: + the endpoint answered, and the answer is what failed. + """ + + url = "https://glpi.example.test/api.php/token" + session = _FakeSession( + response=cast( + FakeResponse, + httpx.Response( + 200, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("POST", url), + ), + ) + ) + manager = GLPITokenManager( + token_url=url, + client_id="client-id", + client_secret="client-secret", + session=cast(httpx.Client, session), + ) + if refresh: + manager.access_token = "old" + manager.refresh_token = "refresh" + with pytest.raises(GlpiResponseBodyError) as excinfo: + if refresh: + manager._refresh_access_token() + else: + manager.ensure_token() + + error = excinfo.value + assert isinstance(error.__cause__, (json.JSONDecodeError, UnicodeDecodeError)) + assert (error.status_code, error.content_type) == (200, content_type) + assert error.body_length == len(content) + assert error.url == url + assert len(session.calls) == 1 diff --git a/glpi_python_client/_sync/auth/tests/test_v1_session.py b/glpi_python_client/_sync/auth/tests/test_v1_session.py index e46ec27..be55221 100644 --- a/glpi_python_client/_sync/auth/tests/test_v1_session.py +++ b/glpi_python_client/_sync/auth/tests/test_v1_session.py @@ -11,6 +11,7 @@ from glpi_python_client import ( GlpiProtocolError, + GlpiResponseBodyError, GlpiServerError, GlpiTransportError, GlpiValidationError, @@ -559,3 +560,54 @@ def test_session_token_invalid_marker_triggers_renew() -> None: result = session.upload_document("a.txt", b"x", "text/plain") assert result == {"id": 2} + + +def _non_json(content: bytes, content_type: str) -> httpx.Response: + return httpx.Response( + 200, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("GET", "https://glpi.example.test/apirest.php/x"), + ) + + +_NON_JSON_BODIES = [ + (b"Gateway page", "text/html"), + (b"\xff\xfe\x00garbled", "application/json"), +] + + +@pytest.mark.parametrize(("content", "content_type"), _NON_JSON_BODIES) +@pytest.mark.parametrize("step", ["init", "upload", "json"]) +def test_v1_success_body_that_is_not_json_raises_protocol_error_once( + step: str, content: bytes, content_type: str +) -> None: + """A non-JSON 200 raises ``GlpiResponseBodyError`` and is not retried.""" + + bad = cast(FakeResponse, _non_json(content, content_type)) + good_init = FakeResponse(status_code=200, payload={"session_token": "tk"}) + responses: dict[str, list[FakeResponse]] = { + "init": [good_init], + "upload": [], + "json": [], + "kill": [FakeResponse(status_code=200, payload={})], + } + responses["init" if step == "init" else step] = [bad] + http = _FakeV1Http(responses=responses) + session = _make(http) + + with pytest.raises(GlpiResponseBodyError) as excinfo: + if step == "init": + session._init_session() + elif step == "upload": + session.upload_document("a.txt", b"x", "text/plain") + else: + session.request_json("GET", "Ticket/1") + + error = excinfo.value + assert isinstance(error, GlpiProtocolError) + assert isinstance(error.__cause__, (jsonlib.JSONDecodeError, UnicodeDecodeError)) + assert (error.status_code, error.content_type) == (200, content_type) + assert error.body_length == len(content) + target = {"init": "/initSession", "upload": "/Document", "json": "/Ticket/1"}[step] + assert len([c for c in http.calls if c["url"].endswith(target)]) == 1 diff --git a/glpi_python_client/_sync/clients/commons/_http.py b/glpi_python_client/_sync/clients/commons/_http.py index e4dca06..f45f3ab 100644 --- a/glpi_python_client/_sync/clients/commons/_http.py +++ b/glpi_python_client/_sync/clients/commons/_http.py @@ -7,6 +7,7 @@ from __future__ import annotations +import json import logging from collections.abc import Mapping @@ -15,6 +16,7 @@ from glpi_python_client._sync.clients.commons._constants import RequestParamValue from glpi_python_client._errors import ( GlpiProtocolError, + GlpiResponseBodyError, GlpiServerError, GlpiTimeoutError, GlpiTransportError, @@ -285,6 +287,62 @@ def ensure_response_status( ) +#: Longest body excerpt kept on a :class:`GlpiResponseBodyError`. +_BODY_EXCERPT_LIMIT = 200 + + +def decode_json_body(response: httpx.Response, *, url: str | None = None) -> object: + """Decode one success response body as JSON, or raise a library error. + + Every decode of a success body goes through this helper, so a server or + a proxy answering 2xx with an HTML page or a garbled body surfaces as + :class:`~glpi_python_client.GlpiResponseBodyError` (a + :class:`~glpi_python_client.GlpiProtocolError`) instead of a bare + :class:`json.JSONDecodeError`. The request was answered, so the failure + is the response, and it is not retried. + + An empty body is not valid JSON and raises too: this helper is for + routes that must return a payload. Routes that deliberately accept an + empty answer use :func:`response_json_or_empty` or + :func:`response_json_mapping`. + + Parameters + ---------- + response : httpx.Response + A response whose status was already accepted as a success. + url : str, optional + URL to report; defaults to the response's own request URL. + + Returns + ------- + object + The decoded JSON value. + + Raises + ------ + GlpiResponseBodyError + When the body is not valid JSON or not valid text. + """ + + try: + return response.json() + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + content = response.content + content_type = str(response.headers.get("content-type", "")) + status = response.status_code + reported_url = url if url is not None else str(response.url) + raise GlpiResponseBodyError( + f"GLPI answered {status} with a body that is not JSON " + f"(content type {content_type or 'none'!r}, {len(content)} bytes) " + f"from {reported_url}", + status_code=status, + url=reported_url, + content_type=content_type, + body_length=len(content), + body_excerpt=content[:_BODY_EXCERPT_LIMIT].decode("utf-8", "replace"), + ) from exc + + def response_json_or_empty(response: httpx.Response) -> object: """Return the parsed JSON body or an empty mapping for empty responses. @@ -295,7 +353,7 @@ def response_json_or_empty(response: httpx.Response) -> object: if not response.content or not response.text.strip(): return {} - return response.json() + return decode_json_body(response) def response_json_mapping(response: httpx.Response) -> Mapping[str, object]: @@ -306,7 +364,7 @@ def response_json_mapping(response: httpx.Response) -> Mapping[str, object]: expected keys. """ - result = response.json() if response.content else {} + result = decode_json_body(response) if response.content else {} return result if isinstance(result, Mapping) else {} @@ -438,6 +496,7 @@ def unwrap_timeline_items(payload: object) -> list[dict[str, object]]: "build_request_headers", "build_request_url", "coerce_response_int", + "decode_json_body", "ensure_response_status", "finalize_request_response", "list_payload_items", diff --git a/glpi_python_client/_sync/clients/commons/_transport.py b/glpi_python_client/_sync/clients/commons/_transport.py index 6ec2e12..a03dbf0 100644 --- a/glpi_python_client/_sync/clients/commons/_transport.py +++ b/glpi_python_client/_sync/clients/commons/_transport.py @@ -36,6 +36,7 @@ from glpi_python_client._sync.clients.commons._http import ( build_request_headers, build_request_url, + decode_json_body, ensure_response_status, finalize_request_response, list_payload_items, @@ -446,7 +447,7 @@ def _resource_list( success_statuses=success_statuses, failure_message=failure_message or f"Failed to list {endpoint}", ) - payload = response.json() + payload = decode_json_body(response) items = ( unwrap_timeline_items(payload) if unwrap_envelope @@ -492,7 +493,7 @@ def _resource_get( failure_message=failure_message, ) return model_from_payload( - model, response.json(), server_timezone=self.server_timezone + model, decode_json_body(response), server_timezone=self.server_timezone ) def _body(self, model: GlpiModel) -> dict[str, object]: diff --git a/glpi_python_client/_sync/clients/commons/tests/test_http.py b/glpi_python_client/_sync/clients/commons/tests/test_http.py index 7348c7f..b71222d 100644 --- a/glpi_python_client/_sync/clients/commons/tests/test_http.py +++ b/glpi_python_client/_sync/clients/commons/tests/test_http.py @@ -8,12 +8,19 @@ import json +import httpx import pytest -from glpi_python_client import GlpiNotFoundError, GlpiProtocolError, GlpiValidationError +from glpi_python_client import ( + GlpiNotFoundError, + GlpiProtocolError, + GlpiResponseBodyError, + GlpiValidationError, +) from glpi_python_client._sync.clients.commons._http import ( build_request_headers, build_request_url, + decode_json_body, ensure_response_status, list_payload_items, request_param_value, @@ -21,6 +28,7 @@ require_access_token, require_response_int, response_json_mapping, + response_json_or_empty, ) from glpi_python_client.testing.utils import FakeResponse @@ -244,3 +252,94 @@ def test_require_response_int_falls_back_to_the_location_header() -> None: ) assert require_response_int(response, keys=("id",), missing_message="x") == 4242 + + +_BODY_URL = "https://glpi.example.test/api.php/Assistance/Ticket/1" + + +def _body_response( + content: bytes, *, content_type: str = "text/html", status: int = 200 +) -> httpx.Response: + """Build a real ``httpx`` response, so ``json()`` really tries to decode.""" + + return httpx.Response( + status, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("GET", _BODY_URL), + ) + + +@pytest.mark.parametrize( + ("content", "content_type"), + [ + (b"Bad gateway page", "text/html; charset=utf-8"), + (b"\xff\xfe\x00garbled", "application/json"), + (b"", "application/json"), + ], +) +def test_decode_json_body_raises_protocol_error_on_an_unusable_body( + content: bytes, content_type: str +) -> None: + """A success body that is not JSON is the response's fault, not a bad value.""" + + response = _body_response(content, content_type=content_type) + with pytest.raises(GlpiResponseBodyError) as excinfo: + decode_json_body(response) + + error = excinfo.value + assert isinstance(error, GlpiProtocolError) + assert isinstance(error.__cause__, (json.JSONDecodeError, UnicodeDecodeError)) + assert error.status_code == 200 + assert error.url == _BODY_URL + assert error.content_type == content_type + assert error.body_length == len(content) + + +def test_decode_json_body_bounds_the_excerpt_and_keeps_it_out_of_the_message() -> None: + """The body may carry data: it is kept as a bounded attribute only.""" + + content = b"" + b"x" * 5000 + with pytest.raises(GlpiResponseBodyError) as excinfo: + decode_json_body(_body_response(content)) + + assert excinfo.value.body_excerpt == content[:200].decode() + assert "xxxx" not in str(excinfo.value) + assert str(excinfo.value.status_code) in str(excinfo.value) + + +def test_decode_json_body_returns_valid_json_untouched() -> None: + assert decode_json_body(_body_response(b'{"id": 1}', content_type="a/b")) == { + "id": 1 + } + + +def test_lenient_helpers_keep_an_empty_body_empty_but_reject_html() -> None: + """Deliberately empty answers stay empty; a non-empty non-JSON body raises.""" + + assert response_json_or_empty(_body_response(b"")) == {} + assert response_json_mapping(_body_response(b"")) == {} + with pytest.raises(GlpiResponseBodyError): + response_json_or_empty(_body_response(b"")) + with pytest.raises(GlpiResponseBodyError): + response_json_mapping(_body_response(b"")) + + +def test_response_body_error_survives_pickle_round_trip() -> None: + import pickle + + error = GlpiResponseBodyError( + "boom", + status_code=200, + url="https://x", + content_type="text/html", + body_length=7, + body_excerpt="", + ) + clone = pickle.loads(pickle.dumps(error)) + assert (clone.status_code, clone.url, clone.content_type) == ( + 200, + "https://x", + "text/html", + ) + assert (clone.body_length, clone.body_excerpt, str(clone)) == (7, "", "boom") diff --git a/glpi_python_client/_sync/clients/commons/tests/test_transport.py b/glpi_python_client/_sync/clients/commons/tests/test_transport.py index e4d4a69..14457fd 100644 --- a/glpi_python_client/_sync/clients/commons/tests/test_transport.py +++ b/glpi_python_client/_sync/clients/commons/tests/test_transport.py @@ -14,6 +14,7 @@ from __future__ import annotations +import json from collections.abc import Iterator from typing import Any @@ -24,6 +25,8 @@ from glpi_python_client import ( GlpiClient, GlpiError, + GlpiProtocolError, + GlpiResponseBodyError, GlpiServerError, GlpiStatusError, GlpiTimeoutError, @@ -453,3 +456,52 @@ def _request(method: str, url: str, **kw: Any) -> FakeResponse: retry_client._session.request = _request with pytest.raises(GlpiTimeoutError): retry_client._get_request("Assistance/Ticket") + + +def _non_json_response(content: bytes, content_type: str) -> httpx.Response: + return httpx.Response( + 200, + content=content, + headers={"content-type": content_type}, + request=httpx.Request("GET", "https://glpi.example.test/api.php/Ticket"), + ) + + +@pytest.mark.parametrize( + ("content", "content_type"), + [ + (b"Gateway page", "text/html"), + (b"\xff\xfe\x00garbled", "application/json"), + ], +) +@pytest.mark.parametrize("surface", ["list", "get"]) +def test_success_body_that_is_not_json_raises_protocol_error_once( + transport_client: Any, surface: str, content: bytes, content_type: str +) -> None: + """A 200 that is not JSON is a protocol error and is never retried. + + A 2xx means the server processed the request; sending it again could + apply a write twice, so exactly one request is made. + """ + + sent: list[str] = [] + + def _send(method: str, url: str, **kw: Any) -> httpx.Response: + sent.append(url) + return _non_json_response(content, content_type) + + transport_client._send_request = _send + + with pytest.raises(GlpiProtocolError) as excinfo: + if surface == "list": + transport_client.search_tickets() + else: + transport_client.get_ticket(1) + + error = excinfo.value + assert isinstance(error, GlpiResponseBodyError) + assert isinstance(error.__cause__, (json.JSONDecodeError, UnicodeDecodeError)) + assert error.status_code == 200 + assert error.content_type == content_type + assert error.body_length == len(content) + assert len(sent) == 1 diff --git a/glpi_python_client/testing/tests/test_raise_site_audit.py b/glpi_python_client/testing/tests/test_raise_site_audit.py index 1e839c8..d978341 100644 --- a/glpi_python_client/testing/tests/test_raise_site_audit.py +++ b/glpi_python_client/testing/tests/test_raise_site_audit.py @@ -32,6 +32,7 @@ _ALLOWED = { "GlpiValidationError", "GlpiProtocolError", + "GlpiResponseBodyError", "GlpiContentError", "GlpiServerError", "GlpiStatusError", From d88563947bc0155313b913af4b2a66ce712cb922 Mon Sep 17 00:00:00 2001 From: baraline Date: Mon, 23 Nov 2026 00:47:14 +0100 Subject: [PATCH 2/3] The CHANGELOG entry for non-JSON success bodies mentions the lenient helpers, which now raise the same error for a non-empty body that is not JSON. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 99fa3eb..833af42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `__cause__`. The body is kept out of the message. It is not retried: a 2xx means the request was processed. Empty answers on routes that accept them (204, `DELETE`, v1 calls without a payload) are unchanged; an empty - 200 on a route that must return JSON raises the same error. + 200 on a route that must return JSON raises the same error. The lenient + helpers `response_json_or_empty` and `response_json_mapping` keep an + empty body as empty but now raise the same error for a non-empty body that + is not JSON; the new error is a `ValueError` subclass like the one it + replaces, so existing `except ValueError` handlers still catch it. ### Added From eafb9dd1b794dec00e8af54d9d0937356ecfe622 Mon Sep 17 00:00:00 2001 From: baraline Date: Mon, 23 Nov 2026 01:23:11 +0100 Subject: [PATCH 3/3] The lenient JSON helpers treat a whitespace-only body alike as empty, and the docs give the error excerpt in bytes, not characters. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/user_guide.rst | 2 +- glpi_python_client/_async/clients/commons/_http.py | 4 +++- glpi_python_client/_async/clients/commons/tests/test_http.py | 2 ++ glpi_python_client/_errors.py | 4 ++-- glpi_python_client/_sync/clients/commons/_http.py | 4 +++- glpi_python_client/_sync/clients/commons/tests/test_http.py | 2 ++ 7 files changed, 14 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 833af42..25d45ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). them (204, `DELETE`, v1 calls without a payload) are unchanged; an empty 200 on a route that must return JSON raises the same error. The lenient helpers `response_json_or_empty` and `response_json_mapping` keep an - empty body as empty but now raise the same error for a non-empty body that + empty or whitespace-only body as empty but now raise the same error for a non-empty body that is not JSON; the new error is a `ValueError` subclass like the one it replaces, so existing `except ValueError` handlers still catch it. diff --git a/docs/user_guide.rst b/docs/user_guide.rst index d87b189..d125c13 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -1847,7 +1847,7 @@ is the response, not your arguments: print(exc.url) # the absolute URL that was requested print(exc.content_type) # for example "text/html" print(exc.body_length) # body size in bytes - print(exc.body_excerpt) # first 200 characters, for diagnostics + print(exc.body_excerpt) # first 200 bytes (UTF-8, replacement), for diagnostics The decode error is chained as ``__cause__``. The message names the status, URL, content type and length but never the body, which may carry data. The diff --git a/glpi_python_client/_async/clients/commons/_http.py b/glpi_python_client/_async/clients/commons/_http.py index 7425b9b..e44cd23 100644 --- a/glpi_python_client/_async/clients/commons/_http.py +++ b/glpi_python_client/_async/clients/commons/_http.py @@ -364,7 +364,9 @@ def response_json_mapping(response: httpx.Response) -> Mapping[str, object]: expected keys. """ - result = decode_json_body(response) if response.content else {} + if not response.content or not response.text.strip(): + return {} + result = decode_json_body(response) return result if isinstance(result, Mapping) else {} diff --git a/glpi_python_client/_async/clients/commons/tests/test_http.py b/glpi_python_client/_async/clients/commons/tests/test_http.py index e3fabcc..a983414 100644 --- a/glpi_python_client/_async/clients/commons/tests/test_http.py +++ b/glpi_python_client/_async/clients/commons/tests/test_http.py @@ -319,6 +319,8 @@ def test_lenient_helpers_keep_an_empty_body_empty_but_reject_html() -> None: assert response_json_or_empty(_body_response(b"")) == {} assert response_json_mapping(_body_response(b"")) == {} + assert response_json_or_empty(_body_response(b"\n")) == {} + assert response_json_mapping(_body_response(b"\n")) == {} with pytest.raises(GlpiResponseBodyError): response_json_or_empty(_body_response(b"")) with pytest.raises(GlpiResponseBodyError): diff --git a/glpi_python_client/_errors.py b/glpi_python_client/_errors.py index 8fcb864..7e57a38 100644 --- a/glpi_python_client/_errors.py +++ b/glpi_python_client/_errors.py @@ -167,7 +167,7 @@ class GlpiResponseBodyError(GlpiProtocolError): body_length : int, optional The length of the body in bytes. body_excerpt : str, optional - The first characters of the body, for diagnostics. + The first 200 bytes of the body, decoded as UTF-8 with replacement. Attributes ---------- @@ -180,7 +180,7 @@ class GlpiResponseBodyError(GlpiProtocolError): body_length : int The length of the body in bytes. body_excerpt : str - The first characters of the body, for diagnostics. + The first 200 bytes of the body, decoded as UTF-8 with replacement. """ status_code: int diff --git a/glpi_python_client/_sync/clients/commons/_http.py b/glpi_python_client/_sync/clients/commons/_http.py index f45f3ab..cd09c82 100644 --- a/glpi_python_client/_sync/clients/commons/_http.py +++ b/glpi_python_client/_sync/clients/commons/_http.py @@ -364,7 +364,9 @@ def response_json_mapping(response: httpx.Response) -> Mapping[str, object]: expected keys. """ - result = decode_json_body(response) if response.content else {} + if not response.content or not response.text.strip(): + return {} + result = decode_json_body(response) return result if isinstance(result, Mapping) else {} diff --git a/glpi_python_client/_sync/clients/commons/tests/test_http.py b/glpi_python_client/_sync/clients/commons/tests/test_http.py index b71222d..58ceb52 100644 --- a/glpi_python_client/_sync/clients/commons/tests/test_http.py +++ b/glpi_python_client/_sync/clients/commons/tests/test_http.py @@ -319,6 +319,8 @@ def test_lenient_helpers_keep_an_empty_body_empty_but_reject_html() -> None: assert response_json_or_empty(_body_response(b"")) == {} assert response_json_mapping(_body_response(b"")) == {} + assert response_json_or_empty(_body_response(b"\n")) == {} + assert response_json_mapping(_body_response(b"\n")) == {} with pytest.raises(GlpiResponseBodyError): response_json_or_empty(_body_response(b"")) with pytest.raises(GlpiResponseBodyError):