[Python] mock motor AsyncIOMotorClient with uuid settings

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I have AsyncIOMotorClient code as below.

    def get_client():
    """
    Get Client.

    Get the client for the database connection.
    """
    return motor.motor_asyncio.AsyncIOMotorClient(
    os.getenv(
    "DB_CONN_STR",
    "mongodb://user:pass@127.0.0.1:27017"
    ),
    uuidRepresentation='standard',
    )


    in this, I am setting uuidRepresentation='standard' to make sure UUID will parse properly.

    I use mongomock-motor and mock the client as below.

    from mongomock_motor import AsyncMongoMockClient

    class MockSession():
    client = AsyncMongoMockClient(
    uuidRepresentation='standard',
    )

    def override_get_session():
    return MockSession()


    app.dependency_overrides[get_session] = override_get_session


    When I run testcase where it need UUID, it fail with below error.

    app_client = <starlette.testclient.TestClient object at 0x10344a9d0>

    def test_valid_payload(app_client):
    payload = {
    "country": "ARE",
    "email": "test@test.com",
    "first_name": "TEst",
    "last_name": "Surname",
    "password": "PAssword@123",
    "phone": "+911234567890"
    }
    > response = app_client.post("/doctor/signup", json=payload)

    tests/integration/doctor/test_post_signup.py:123:
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    venv/lib/python3.11/site-packages/starlette/testclient.py:597: in post
    return super().post(
    venv/lib/python3.11/site-packages/httpx/_client.py:1144: in post
    return self.request(
    venv/lib/python3.11/site-packages/starlette/testclient.py:488: in request
    return super().request(
    venv/lib/python3.11/site-packages/httpx/_client.py:825: in request
    return self.send(request, auth=auth, follow_redirects=follow_redirects)
    venv/lib/python3.11/site-packages/httpx/_client.py:914: in send
    response = self._send_handling_auth(
    venv/lib/python3.11/site-packages/httpx/_client.py:942: in _send_handling_auth
    response = self._send_handling_redirects(
    venv/lib/python3.11/site-packages/httpx/_client.py:979: in _send_handling_redirects
    response = self._send_single_request(request)
    venv/lib/python3.11/site-packages/httpx/_client.py:1014: in _send_single_request
    response = transport.handle_request(request)
    venv/lib/python3.11/site-packages/starlette/testclient.py:381: in handle_request
    raise exc
    venv/lib/python3.11/site-packages/starlette/testclient.py:378: in handle_request
    portal.call(self.app, scope, receive, send)
    venv/lib/python3.11/site-packages/anyio/from_thread.py:290: in call
    return cast(T_Retval, self.start_task_soon(func, *args).result())
    /opt/homebrew/Cellar/python@3.11/3.11.10/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/_base.py:456: in result
    return self.__get_result()
    /opt/homebrew/Cellar/python@3.11/3.11.10/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/_base.py:401: in __get_result
    raise self._exception
    venv/lib/python3.11/site-packages/anyio/from_thread.py:221: in _call_func
    retval = await retval_or_awaitable
    venv/lib/python3.11/site-packages/fastapi/applications.py:1054: in __call__
    await super().__call__(scope, receive, send)
    venv/lib/python3.11/site-packages/starlette/applications.py:113: in __call__
    await self.middleware_stack(scope, receive, send)
    venv/lib/python3.11/site-packages/starlette/middleware/errors.py:187: in __call__
    raise exc
    venv/lib/python3.11/site-packages/starlette/middleware/errors.py:165: in __call__
    await self.app(scope, receive, _send)
    venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py:62: in __call__
    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
    venv/lib/python3.11/site-packages/starlette/_exception_handler.py:62: in wrapped_app
    raise exc
    venv/lib/python3.11/site-packages/starlette/_exception_handler.py:51: in wrapped_app
    await app(scope, receive, sender)
    venv/lib/python3.11/site-packages/starlette/routing.py:715: in __call__
    await self.middleware_stack(scope, receive, send)
    venv/lib/python3.11/site-packages/starlette/routing.py:735: in app
    await route.handle(scope, receive, send)
    venv/lib/python3.11/site-packages/starlette/routing.py:288: in handle
    await self.app(scope, receive, send)
    venv/lib/python3.11/site-packages/starlette/routing.py:76: in app
    await wrap_app_handling_exceptions(app, request)(scope, receive, send)
    venv/lib/python3.11/site-packages/starlette/_exception_handler.py:62: in wrapped_app
    raise exc
    venv/lib/python3.11/site-packages/starlette/_exception_handler.py:51: in wrapped_app
    await app(scope, receive, sender)
    venv/lib/python3.11/site-packages/starlette/routing.py:73: in app
    response = await f(request)
    venv/lib/python3.11/site-packages/fastapi/routing.py:301: in app
    raw_response = await run_endpoint_function(
    venv/lib/python3.11/site-packages/fastapi/routing.py:212: in run_endpoint_function
    return await dependant.call(**values)
    src/noveraapi/routers/doctor.py:64: in create_doctor
    new_doctor = await collection.insert_one(
    venv/lib/python3.11/site-packages/mongomock_motor/__init__.py:43: in wrapper
    return getattr(proxy_source, method_name)(*args, **kwargs)
    venv/lib/python3.11/site-packages/mongomock/collection.py:497: in insert_one
    return InsertOneResult(self._insert(document, session), acknowledged=True)
    venv/lib/python3.11/site-packages/mongomock_motor/patches.py:58: in wrapper
    return fn(data, *args, **kwargs)
    venv/lib/python3.11/site-packages/mongomock/collection.py:552: in _insert
    BSON.encode(data, check_keys=check_keys)
    venv/lib/python3.11/site-packages/bson/__init__.py:1429: in encode
    return cls(encode(document, check_keys, codec_options))
    venv/lib/python3.11/site-packages/bson/__init__.py:1050: in encode
    return _dict_to_bson(document, check_keys, codec_options)
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    cls = <class 'bson.binary.Binary'>, uuid = UUID('097cb7d0-1b2a-43a5-8686-a3525615d254'), uuid_representation = 0

    @classmethod
    def from_uuid(
    cls: Type[Binary], uuid: UUID, uuid_representation: int = UuidRepresentation.STANDARD
    ) -> Binary:
    """Create a BSON Binary object from a Python UUID.

    Creates a :class:`~bson.binary.Binary` object from a
    :class:`uuid.UUID` instance. Assumes that the native
    :class:`uuid.UUID` instance uses the byte-order implied by the
    provided ``uuid_representation``.

    Raises :exc:`TypeError` if `uuid` is not an instance of
    :class:`~uuid.UUID`.

    :param uuid: A :class:`uuid.UUID` instance.
    :param uuid_representation: A member of
    :class:`~bson.binary.UuidRepresentation`. Default:
    :const:`~bson.binary.UuidRepresentation.STANDARD`.
    See :ref:`handling-uuid-data-example` for details.

    .. versionadded:: 3.11
    """
    if not isinstance(uuid, UUID):
    raise TypeError("uuid must be an instance of uuid.UUID")

    if uuid_representation not in ALL_UUID_REPRESENTATIONS:
    raise ValueError(
    "uuid_representation must be a value from bson.binary.UuidRepresentation"
    )

    if uuid_representation == UuidRepresentation.UNSPECIFIED:
    > raise 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."
    )
    E 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.

    venv/lib/python3.11/site-packages/bson/binary.py:272: ValueError


    how to make uuidRepresentation working in mock client ?

    Continue reading...

Compartilhe esta Página