Why is my assert_called_once_with giving different ids when calling a mocked async method?

398 Views Asked by At

I am struggling with an assert_called_once_with call when mocking an async method in a class.

I have the following code that needs to be tested :

In class_under_test.py :

class ClassUnderTest():    
    def func_to_be_tested(self, x, y):
        loop = asyncio.new_event_loop()
        task = loop.create_task(self.func_to_be_mocked(x, y))
        loop.run_until_complete(task)
    
    async def func_to_be_mocked(self, x, y):
        # does something doesn't matter what

And here is the code and pseudo code (for certain lines) of the test : In test_class_under_test.py :

class Tests():
    @pytest.mark.asyncio
    def test_func_to_be_tested(self, mocker):
        test_class = ClassUnderTest()

        mocked_func = mocker.patch("class_under_test.ClassUnderTest.func_to_be_mocked")
        mocked_func.return_value = mocked_func
    
        mocked_event_loop = mocker.patch("asyncio.AbstractEventLoop")
        mocked_task = mocker.patch("asyncio.Task")
    
        mocked_asyncio_new_event_loop = mocker.patch("asyncio.new_event_loop", return_value=mocked_event_loop)
        mocked_event_loop.create_task = mocker.patch("asyncio.AbstractEventLoop.create_task", return_value=mocked_task)
            
        test_class.func_to_be_tested(1, 2)
  
        mocked_event_loop.create_task.assert_called_once_with(mocked_func_to_be_mocked(1, 2))

Right now, I am struggling with the last line of my test which is making a assert_called_once_with call.

When runnin my test, I get the following output :

AssertionError: expected call not found.
Expected: create_task(<coroutine object AsyncMockMixin._execute_mock_call at 0x7fa0d5886840>)
Actual: create_task(<coroutine object AsyncMockMixin._execute_mock_call at 0x7fa0d5886ac0>)

I can see the parameter is of the valid type, but why are the IDs different? Shouldn't they have the same idea since it's the same mock?

Anyone knows why the ids are different?

0

There are 0 best solutions below