[Python] Python How to patch module with assert_called

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

  1. Stack

    Stack Membro Participativo

    Im trying to create a mocked AsyncOpenSearch and all its methods, so that in my unittest when I use AsyncOS.ping() it will assure me that AsyncOpenSearch.native_ping has been called or awaited

    How should I patch the whole AsyncOpenSearch and native_ping? assert_await or assert_called fails, but the print from native_ping is printed.

    import pytest
    from unittest.mock import AsyncMock, patch
    import asyncio

    class OSConfig:
    pass

    # Different module: ops.my_module.AsyncOpenSearch
    # class AsyncOpenSearch:
    # async def native_ping(self):
    # print("I have been called!")


    class AsyncOS:
    def __init__(self, config: OSConfig):
    self.client: AsyncOpenSearch = AsyncOpenSearch()

    async def ping(self):
    await self.client.native_ping()


    @pytest.mark.asyncio
    async def test_ping_called():
    with patch("ops.my_module.AsyncOpenSearch", new_callable=AsyncMock) as os_mock:
    async_os = AsyncOS(config=OSConfig())
    await async_os.ping()

    #os_mock.native_ping.assert_called() # doesn't work
    os_mock.native_ping.assert_awaited() # doesn't work

    Continue reading...

Compartilhe esta Página