Martiusweb / asynctest

Enhance the standard unittest package with features for testing asyncio libraries
https://asynctest.readthedocs.org/
Apache License 2.0
309 stars 41 forks source link

Trouble with mocking aiopg #146

Open DrMartiner opened 4 years ago

DrMartiner commented 4 years ago

Hi everyone,

Could u help me to mock aiopg's connection pool? I have error object MagicMock can't be used in 'await' expression

import asynctest
import pytest
from asyncmock import AsyncMock

pytestmark = pytest.mark.asyncio

@pytest.yield_fixture(scope="function")
def pg_pool():
    pg_pool_mock = asynctest.CoroutineMock()
    pg_pool_mock.acquire.__aenter__.cursor.__aenter__.begin.return_value = AsyncMock()

    return pg_pool_mock

async def test_do_something(pg_pool):
    await do_something(pg_pool)
import asyncio

import aiopg

async def main():
    async with aiopg.create_pool("DSN string") as pg_pool:
        await asyncio.gather(*[do_something(pg_pool) for i in range(10)])

async def do_something(pg_pool):
    async with pg_pool.acquire() as connection:
        async with connection.cursor() as cursor:
            transaction = await cursor.begin()  # object MagicMock can't be used in 'await' expression
            try:
                await cursor.execute("...", [])
                await transaction.commit()
            except Exception as e:
                await transaction.rollback()

if __name__ == '__main__':
    asyncio.run(main())

Best regards, Alex