[Python] Mock asyncio.sleep to be faster in unittest

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    I want to mock asyncio.sleep to shorten the delay, e.g. by a factor of 10, to speed up my tests while also trying to surface any possible race conditions or other bugs as a crude sanity check. However I cannot figure out, if sut.py and test.py both use import asyncio, how to patch sleep only in sut.py but not test.py. For example, if I run the following:

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

    @pytest.mark.asyncio
    @patch("sut.asyncio.sleep")
    async def test(mock_asyncio_sleep):
    print(asyncio.sleep)


    It prints an AsyncMock instance rather than the actual sleep function.

    The issue is then I cannot simulate the sleep in test.py:

    @pytest.mark.asyncio
    @patch("sut.asyncio.sleep")
    async def test(mock_asyncio_sleep):
    async def fast_sleep(t):
    await asyncio.sleep(t / 10)
    mock_asyncio_sleep.side_effect = fast_sleep

    Continue reading...

Compartilhe esta Página