【发布时间】:2022-07-28 08:11:37
【问题描述】:
我一直在努力模拟典型的异步数据库连接设置:
async with aiomysql.create_pool(...) as pool:
async with pool.acquire() as connection:
async with connection.cursor() as cursor:
await connection.begin()
...
我第一次尝试测试函数看起来像这样:
async def test_database(mocker: pytest_mock.MockerFixture):
context = mocker.AsyncMock()
pool = mocker.AsyncMock()
connection = mocker.AsyncMock()
cursor = mocker.AsyncMock()
cursor.fetchall.return_value = [{'Database': 'information_schema'}]
cursor.fetchone.return_value = {'COUNT(*)': 0}
cursor.rowcount = 0
connection.cursor.return_value.__aenter__.return_value = cursor
pool.acquire.return_value.__aenter__.return_value = connection
context.__aenter__.return_value = pool
mocker.patch('aiomysql.create_pool', return_value=context)
async with aiomysql.create_pool() as p:
async with p.acquire() as c:
async with c.cursor() as cur:
await c.begin()
如果您因缺少__aenter__s 而收到AttributeErrors,那么这篇文章适合您。
【问题讨论】:
标签: python-3.x database pytest pytest-mock