asynctest
asynctest copied to clipboard
Patching a coroutine fails if it's imported directly in module being tested
We were exploring aio_pika and we had this test:
class OurTest(TestCase):
async def test_one(self):
with asynctest.mock.patch('aio_pika.robust_connect') as mcr:
await AdapterClass.create(**options) #options is a dict declared prior to test class
mcr.assert_called_once_with(**options)
The code under test is like:
from aio_pika import connect_robust
class OurClass(object):
def _init__(self, host, port, user, pass):
self.host = host
#etc..
self.connection = None
@classmethod
async def create(cls, host, port, user, pass):
_instance = cls(host, port, user, pass)
self.connection = await connect_robust(host=host, port=port, ...etc...)
As it is, the assertion will fail. But if we modify the class under test import to
import aio_pika
and modify the call further to
self.connection = await aio_pika.connect_robust(.....)
....test will succeed.
I think this is expected behaviour in line with unittest.mock, as in: http://www.voidspace.org.uk/python/mock/patch.html#id1