Sub topic 9
Building in memory versus persisting
This chapter assumes you can write pytest tests, you know the make_user factory from the earlier chapters, and you have used a SQL database from Python. It covers when a factory should only construct an object and when it should also save it.
Two kinds of factory call
A factory can do two different things:
- Build an object in memory. Nothing outside the test process changes.
- Create an object by building it and then saving it, for example with an
INSERTinto a database.
make_user only builds. Persisting adds a step after the build. The factory still supplies the defaults and the overrides.
import sqlite3
from dataclasses import dataclass
from itertools import count
import pytest
@dataclass
class User:
id: int
email: str
role: str
active: bool
_user_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 create_user(conn, **overrides):
user = make_user(**overrides)
conn.execute(
"INSERT INTO users (id, email, role, active) VALUES (?, ?, ?, ?)",
(user.id, user.email, user.role, int(user.active)),
)
return user
@pytest.fixture
def conn():
connection = sqlite3.connect(":memory:")
connection.execute(
"CREATE TABLE users ("
"id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, "
"role TEXT NOT NULL, active INTEGER NOT NULL)"
)
yield connection
connection.close()
def can_log_in(user):
return user.active
def find_active_emails(conn):
rows = conn.execute("SELECT email FROM users WHERE active = 1 ORDER BY id")
return [row[0] for row in rows]
def test_inactive_user_cannot_log_in():
user = make_user(active=False)
assert can_log_in(user) is False
def test_query_returns_only_active_users(conn):
create_user(conn, email="[email protected]")
create_user(conn, email="[email protected]", active=False)
assert find_active_emails(conn) == ["[email protected]"]create_user reuses make_user, so the defaults live in one place. Only the save step is new.
Choosing between them
| Aspect | Build | Create |
|---|---|---|
| Speed | Microseconds | Slower, one write per object |
| Needs a database | No | Yes |
| Good for | Business rules, validation, formatting | Queries, constraints, joins, repositories |
| Isolation | Nothing to clean up | Needs a fresh database or a rollback per test |
Default to building. A test that can pass with an in-memory object should not pay for a database. Persist only when the behavior you are testing depends on the stored row, such as a WHERE clause or a unique constraint.
Relationships and persistence
Order matters when you persist related objects. A saved order that refers to a customer needs the customer row to exist first, or the foreign key fails. A create_order therefore calls create_user for its default customer and then inserts the order. In memory there is no such rule. make_order can hold any User object, saved or not.
Common errors
- Persisting by default. If every factory call writes to the database, the whole suite slows down. Offer both a build and a create function, and use build unless the test needs storage.
- Leaking rows between tests. Rows left by one test can break the unique
emailconstraint or change the counts in another. Give each test a fresh database, as theconnfixture does, or roll back a transaction after each test. - Id collisions. The
countinmake_userproduces ids that are unique within the process. If other code assigns ids in the database, such as auto-increment, let the database choose and read the id back after the insert. - Hidden writes in a build call. If a build function quietly saves related objects, tests that look like pure unit tests start touching storage. Keep the name honest:
make_*builds,create_*saves.
Factory libraries use the same split. factory_boy offers build() and create() on a factory, and the next chapters show how.
Exercise
A test checks that find_active_emails ignores inactive users. Should it use make_user or create_user, and why?
Show answer
It should use create_user. find_active_emails runs a SQL query, so the rows must exist in the database. Objects built with make_user live only in memory and the query would not see them.