From fc5ddcc87e1eb0aab3a3efca727c3be1577ce593 Mon Sep 17 00:00:00 2001 From: techi101 Date: Sat, 7 Nov 2026 12:11:19 +0530 Subject: [PATCH] Fix $maxKey error messages in json_util The $maxKey value check passed the doc as a second TypeError argument instead of formatting it, and the extra-field check said $minKey. Format both like the $minKey parser does and add a test. Assisted-by: Claude --- bson/json_util.py | 4 ++-- test/test_json_util.py | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/bson/json_util.py b/bson/json_util.py index 01f9f0497d..f19ad69afb 100644 --- a/bson/json_util.py +++ b/bson/json_util.py @@ -776,9 +776,9 @@ def _parse_canonical_minkey(doc: Any, dummy0: Any) -> MinKey: def _parse_canonical_maxkey(doc: Any, dummy0: Any) -> MaxKey: """Decode a JSON MaxKey to bson.max_key.MaxKey.""" if type(doc["$maxKey"]) is not int or doc["$maxKey"] != 1: - raise TypeError("$maxKey value must be 1: %s", (doc,)) + raise TypeError(f"$maxKey value must be 1: {doc}") if len(doc) != 1: - raise TypeError(f"Bad $minKey, extra field(s): {doc}") + raise TypeError(f"Bad $maxKey, extra field(s): {doc}") return MaxKey() diff --git a/test/test_json_util.py b/test/test_json_util.py index ada04955c4..2d02b0ad59 100644 --- a/test/test_json_util.py +++ b/test/test_json_util.py @@ -398,6 +398,13 @@ def test_minkey(self): def test_maxkey(self): self.round_trip({"m": MaxKey()}) + def test_minkey_maxkey_errors(self): + for key in ("$minKey", "$maxKey"): + with self.assertRaisesRegex(TypeError, rf"^\{key} value must be 1: "): + json_util.loads(json.dumps({key: 2})) + with self.assertRaisesRegex(TypeError, rf"^Bad \{key}, extra field\(s\): "): + json_util.loads(json.dumps({key: 1, "x": 1})) + def test_timestamp(self): dct = {"ts": Timestamp(4, 13)} res = json_util.dumps(dct, default=json_util.default)