Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock async SQLAlchemy 2.0 #360

Open
tamio96 opened this issue Jun 29, 2023 · 4 comments
Open

Mock async SQLAlchemy 2.0 #360

tamio96 opened this issue Jun 29, 2023 · 4 comments
Labels
bug Something isn't working

Comments

@tamio96
Copy link

tamio96 commented Jun 29, 2023

Describe the bug
Hi, I start to apply async sqlalchemy to my project and got stuck as mocking an AsyncSession
To Reproduce
CRUD function:

async def get_record_by_id(db: AsyncSession, user_id: int) -> Optional[sql_models.User]:
    result = await db.execute(select(sql_models.User).filter(sql_models.User.id == user_id))
    result = result.scalars().first()
    return result

Unit test function:

@pytest.mark.asyncio
async def test_get_investment_record_by_id():
    mock_result = AlchemyMagicMock()
    mock_result.scalars.return_value.first.return_value = user_obj

    mock_db = AlchemyMagicMock()
    mock_db.execute.return_value = mock_result

    user_id = 1234
    await get__record_by_id(mock_db, user_id)
    mock_db.execute.assert_called_with(select(sql_models.User).filter(sql_models.User.id == user_id))

Outcome:

E       TypeError: object AlchemyMagicMock can't be used in 'await' expression

Expected behavior

  • AlchemyMagicMock support async

Desktop (please complete the following information):

  • OS: Ubuntu
  • Version 20.04
@tamio96 tamio96 added the bug Something isn't working label Jun 29, 2023
@edjeffery
Copy link

I would also find this feature useful 👍

@willcipriano
Copy link

I also would like this

@fabrice-toussaint
Copy link

Any updates on this?

@tamioEcoligo
Copy link

tamioEcoligo commented Feb 24, 2024

hi, I share an alternative way to mock AsyncSession

from unittest.mock import AsyncMock
from unittest.mock import MagicMock

@pytest.mark.asyncio
async def test_get_investment_record_by_id():
    mock_result = MagicMock()
    mock_result.scalars.return_value.first.return_value = user_obj

    mock_db = AsyncMock(return_value=asyncio.Future())
    mock_db.execute.return_value = mock_result

    user_id = 1234
    await get__record_by_id(mock_db, user_id)
    mock_db.execute.assert_called_with(select(sql_models.User).filter(sql_models.User.id == user_id))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

5 participants