dialoguemd / fastapi-sqla

SQLAlchemy extension for FastAPI with support for pagination, asyncio, SQLModel and pytest, ready for production.
MIT License
172 stars 11 forks source link

Pytest override session dependency #153

Open foarsitter opened 1 week ago

foarsitter commented 1 week ago

When using the fastapi.testclient.TestClient with pytest, the app doesn't use the session fixture resulting in writes to the database.

To solve this problem, pytest needs to tell the app to use the same session as used for testing. This can be done by using dependency_overrides.

@pytest.fixture(autouse=True)
def _app_session(app, session):
    app.dependency_overrides[fastapi_sqla.sqla.default_session_dep] = lambda: session

At least, this is how I solved the problem. Is there a beter approach or should I send a PR to document this?

arththebird commented 1 week ago

Hi @foarsitter! Overriding the dependency shouldn't be necessary since we patch the engine factory used to generate the sessions. Can you try updating your test so that the session fixture is before the app fixture in the test function signature, so that it's loaded before the app by pytest?

foarsitter commented 1 week ago

My app is a session scoped fixture, changing it to function scoped and adding session as dependency raises on https://github.com/dialoguemd/fastapi-sqla/blob/4fc7c755a7c14c82845d8a6424e03f1dc67256e2/fastapi_sqla/sqla.py#L62 with

AttributeError: 'Connection' object has no attribute 'connect'. Did you mean: 'connection'?