From d2d5e10e1931f72553f2203a255703e820c63b22 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:39:45 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=202:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20read=20an?= =?UTF-8?q?=20error=20answer's=20body=20guarded,=20so=20one=20cut=20short?= =?UTF-8?q?=20names=20its=20status?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/mattermost_dm/dm.py | 9 +++++---- bin/mattermost_dm/test_mattermost_dm.py | 4 ++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/bin/mattermost_dm/dm.py b/bin/mattermost_dm/dm.py index 0f01578b..b71d27df 100644 --- a/bin/mattermost_dm/dm.py +++ b/bin/mattermost_dm/dm.py @@ -104,7 +104,7 @@ def http_json(method: str, url: str, token: str, body: object) -> object: raw = response.read() except urllib.error.HTTPError as failure: with failure: - return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}") + return Failure(f"{request_name} answered {failure.code}: {error_message(failure) or failure.reason}") except http.client.HTTPException as failure: return Failure(f"{request_name} got a broken answer: {failure!r}") except (OSError, ValueError) as failure: @@ -116,10 +116,11 @@ def http_json(method: str, url: str, token: str, body: object) -> object: return Failure(f"{request_name} answered with something other than JSON") -def error_message(raw: bytes) -> str: +def error_message(failure: urllib.error.HTTPError) -> str: + """Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none.""" try: - answer = json.loads(raw) - except ValueError: + answer = json.loads(failure.read()) + except (http.client.HTTPException, OSError, ValueError): return "" message = answer.get("message") if isinstance(answer, dict) else None return message if isinstance(message, str) else "" diff --git a/bin/mattermost_dm/test_mattermost_dm.py b/bin/mattermost_dm/test_mattermost_dm.py index 8924e5a2..9ed360be 100644 --- a/bin/mattermost_dm/test_mattermost_dm.py +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -176,6 +176,10 @@ class HttpJson(unittest.TestCase): failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None) self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed) + def test_names_the_status_of_an_error_whose_body_is_cut_short(self): + base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}")) + self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error")) + def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self): silent = socket.socket() self.addCleanup(silent.close)