From f24e1653361576ddc23739715543e3784b5feddb Mon Sep 17 00:00:00 2001 From: Prashant Mital <5883388+prashantmital@users.noreply.github.com> Date: Mon, 13 Jul 2020 11:03:02 -0700 Subject: [PATCH] PYTHON-2263 Respect UuidRepresentation.UNSPECIFIED when parsing $uuid fields in extended JSON (#464) --- bson/json_util.py | 9 ++++++--- test/test_json_util.py | 6 +++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/bson/json_util.py b/bson/json_util.py index 14c364e7f..7b789b0f3 100644 --- a/bson/json_util.py +++ b/bson/json_util.py @@ -449,7 +449,7 @@ def object_hook(dct, json_options=DEFAULT_JSON_OPTIONS): if "$code" in dct: return _parse_canonical_code(dct) if "$uuid" in dct: - return _parse_legacy_uuid(dct) + return _parse_legacy_uuid(dct, json_options) if "$undefined" in dct: return None if "$numberLong" in dct: @@ -484,11 +484,14 @@ def _parse_legacy_regex(doc): return Regex(pattern, flags) -def _parse_legacy_uuid(doc): +def _parse_legacy_uuid(doc, json_options): """Decode a JSON legacy $uuid to Python UUID.""" if len(doc) != 1: raise TypeError('Bad $uuid, extra field(s): %s' % (doc,)) - return uuid.UUID(doc["$uuid"]) + if json_options.uuid_representation == UuidRepresentation.UNSPECIFIED: + return Binary.from_uuid(uuid.UUID(doc["$uuid"])) + else: + return uuid.UUID(doc["$uuid"]) def _binary_or_uuid(data, subtype, json_options): diff --git a/test/test_json_util.py b/test/test_json_util.py index 6499818b2..e8b64a16d 100644 --- a/test/test_json_util.py +++ b/test/test_json_util.py @@ -301,7 +301,11 @@ class TestJsonUtil(unittest.TestCase): ext_json_str = json_util.dumps(doc) self.assertEqual( doc, json_util.loads(ext_json_str, json_options=options)) - + # $uuid-encoded fields + doc = {'uuid': Binary(_uuid.bytes, subtype=4)} + ext_json_str = json_util.dumps({'uuid': _uuid}) + self.assertEqual( + doc, json_util.loads(ext_json_str, json_options=options)) def test_binary(self): if PY3: