How to access the database from unit test in Fast API?

Viewed 3033

I'm struggling accessing SQLAlchemy while unit testing in Fast API.

def test_successful_register_ios():
    response = client.post("/register/",headers={},json={})
    assert response.status_code == 201
    device = get_db().query(Device).get("a1")
    assert device.expires_at == mydate

AttributeError: 'generator' object has no attribute 'query'

In my test class I'm applying all the overrides:

from database.database import Base
from main import app, get_db

settings = Settings()
engine = create_engine(settings.sqlalchemy_database_uri)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all(bind=engine)
client = TestClient(app)

def override_get_db():
    try:
        db = TestingSessionLocal()
        yield db
    finally:
        db.close()

app.dependency_overrides[get_db] = override_get_db

I don't think get_db().query(Device).get("a1") is the right way to do it. But I'm quite stuck and the documentation doesn't cover this case.

1 Answers

When you get the error AttributeError: 'generator' object has no attribute 'query' python is telling you that the result of get_db() is not an sqlalchemy session object but rather a generator that yields a session object.

Try calling next() on your generator to get a session out of the generator.

def test_successful_register_ios():
    response = client.post("/register/",headers={},json={})
    assert response.status_code == 201
    device = next(get_db()).query(Device).get("a1")
    assert device.expires_at == mydate
Related