mercredi 6 février 2019

How can I mock a call to 'aiomysql.create_pool'?

I want to mock a call to aiomysql.create_pool for some Tornado tests.

My customized web module has this class:

from aiomysql import create_pool

import tornado.web


class CustomApplication(tornado.web.Application):
    async def _conf_mysql(self) -> None:
        kwargs = {...}
        pool = await create_pool(**kwargs)
        # Other code

and I want to call it within the get_app of my tornado.testing.AsyncHTTPTestCase class.

I've already tried these two ways:

First attempt

@mock.patch('aiomysql.create_pool', asyncio.coroutine(mock.MagicMock(return_value=None)))
@tornado.testing.gen_test
async def get_app(self):
    app = CustomApplication([
        (r"/test", TestRequestHandler),
    ])
    await app._conf_mysql()

Second attempt

@tornado.testing.gen_test
async def get_app(self):
    aiomysql.create_pool = asyncio.coroutine(mock.MagicMock(return_value=None))
    app = CustomApplication([
        (r"/test", TestRequestHandler),
    ])
    await app._conf_mysql()

but both of them give me back this error: pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'http://localhost'"). They still seem to try to establish a real connection to a real database that does not exist of course.

What's the best way to mock the call to aiomysql.create_pool with a customized class?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire