Point the App at a Test Database Before It Imports Its Connection
An app that opens its database connection at import time reads its settings once, when the module is first imported. A test suite that wants a separate database must set the environment variable before that import happens, in conftest.py, or the tests run against the development database and leave their data behind.
Read the Location from the Environment
# config/database.py
import os
from sqlite3 import connect
db_name = os.getenv("SQLITE_DATABASE", "app.db")
conn = connect(db_name, check_same_thread=False)
curs = conn.cursor()
Override It First in conftest.py
# tests/conftest.py
import os
os.environ["SQLITE_DATABASE"] = ":memory:" # before anything imports config.database
import pytest
from config.database import conn, curs
from data.books import seed_db
@pytest.fixture(autouse=True)
def reset_db():
curs.execute("DELETE FROM book")
conn.commit()
seed_db()
Pytest loads conftest.py before collecting test modules, so the override wins. :memory: keeps the database in RAM: fast, and gone when the process ends. The autouse fixture resets the data before every test, so no test depends on another's leftovers.
References
- FastAPI MOC - hub for FastAPI notes.
- Relative Template Directories Resolve Against the Working Directory, Not the Source File - the other setting that breaks when tests run from another context.
- pytest documentation: conftest.py - when conftest files load.
- Python documentation: sqlite3 in-memory databases -
:memory:behaviour. - SQLModel documentation: Test Applications with FastAPI and SQLModel - an in-memory SQLite engine with
StaticPooland an overridden session dependency (FastAPI's own "Testing a Database" page now points here; checked 2026-11-24).
Review cards
Flashcard In conftest.py, why must SQLITE_DATABASE be set before importing config.database?
The module opens its connection at import time and reads the variable only then. Set it after the import and the tests run against the development database.
Flashcard Why does a second connect(":memory:") not see the test data?
Each connection to :memory: opens its own new, empty database. The pattern only works while the app shares one connection; with SQLAlchemy, use a StaticPool.