Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 3

Why Mocks Lie About Databases

Discover why mock objects and in-memory SQLite engines hide real production failures, and how testing against a real PostgreSQL engine exercises the constraints production enforces.

Contentsand lesson path

What you will learn

  • Run integration tests against a disposable PostgreSQL instance with migrations applied and per-test isolation through transaction rollback or truncation.

Prerequisites: Software Testing Fundamentals, Data Access with SQLAlchemy

01. Why it matters

Here is a common story. The unit tests run in two seconds and all pass, yet soon after the deploy the service fails with a database error. A foreign key rejected a row, a unique index rejected a duplicate, or a renamed column no longer existed. The tests passed because they never asked the database.

When you test database code with mock objects, mock repositories or an in-memory SQLite database, you do not test how your application works with its real database. You test your own assumptions about how that database behaves. PostgreSQL is not a simple key-value store: it has its own type system, integrity rules, SQL dialect and concurrency control, and each of them can reject what your code sends.

In this lesson you will see where mocks and in-memory substitutes give wrong answers about database code. You will look at the engine rules (constraint checks, type conversions and transaction behaviour) that only a real database engine checks. These failure modes are the reason the next lessons run integration tests against a disposable PostgreSQL database.

02. The illusion of the mock object

In standard unit testing tutorials, developers are often instructed to mock the database session or repository interface using tools like unittest.mock.MagicMock or AsyncMock. The rationale seems appealing at first: unit tests stay fast because they perform no network I/O, require no external processes, and run anywhere without Docker or local database credentials.

Consider what actually occurs when you mock an ORM session or database query. You configure the mock object to return pre-baked data whenever a specific method is called:

Python · unit test using a mocked database session (fragile)
from unittest.mock import MagicMock

from sqlalchemy import select

from app.models import Book


def get_book_by_title(session, title: str):
    # If a migration renames the column but the model still maps `title`,
    # or the filter uses the wrong column, this query fails or returns
    # the wrong row in PostgreSQL, but the mocked test below still passes.
    return session.scalars(select(Book).where(Book.title == title)).first()


def test_get_book_with_mock():
    mock_session = MagicMock()
    fake_book = Book(id=1, title="Refactoring", year=1999)
    mock_session.scalars.return_value.first.return_value = fake_book

    result = get_book_by_title(mock_session, "Refactoring")
    assert result.title == "Refactoring"
    assert result.year == 1999

Notice the fundamental flaw in test_get_book_with_mock: the mocked scalars().first() chain returns fake_book regardless of what query was constructed. If a developer misspells a column name in the filter expression, joins the wrong table, or passes an incompatible parameter type, the mock session returns fake_book anyway. You are testing your mock configuration rather than your database logic.

Mocks also completely ignore database side effects. When your code executes session.add(entity) or session.flush(), a mock session records that a method named add was called. It cannot tell you whether an identical email address violates a unique constraint, whether a foreign key points to a nonexistent user ID, or whether a mandatory non-null column was omitted. A mock raises an integrity error only when you configure it to.

03. The in-memory SQLite trap

Some teams try to keep tests fast without pure mocks by running them against an in-memory SQLite database (sqlite:///:memory:). SQLite is an excellent embedded database, but when production runs PostgreSQL, the two engines differ in dialect and behaviour.

Here are five differences where a SQLite test suite can give the wrong answer:

  • JSON queries. PostgreSQL has a binary jsonb type with GIN indexes and the @> and ? operators. SQLite has JSON functions, the -> and ->> operators and (since 3.45) a binary JSONB storage format, but not PostgreSQL's containment and existence operators (@>, ?, ?|) or GIN indexes. Those queries fail with a syntax error or must be rewritten.
  • Foreign keys. PostgreSQL enforces every foreign key, checking it at the end of each statement unless the constraint is declared deferrable. SQLite does not enforce foreign keys unless each connection runs PRAGMA foreign_keys = ON.
  • Concurrency and row locks. PostgreSQL has row-level locks (SELECT ... FOR UPDATE) and MVCC snapshots. SQLite locks the whole database file for writes and has no FOR UPDATE: raw SQL containing it is a syntax error, and SQLAlchemy silently leaves with_for_update() out of the SQL it sends to SQLite.
  • Time zones and dates. PostgreSQL has timestamptz with time zone offsets and microsecond arithmetic. SQLite stores timestamps as text or numbers, so time zone arithmetic behaves differently.
  • Case sensitivity. In PostgreSQL, LIKE is case-sensitive, and case-insensitive search needs ILIKE. SQLite LIKE ignores case for ASCII letters by default and has no ILIKE keyword (SQLAlchemy's ilike() hides this by compiling to lower(x) LIKE lower(y)).

Consider LIKE and foreign keys. If your SQLAlchemy query uses .where(Book.title.like("%python%")), SQLite matches a book titled "Python Tricks", because its LIKE ignores ASCII case, while PostgreSQL does not match it. The SQLite test passes and production returns nothing. (ilike() would behave the same on both, because SQLAlchemy rewrites it for SQLite; raw SQL containing ILIKE fails on SQLite.) Similarly, if you write code that accidentally inserts an orphan order record without an existing customer ID, SQLite will accept the write silently unless you manually executed PRAGMA foreign_keys = ON on the SQLite connection. In production, PostgreSQL rejects the insert with a foreign key violation (psycopg raises ForeignKeyViolation, which SQLAlchemy wraps in IntegrityError), and the transaction is aborted.

04. Invariants only the real engine enforces

A production database enforces rules that span several operations and concurrent transactions. A test double cannot reproduce them reliably:

  • Unique and exclusion constraints. When two concurrent requests try to reserve the same username or the same meeting-room slot, PostgreSQL enforces uniqueness with a unique B-tree index or an exclusion constraint with a GiST index. A mock cannot reproduce that race.
  • A schema built by migrations. In production the schema comes from migration scripts (for example Alembic). An in-memory test database is often built with Base.metadata.create_all(), which creates tables straight from the current Python models. That skips custom migration steps, partial indexes, triggers and data backfills.
  • Transaction aborts and rollbacks. In PostgreSQL, a transaction that hits an SQL error is marked aborted, and every later statement in it fails until you roll back. Mocks and simple test doubles do not reproduce this.

05. Where integration tests fit in the pyramid

Testing against real PostgreSQL does not mean giving up fast unit tests. Split the work by what each test needs:

  1. Unit tests (fast, in memory) cover pure business logic: calculations, data transformations, validation rules and algorithms. These functions take plain Python objects and return plain Python objects. They do not open database sessions or make network calls, so they run in milliseconds.
  2. Database integration tests (real PostgreSQL) cover repository methods, SQLAlchemy queries, transaction boundaries and Alembic migrations. Each test runs against a real, disposable PostgreSQL database, so the schema and constraints are the ones production has.
  3. End-to-end API tests (HTTP to database) send full requests with FastAPI's TestClient or httpx.AsyncClient. They check routing, request parsing, authorisation, persistence and status codes together.

In the next lesson you will build a disposable PostgreSQL test database with Docker and session-scoped fixtures, so integration tests stay fast, isolated and reproducible on developer machines and in CI.

06. Check your understanding

Practice check · 3 questions

Database mocking tradeoffs

Three questions on why mocks and SQLite differ from real PostgreSQL.

Q1. A migration renamed a column, but the model still maps the old name. Why does a test that mocks the database session still pass?
Q2. Tests run on in-memory SQLite and production runs PostgreSQL. Which code is most likely to pass the tests and misbehave in production?
Q3. Which of these should be verified with an integration test against real PostgreSQL rather than a unit test?
Practice only: not graded, not saved, not evidence.

07. Apply it

Inspect your current projects: identify where database calls are currently mocked or where SQLite is used as a test substitute. Write down three specific failure modes (such as JSON queries, unique constraints, or foreign key cascades) that could silently break in production without being caught by your current tests. In the next lab lesson, you will set up a real, disposable PostgreSQL container that catches these bugs.

08. Review prompt

Explain to a teammate why passing a test with mock_session.scalars.return_value does not prove that a SQL query will run in production. Name at least three dialect or constraint differences between SQLite in-memory and PostgreSQL, and describe which types of tests belong in unit tests versus database integration tests.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check