FastAPI Dependency Injection Not Resolving Session in Unit Tests
I've searched everywhere and can't find a clear answer. I've been struggling with this for a few days now and could really use some help... I'm facing an issue with unit testing in FastAPI where my dependency injection for a database session isn't resolving correctly. I have the following setup for my FastAPI application: ```python from fastapi import FastAPI, Depends from sqlalchemy.orm import Session, sessionmaker from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine DATABASE_URL = 'sqlite+aiosqlite:///./test.db' Base = declarative_base() engine = create_async_engine(DATABASE_URL, echo=True) async def get_db(): async with AsyncSession(engine) as session: yield session app = FastAPI() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) @app.post('/users/') async def create_user(name: str, db: Session = Depends(get_db)): user = User(name=name) db.add(user) await db.commit() return user ``` Now, when I run my unit tests using `pytest`, I'm trying to mock the `get_db` dependency, but I'm getting the following error: ``` E sqlalchemy.exc.InvalidRequestError: This session is not bound to a mapper; it is in 'detached' state. ``` Here's how I attempted to set up my test: ```python import pytest from fastapi.testclient import TestClient from myapp import app, get_db from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine @pytest.fixture(scope='module') def test_app(): client = TestClient(app) yield client @pytest.fixture(scope='module') def db_session(): test_engine = create_engine('sqlite:///:memory:', echo=True) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=test_engine) session = SessionLocal() yield session session.close() @pytest.fixture(autouse=True) def override_get_db(db_session): yield db_session def test_create_user(test_app): response = test_app.post('/users/', json={'name': 'John Doe'}) assert response.status_code == 200 assert response.json()['name'] == 'John Doe' ``` In the `override_get_db` fixture, I'm yielding the `db_session`, but it seems like the session is not being bound correctly. I suspect the issue lies in how I'm handling the session lifecycle within the test context. Any advice on how to properly mock the database session for testing in this case would be greatly appreciated. I'm currently using FastAPI version 0.68.1 and SQLAlchemy version 1.4.22. For context: I'm using Python on Windows. Am I missing something obvious? Any pointers in the right direction?