我有存储 mongoengine.Documents 的生产代码,其 UUID 如下所示:
class TestEntry(Document):
uuid_test = UUIDField(primary_key=True)
常规代码按预期工作:
connect('mydatabase', host='localhost', port=27017)
_uid = uuid.uuid4()
entry = TestEntry(uuid_test=_uid)
entry.save()
我尝试用 mongomock 客户端替换本地数据库进行单元测试,这改变了连接调用:
connect('mydatabase', mongo_client_class=mongomock.MongoClient)
使用 mongomock 客户端时,我收到以下错误代码:
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.
我尝试像上面提到的那样手动转换生成的uuid。
但是,当我尝试这样做时,我收到了这个异常:
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'])
允许两个客户端互换工作的最佳实践是什么?
预先感谢!
mongomock 不支持设置 uuidRepresentation,因此无法解码/编码 UUID。我不知道有什么解决方法可以在不修补 mongomock 的情况下起作用。
参见:https://github.com/mongomock/mongomock/issues/745
mongomock 中的确切代码:https://github.com/mongomock/mongomock/blob/4.2.0/mongomock/codec_options.py#L66