I have production code that stores mongoengine.Documents
with UUIDs like this:
class TestEntry(Document):
uuid_test = UUIDField(primary_key=True)
The regular code works as intended:
connect('mydatabase', host='localhost', port=27017)
_uid = uuid.uuid4()
entry = TestEntry(uuid_test=_uid)
entry.save()
I tried to replace the local db for with a mongomock
client for unit tests, which changes the connection call:
connect('mydatabase', mongo_client_class=mongomock.MongoClient)
When using the mongomock
client, I receive the following error code:
ValueError: cannot encode native uuid.UUID with UuidRepresentation.UNSPECIFIED.
UUIDs can be manually converted to bson.Binary instances using bson.Binary.from_uuid()
or a different UuidRepresentation can be configured.
See the documentation for UuidRepresentation for more information.
I tried to manually convert the generated uuid like mentioned.
However, I receive this exception, when trying to do so:
mongoengine.errors.ValidationError: ValidationError
(TestEntry:b'\xe7\xbe.h\xbe\xcfE\x95\x86%u\x15\xefA\x9a\x80')
(Could not convert to UUID: badly formed hexadecimal UUID string: ['uuid_test'])
What is best practice to allow for both clients to work interchangeable?
mongomock does not support setting uuidRepresentation and thus fails to decode/encode UUIDs. I'm not aware of any workaround what works without patching mongomock.
See: https://github.com/mongomock/mongomock/issues/745
Exact code in mongomock: https://github.com/mongomock/mongomock/blob/4.2.0/mongomock/codec_options.py#L66