AsyncSession.scalars returns an instance of ScalarResult. Mock async session with AsyncMock
and mock return value of AsyncSession.scalars
with a mocked instance of ScalarResult
by autospeccing it.
from unittest import mock
async with session_maker() as session:
session_mock = mock.AsyncMock(spec=session,
**{'scalars.return_value': mock.create_autospec(
spec=ScalarResult, instance=True)})
await session_mock.scalars(...)
Mocking the return value of AsyncSession.scalars
is not enough. What you are interested in mocking the final result to get the expected value. So, you have to mock the methods of ScalarResult
as well.
expected_value = ['result_one', 'result_two', 'result_three']
session_mock = mock.AsyncMock(
spec=session, **{'scalars.return_value': mock.create_autospec(spec=ScalarResult,
instance=True),
'scalars.return_value.all.return_value': expected_value})
result = await session_mock.scalars(...)
assert result.all == expected_value
session_mock = mock.AsyncMock(
spec=session, **{'scalars.return_value': mock.create_autospec(spec=ScalarResult,
instance=True),
'scalars.return_value.one_or_none.return_value': None})
result = await session_mock.scalars(...)
assert result.one_or_none is None