Search code examples
mockingpytestpython-asynciopython-unittestpatch

Pytest: patching the function invoked in another task


I have code as follows:

import asyncio
import pytest

from unittest.mock import patch


def another_func():
    pass

class A:
    async def func(self):
        print(f"!!!!!!!!!!!{another_func}!!!!!!!!!!!")
        another_func()
        
    async def run(self):
        await self.func()
        asyncio.create_task(self.func())
        


@pytest.mark.asyncio
@patch("main.another_func")
async def test_otg_test_low_disk_space_handler_fired(patched):
    a = A()
    await a.run()

The result output looks as follows:

main.py !!!!!!!!!!!<MagicMock name='another_func' id='139827220171360'>!!!!!!!!!!!
!!!!!!!!!!!<function another_func at 0x7f2c0fdfd2d0>!!!!!!!!!!!

I wonder if there is a way to properly patch the another_func to see the MagicMock also as the second output as well. I think, asyncio.create_task somehow "forgets" to take the mocks and patches inside its execution context.

Any help would be appreciated!


Solution

  • Ok, the answer is named monkeypatch. This guy finally allowed me to mock the function even in another task. Finding solution took me half a day, so I leave it here for anyone needed.

    The working code is as follows:

    import asyncio
    import pytest
    
    from unittest.mock import MagicMock
    
    
    def another_func():
        pass
    
    class A:
        async def func(self):
            print(f"!!!!!!!!!!!{another_func}!!!!!!!!!!!")
            another_func()
            
        async def run(self):
            await self.func()
            asyncio.create_task(self.func())
            
    
    
    @pytest.mark.asyncio
    async def test_func(monkeypatch):
        a = A()
        mock = MagicMock()
        monkeypatch.setattr("main.another_func", mock)
        await a.run()
    

    and the awaited result is as follows:

    main.py !!!!!!!!!!!<MagicMock id='139952231369168'>!!!!!!!!!!!
    !!!!!!!!!!!<MagicMock id='139952231369168'>!!!!!!!!!!!