mock.py 1.2 KB

1234567891011121314151617181920212223242526272829
  1. from unittest.mock import AsyncMock, MagicMock
  2. def mock_async_session():
  3. """Create a mock for async_session that supports async context manager usage
  4. without producing 'coroutine was never awaited' warnings.
  5. Using a plain AsyncMock as the session causes warnings because any attribute
  6. access on AsyncMock implicitly creates a coroutine. Third-party code (pydantic,
  7. requests, inspect, etc.) accesses attributes without awaiting them, triggering:
  8. RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited
  9. The fix: use MagicMock as the session (no spurious coroutines on attribute access),
  10. but explicitly set the async methods that need to be awaitable.
  11. """
  12. session = MagicMock()
  13. # exec returns a Result whose .all()/.first()/etc. are sync — use MagicMock as
  14. # the return value so that chained sync calls don't spawn unawaited coroutines.
  15. session.exec = AsyncMock(return_value=MagicMock())
  16. session.get = AsyncMock()
  17. session.refresh = AsyncMock()
  18. session.flush = AsyncMock()
  19. session.commit = AsyncMock()
  20. session.rollback = AsyncMock()
  21. cm = MagicMock()
  22. cm.__aenter__ = AsyncMock(return_value=session)
  23. cm.__aexit__ = AsyncMock(return_value=False)
  24. return cm