A Mocked Database Lets Broken SQL Pass, an In-Memory Database Runs It

In progress Testing Python

Code that talks to a database can be tested two ways: replace the connection with a mock that returns canned answers, or run against a real database engine kept in memory. The mock is faster and controls edge cases precisely, but it never executes your SQL, so a typo, a wrong column or a violated constraint still passes. For most small and medium apps, an in-memory SQLite database gives real queries and constraints at nearly mock speed.

The Trade-Off

Mock In-memory database (SQLite :memory:)
Executes your SQL no yes
Enforces constraints (unique, foreign keys) no yes (enable PRAGMA foreign_keys = ON in SQLite)
Speed fastest fast; no disk, no server
Edge cases (timeouts, connection loss) easy to simulate hard
Fidelity to production (PostgreSQL) none high for standard SQL, not for vendor features
Leftovers none none: the database vanishes with the process

Keep the Database Choice Configurable

Tests can only swap the database if the app reads its location from configuration:

  • take the path from an environment variable with a relative fallback (os.getenv("SQLITE_DATABASE", "app.db")) instead of building it from the source tree's absolute location, which breaks when tests run from another directory or in CI;
  • switch engines from the environment too: if DATABASE_URL (or POSTGRES_HOST) is set, connect to PostgreSQL; otherwise use SQLite. Local runs need nothing installed, containers get the production engine.

References

Review cards

Flashcard Why can a test with a mocked database pass when the SQL has a typo?

The mock never executes the SQL: it returns whatever the test told it to, so typos, wrong columns and violated constraints all pass.

Flashcard What does an in-memory SQLite database catch that a mock can't?

Broken queries and constraint violations: it runs the real SQL and enforces unique and foreign keys (after PRAGMA foreign_keys = ON), at nearly mock speed, with nothing left behind.

Flashcard How should an app pick its database so tests can swap it?

From the environment: the SQLite path from a variable with a relative fallback (os.getenv("SQLITE_DATABASE", "app.db")), and PostgreSQL when DATABASE_URL is set, SQLite otherwise.

Quiz Which test is a mock better suited for than an in-memory database?
  • How the app handles a connection timeout
  • A query that joins two tables
  • A unique constraint on the email column
  • An insert followed by a select

Timeouts and connection loss are easy to simulate with a mock and hard with a real engine. Anything that reads or writes data needs real queries.