Sub topic 9
Building in Memory Versus Persisting
This chapter assumes you can write Python tests with pytest, you know dataclasses, and you have used make_user-style factory functions with keyword overrides. It also assumes you know basic SQL. The database examples use the standard library's sqlite3, so nothing needs installing besides pytest.
Two things a factory can do
A factory can stop at an object in memory. That is called building. It can also go on to save the object in a database, a file, or a service. That is called persisting, or creating.
The factories so far only build. make_user() returns a User and touches nothing else. This is the default you should reach for, and the rest of the chapter explains when to leave it.
| Row | Build | Create (persist) |
|---|---|---|
| Result | Object in memory | Object in memory and a stored row |
| Speed | Microseconds | Milliseconds or more, per object |
| Needs a database | No | Yes |
| Typical use | Unit tests of pure logic | Tests of queries, constraints, and repositories |
| Typical failure | Object is valid in Python but invalid in the database | Slow suites and data leaking between tests |
Why build is the default
Most logic does not need a database. A function such as can_log_in(user) reads fields and returns a value. Testing it with a persisted user adds setup time and a database dependency, and it adds no coverage.
def can_log_in(user):
return user.active
def test_inactive_user_cannot_log_in():
user = make_user(active=False)
assert can_log_in(user) is FalseThis test runs without a connection, a schema, or cleanup. If a thousand tests look like this one, the speed difference is the difference between a suite that runs in a second and one that runs in a minute.
When you need to persist
Persist when the behavior under test involves the storage layer:
- Queries that filter, sort, or join rows.
- Constraints such as unique indexes, foreign keys, and
NOT NULL. - Repository or data-access code that reads and writes rows.
- Behavior that depends on database-generated values, such as defaults or timestamps.
A query like "find all active users" can only be tested against real rows. Building objects and passing them to a function that expects a connection does not exercise the SQL at all.
A factory that builds and one that creates
The cleanest design keeps the two steps separate. The build factory stays exactly as it was. A second function calls it and then saves the result. Here is a complete, runnable setup with both.
import sqlite3
from dataclasses import dataclass
from itertools import count
@dataclass
class User:
id: int
email: str
role: str
active: bool
@dataclass
class Order:
id: int
customer: User
total_cents: int
status: str
_user_ids = count(1)
_order_ids = count(1)
def make_user(**overrides):
n = next(_user_ids)
defaults = {
"id": n,
"email": f"user{n}@example.com",
"role": "member",
"active": True,
}
return User(**{**defaults, **overrides})
def make_order(customer=None, **overrides):
if customer is None:
customer = make_user()
defaults = {
"id": next(_order_ids),
"customer": customer,
"total_cents": 1000,
"status": "pending",
}
return Order(**{**defaults, **overrides})
def make_db():
conn = sqlite3.connect(":memory:")
conn.execute("PRAGMA foreign_keys = ON")
conn.execute(
"""CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
role TEXT NOT NULL,
active INTEGER NOT NULL
)"""
)
conn.execute(
"""CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES users(id),
total_cents INTEGER NOT NULL,
status TEXT NOT NULL
)"""
)
return conn
def save_user(conn, user):
conn.execute(
"INSERT INTO users (id, email, role, active) VALUES (?, ?, ?, ?)",
(user.id, user.email, user.role, int(user.active)),
)
conn.commit()
return user
def save_order(conn, order):
conn.execute(
"INSERT INTO orders (id, customer_id, total_cents, status) "
"VALUES (?, ?, ?, ?)",
(order.id, order.customer.id, order.total_cents, order.status),
)
conn.commit()
return order
def create_user(conn, **overrides):
return save_user(conn, make_user(**overrides))
def create_order(conn, customer=None, **overrides):
if customer is None:
customer = create_user(conn)
return save_order(conn, make_order(customer=customer, **overrides))The create_* functions take a connection as their first argument and pass everything else through. Overrides work the same way as before: create_user(conn, active=False) stores an inactive user.
Notice how create_order handles the default customer. It calls create_user, not make_user, so the customer row exists before the order row refers to it. If it called make_user, the insert would fail on the foreign key.
Using it in a test
A pytest fixture gives each test a fresh in-memory database. This fixture is not test data. It is infrastructure, and the factories supply the data.
import pytest
@pytest.fixture
def conn():
connection = make_db()
yield connection
connection.close()
def find_active_emails(conn):
rows = conn.execute(
"SELECT email FROM users WHERE active = 1 ORDER BY email"
)
return [row[0] for row in rows]
def test_find_active_emails_skips_inactive_users(conn):
create_user(conn, email="[email protected]")
create_user(conn, email="[email protected]", active=False)
assert find_active_emails(conn) == ["[email protected]"]
def test_order_requires_an_existing_customer(conn):
order = make_order() # built only, customer was never saved
with pytest.raises(sqlite3.IntegrityError):
save_order(conn, order)The first test needs persistence because the SQL WHERE clause is the thing being tested. The second shows what a constraint check looks like: a built order with an unsaved customer breaks the foreign key, and the test proves the database enforces it.
The flow of a persisted factory call
Persisting a graph of objects has an order. Parents must be stored before children.
Choosing between them
Ask what the test needs to observe.
- If the test checks a rule that depends only on field values, build.
- If the test calls code that takes a connection, session, or repository, create.
- If the test checks a constraint, index, or generated value, create.
- If you are unsure, start with build. Switching to create later is a one-word change at the call site.
Mixing is normal. A test can build a hundred objects for a pure function and create two for a query test in the same file.
Edge cases and gotchas
Counters outlive the database
The module-level count(1) keeps increasing across tests, but each test gets a fresh database. That is safe. Ids are unique, and gaps in the sequence do not matter. The reverse problem is more dangerous. If tests share a database that is never cleared, a hard-coded email such as "[email protected]" will violate the unique constraint on the second test that inserts it. Sequence-generated values avoid this, which is why the defaults in make_user use the counter.
Ids assigned by the database
Here the factory sets id itself, so the stored row and the in-memory object always agree. Many real systems let the database assign the id. In that case the create step must read the assigned id back and set it on the object. ORMs do this for you after a flush or commit. If you write your own save_*, do it explicitly, or the returned object will carry a wrong or empty id.
Leaking state between tests
Persisted rows survive until something removes them. There are three common ways to isolate tests:
- A new database per test, as above. This is simple and slow for large schemas.
- A transaction per test that is rolled back at the end. This is fast, but code under test that calls
commit()can break the isolation. - Truncating tables after each test. This is reliable but needs to respect foreign key order.
Pick one and use it everywhere. Mixed strategies produce order-dependent failures that only appear on some machines.
Persisting too much
A factory that creates a customer, an address, a payment method, and a warehouse for every order makes each test slow and hides what matters. Create only the parents the foreign keys require. For optional relations, default to None and let the test opt in.
Built objects can be invalid for the database
Building does not run database constraints. make_order(total_cents=None) succeeds in Python and only fails on insert. If a unit test passes a built object into logic and the logic is correct only for values the database would allow, the test may pass while production fails. Keep the factory defaults valid for the schema, and add create-based tests for the constraints that matter.
How libraries express the same choice
Factory libraries expose this split directly. In factory_boy, calling UserFactory.build() returns an unsaved object and UserFactory.create() saves it through the model's persistence hook. Calling UserFactory() uses the library's default strategy, which is create. For plain classes, as in the earlier chapter, the default strategy only instantiates. ORM-specific base classes, such as the Django or SQLAlchemy ones, override that so create writes rows. The decision you make is the same as in the hand-written version: build unless the test needs storage.
Summary of the rules
- Build by default. Persist only when the test exercises storage.
- Keep build and create as separate functions, with create calling build.
- Save parents before children.
- Keep defaults valid for the database schema, even when building.
- Choose one isolation strategy for persisted data and apply it everywhere.
Exercise
A test checks that apply_discount(order) lowers order.total_cents by 10 percent for orders over 5000 cents. The function reads and writes only the order object. Should the test use make_order or create_order, and what should you do differently if the same rule were enforced by a SQL UPDATE statement?
Show answer
Use make_order(total_cents=6000). The function works only on an in-memory object, so a database adds cost and no coverage. If the rule were a SQL UPDATE, the SQL itself is under test, so use create_order(conn, total_cents=6000) with a database fixture, then read the row back and assert on the stored total_cents.
Exercise
create_order(conn, customer=make_user()) raises sqlite3.IntegrityError. Why, and how do you fix the call?
Show answer
make_user() only builds a user, so no row exists in users when the order row refers to its id, and the foreign key fails. Fix it by creating the customer first: create_order(conn, customer=create_user(conn)), or omit the customer argument so create_order creates one itself.