PYTHON-2263 Respect UuidRepresentation.UNSPECIFIED when parsing $uuid fields in extended JSON (#464)

This commit is contained in:
Prashant Mital 2020-07-13 11:03:02 -07:00 committed by GitHub
parent f80c82453b
commit f24e165336
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 4 deletions

View File

@ -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):

View File

@ -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: