[issue37015] Fix asyncio mock warnings

Karthikeyan Singaravelan report at bugs.python.org
Wed May 22 14:53:39 EDT 2019


Karthikeyan Singaravelan <tir.karthi at gmail.com> added the comment:

patching _accept_connection2 attribute on loop object seems to return an AsyncMock.

➜  cpython git:(master) ✗ cat ../backups/bpo37015.py
import asyncio
from unittest.mock import patch
with patch.object(asyncio.get_event_loop(), '_accept_connection2') as f:
    print(f)
    f()
➜  cpython git:(master) ✗ ./python.exe ../backups/bpo37015.py
<AsyncMock name='_accept_connection2' id='4361411632'>
../backups/bpo37015.py:5: RuntimeWarning: coroutine 'AsyncMockMixin._mock_call' was never awaited
  f()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback


Relevant test

    def test_accept_connection_multiple(self):
        sock = mock.Mock()
        sock.accept.return_value = (mock.Mock(), mock.Mock())
        backlog = 1
        # Mock the coroutine generation for a connection to prevent
        # warnings related to un-awaited coroutines.
        mock_obj = mock.patch.object
        with mock_obj(self.loop, '_accept_connection2') as accept2_mock:
            print(f"{accept2_mock=}")
            accept2_mock.return_value = None
            with mock_obj(self.loop, 'create_task') as task_mock:
                task_mock.return_value = None
                self.loop._accept_connection(
                    mock.Mock(), sock, backlog=backlog)
        self.assertEqual(sock.accept.call_count, backlog)

When I specify new value which defaults to DEFAULT as Mock() then there is no AsyncMock. Same can be done in test and the warnings go away. My suspicion is that if there is a loop object with _accept_connection2 earlier in Python 3.7 <MagicMock name='_accept_connection2'> is returned by patch.object but now it returns an <AsyncMock name='_accept_connection2'> instead

# use explicit mock

import asyncio
from unittest.mock import patch, Mock

with patch.object(asyncio.get_event_loop(), '_accept_connection2', Mock()) as f:
    print(f)
    f()

➜  cpython git:(master) ✗ ./python.exe ../backups/bpo37015.py
<Mock id='4342533248'>

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37015>
_______________________________________


More information about the Python-bugs-list mailing list