1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] UUID save issues with mongoengine and mongomock

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página