Skip to main content

Testing and QA · Intermediate · 24 min

Manage test data with factories and builders

By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · factory_boy 3.3.3 · SQLAlchemy 2.1.9 · Faker 40.63.0 · pytest 9.2

You will replace a shared JSON fixture file with factory_boy factories, traits and a small order builder for a SQLAlchemy shop model, with seeded fake data that comes out the same on every run.

On this page

Most test suites start with a file of shared data: a JSON or YAML fixture with a handful of customers, products and orders that every test loads. It feels tidy. Then a new test needs one more order, someone adds it to the shared file, and an unrelated test that counted orders starts failing. A few months later nobody dares touch the file, and nobody can tell from a test which rows it depends on.

Factories fix this by turning test data into code. A factory knows how to make one valid object with sensible defaults, and each test overrides only the fields it is about. A builder sits on top of factories and assembles a larger object, such as an order with several lines and a coupon, in a way that reads like a sentence in the test.

You will build a small shop model with SQLAlchemy, watch a shared fixture file break a test, then replace it with factory_boy factories, sequences, SubFactory, traits and a builder. Fake names come from Faker's Yoruba locale and are seeded, so the same names appear on every run and on every machine. The tests use an in-memory SQLite database, because the pattern is the point here; running the same tests against PostgreSQL is covered in the integration testing tutorial.

Step 1 · Create the project and the code under test

Make a throwaway project. SQLAlchemy is a runtime dependency; pytest, factory_boy and Faker are only for tests:

Bash
mkdir -p ~/factories-demo
cd ~/factories-demo
uv init --no-package
uv add "sqlalchemy>=2.1,<2.2"
uv add --dev "pytest>=9.2,<9.3" "factory-boy>=3.3,<3.4" "faker==40.63.0"
rm main.py
mkdir -p shop tests
touch shop/__init__.py

Faker is pinned to one exact version on purpose. Its word and name lists change between releases, so a seeded run on Faker 40.63.0 and the same seed on a later release can produce different names. Upgrade it deliberately, in its own commit, not as a side effect of something else.

Create the models. Prices are integers in minor units (kobo, cents, pence), never floats:

Bash
cat > shop/models.py <<'PY'
from datetime import datetime

from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class Customer(Base):
    __tablename__ = "customers"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    email: Mapped[str] = mapped_column(unique=True)
    country: Mapped[str] = mapped_column(String(2))
    vip: Mapped[bool] = mapped_column(default=False)
    orders: Mapped[list["Order"]] = relationship(back_populates="customer")


class Product(Base):
    __tablename__ = "products"
    id: Mapped[int] = mapped_column(primary_key=True)
    sku: Mapped[str] = mapped_column(unique=True)
    name: Mapped[str]
    price_minor: Mapped[int]
    stock: Mapped[int]


class Order(Base):
    __tablename__ = "orders"
    id: Mapped[int] = mapped_column(primary_key=True)
    customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"))
    status: Mapped[str] = mapped_column(default="draft")
    coupon: Mapped[str | None]
    paid_at: Mapped[datetime | None]
    customer: Mapped[Customer] = relationship(back_populates="orders")
    lines: Mapped[list["OrderLine"]] = relationship(back_populates="order")


class OrderLine(Base):
    __tablename__ = "order_lines"
    id: Mapped[int] = mapped_column(primary_key=True)
    order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"))
    product_id: Mapped[int] = mapped_column(ForeignKey("products.id"))
    quantity: Mapped[int]
    order: Mapped[Order] = relationship(back_populates="lines")
    product: Mapped[Product] = relationship()
PY

Then the rules the tests will check. A WELCOME10 coupon takes 10% off. A VIP customer whose total is still at least 1,000,000 minor units after the coupon gets a further 50,000 off. An order ships only when it is paid, has lines, and there is enough stock for every line:

Bash
cat > shop/orders.py <<'PY'
from sqlalchemy import select

from shop.models import Order

OPEN_STATUSES = ("draft", "paid")


def order_total(order):
    total = sum(line.quantity * line.product.price_minor for line in order.lines)
    if order.coupon == "WELCOME10":
        total -= total // 10
    if order.customer.vip and total >= 1_000_000:
        total -= 50_000
    return total


def can_ship(order):
    if order.status != "paid" or not order.lines:
        return False
    return all(line.quantity <= line.product.stock for line in order.lines)


def open_orders_for(session, customer):
    query = (
        select(Order)
        .where(Order.customer_id == customer.id, Order.status.in_(OPEN_STATUSES))
        .order_by(Order.id)
    )
    return list(session.scalars(query))
PY
cat >> pyproject.toml <<'TOML'

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = [".", "tests"]
addopts = "-ra"
TOML

pythonpath puts both the project folder and tests on the import path, so tests can import shop and the helper modules you are about to put in tests.

Check it worked

Bash
uv run python -c "from shop.models import Base; print(sorted(Base.metadata.tables))"

It prints ['customers', 'order_lines', 'orders', 'products'].

Step 2 · Watch a shared fixture file break a test

Each test gets its own empty database. A scoped_session lives in a small module of its own so the factories can import it later, and the session fixture binds it to a fresh in-memory SQLite engine for each test, then throws both away:

Bash
cat > tests/testdb.py <<'PY'
from sqlalchemy.orm import scoped_session, sessionmaker

Session = scoped_session(sessionmaker())
PY
cat > tests/conftest.py <<'PY'
import pytest
from sqlalchemy import create_engine

from shop.models import Base
from testdb import Session


@pytest.fixture
def session():
    engine = create_engine("sqlite://")
    Base.metadata.create_all(engine)
    Session.configure(bind=engine)
    yield Session
    Session.remove()
    engine.dispose()
PY

Now the old way: a shared data file, a loader, and one test that relies on it:

Bash
mkdir -p tests/data
cat > tests/data/shop.json <<'JSON'
{
  "customers": [
    {"id": 1, "name": "Ada Okafor", "email": "ada@example.test", "country": "NG", "vip": false},
    {"id": 2, "name": "Kwame Mensah", "email": "kwame@example.test", "country": "GH", "vip": true}
  ],
  "products": [
    {"id": 1, "sku": "RICE-5KG", "name": "Rice 5kg", "price_minor": 1250000, "stock": 40}
  ],
  "orders": [
    {"id": 1, "customer_id": 1, "status": "paid", "coupon": null},
    {"id": 2, "customer_id": 1, "status": "draft", "coupon": null},
    {"id": 3, "customer_id": 2, "status": "paid", "coupon": "WELCOME10"}
  ],
  "order_lines": [
    {"id": 1, "order_id": 1, "product_id": 1, "quantity": 2},
    {"id": 2, "order_id": 3, "product_id": 1, "quantity": 1}
  ]
}
JSON
cat > tests/test_fixture_file.py <<'PY'
import json
from pathlib import Path

import pytest

from shop.models import Customer, Order, OrderLine, Product
from shop.orders import open_orders_for

DATA = Path(__file__).parent / "data" / "shop.json"
MODELS = {"customers": Customer, "products": Product, "orders": Order, "order_lines": OrderLine}


@pytest.fixture
def shop_data(session):
    data = json.loads(DATA.read_text(encoding="utf-8"))
    for key, model in MODELS.items():
        session.add_all(model(**row) for row in data[key])
    session.flush()
    return session


def test_ada_has_two_open_orders(shop_data):
    ada = shop_data.get(Customer, 1)
    assert len(open_orders_for(shop_data, ada)) == 2
PY
uv run pytest -q

That passes. Now a colleague writes a coupon test and needs a paid order with a coupon for a Nigerian customer. Ada fits, so they add one order to the shared file:

Bash
uv run python - <<'PY'
import json
from pathlib import Path

path = Path("tests/data/shop.json")
data = json.loads(path.read_text(encoding="utf-8"))
data["orders"].append({"id": 4, "customer_id": 1, "status": "paid", "coupon": "WELCOME10"})
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
PY
uv run pytest -q > rot.txt 2>&1 || echo "pytest exited with status $?"
grep "assert 3 == 2" rot.txt

Check it worked

The status line reads pytest exited with status 1, and grep finds assert 3 == 2. Nothing about open orders changed in the code, yet the test fails, and its body does not show why: the reason is a row in a file it never mentions. Multiply that by fifty tests and you have the usual state of a shared fixture file.

Remove the file, the loader and the test. The rest of the tutorial builds each test's data inside the test:

Bash
rm -r tests/data tests/test_fixture_file.py rot.txt

Step 3 · Write factories with defaults and sequences

A factory describes one valid object. Every field gets a default, so a test can call CustomerFactory() with no arguments and get a row the database accepts. Create tests/factories.py:

Bash
cat > tests/factories.py <<'PY'
import factory
from factory.alchemy import SQLAlchemyModelFactory

from shop.models import Customer, Product
from testdb import Session


class BaseFactory(SQLAlchemyModelFactory):
    class Meta:
        abstract = True
        sqlalchemy_session = Session
        sqlalchemy_session_persistence = "flush"


class CustomerFactory(BaseFactory):
    class Meta:
        model = Customer

    name = factory.Faker("name", locale="yo_NG")
    email = factory.Sequence(lambda n: f"customer{n}@example.test")
    country = "NG"
    vip = False


class ProductFactory(BaseFactory):
    class Meta:
        model = Product

    sku = factory.Sequence(lambda n: f"SKU-{n:04d}")
    name = factory.Faker("word")
    price_minor = 150_000
    stock = 100
PY

What each piece does:

  • sqlalchemy_session is the scoped session from testdb.py, so every factory writes through whatever engine the session fixture bound for the current test. A test that creates rows must ask for session, or there is no database to write to.
  • sqlalchemy_session_persistence = "flush" flushes after each object, so it gets its primary key straight away, but nothing is committed. The fixture throws the database away anyway.
  • factory.Sequence gives each object a number that goes up by one per call. Use it for columns that must be unique, such as email and sku. A random Faker email would collide with another one sooner or later and fail the unique constraint at random.
  • factory.Faker("name", locale="yo_NG") draws a Yoruba name. Realistic text in the data catches encoding and length bugs early, and if your users write in Yoruba, Hausa, Swahili or isiZulu, your test data should too.
  • Plain values such as country = "NG" are fixed defaults. Pick boring, valid ones.

Write the first tests. Each one overrides only the field it is about:

Bash
cat > tests/test_customers.py <<'PY'
from sqlalchemy import func, select

from factories import CustomerFactory
from shop.models import Customer


def count_customers(session):
    return session.scalar(select(func.count()).select_from(Customer))


def test_create_saves_a_row(session):
    customer = CustomerFactory()
    assert customer.id is not None
    assert count_customers(session) == 1


def test_batch_gets_unique_emails(session):
    customers = CustomerFactory.create_batch(5)
    assert len({c.email for c in customers}) == 5


def test_build_does_not_touch_the_database(session):
    customer = CustomerFactory.build()
    assert customer.id is None
    assert count_customers(session) == 0


def test_override_only_what_matters(session):
    customer = CustomerFactory(country="KE")
    assert customer.country == "KE"
PY
uv run pytest -q

Calling the factory, or create(), saves the object. build() makes it in memory only, which is faster and is enough when the code under test never queries the database.

Check it worked

The run ends with 4 passed. Change "flush" to None in BaseFactory, run again, and test_create_saves_a_row fails because customer.id is None until something flushes. Put "flush" back before you continue.

Step 4 · Connect related objects with SubFactory

An order line needs an order and a product, and an order needs a customer. SubFactory makes the related object for you when the test does not pass one. Create the order factories in their own module:

Bash
cat > tests/order_factories.py <<'PY'
import factory

from factories import BaseFactory, CustomerFactory, ProductFactory
from shop.models import Order, OrderLine


class OrderFactory(BaseFactory):
    class Meta:
        model = Order

    customer = factory.SubFactory(CustomerFactory)
    status = "draft"
    coupon = None
    paid_at = None


class OrderLineFactory(BaseFactory):
    class Meta:
        model = OrderLine

    order = factory.SubFactory(OrderFactory)
    product = factory.SubFactory(ProductFactory)
    quantity = 1
PY

A double underscore in a keyword reaches into a sub-factory: product__price_minor=200_000 means "make the product with this price". Or pass a whole object, as order=order does below, to share one order between several lines:

Bash
cat > tests/test_orders.py <<'PY'
from order_factories import OrderFactory, OrderLineFactory
from shop.orders import order_total


def test_a_line_brings_its_own_order_customer_and_product(session):
    line = OrderLineFactory()
    assert line.order.customer.id is not None
    assert line.product.id is not None


def test_total_multiplies_quantity_by_price(session):
    line = OrderLineFactory(quantity=3, product__price_minor=200_000)
    assert order_total(line.order) == 600_000


def test_welcome_coupon_takes_ten_percent_off(session):
    order = OrderFactory(coupon="WELCOME10")
    OrderLineFactory(order=order, quantity=2, product__price_minor=500_000)
    assert order_total(order) == 900_000
PY
uv run pytest -q tests/test_orders.py

Each test states the numbers its assertion depends on: the quantity, the price and the coupon. The customer's name, the SKU and the stock are defaults because the test does not care about them.

Check it worked

The run ends with 3 passed. One OrderLineFactory() call writes four rows: a customer, an order, a product and the line. That is convenient, and it is also why a slow suite often turns out to be making far more rows than it needs.

Step 5 · Name common states with traits

A paid order is not one field. It has status="paid" and a paid_at time, and a test that sets one without the other builds an order the real system never makes. A trait gives that combination a name. Replace tests/order_factories.py with this version; the new parts are the datetime import and the Params class:

Bash
cat > tests/order_factories.py <<'PY'
from datetime import datetime

import factory

from factories import BaseFactory, CustomerFactory, ProductFactory
from shop.models import Order, OrderLine


class OrderFactory(BaseFactory):
    class Meta:
        model = Order

    class Params:
        paid = factory.Trait(status="paid", paid_at=datetime(2026, 11, 2, 9, 30))
        cancelled = factory.Trait(status="cancelled")

    customer = factory.SubFactory(CustomerFactory)
    status = "draft"
    coupon = None
    paid_at = None


class OrderLineFactory(BaseFactory):
    class Meta:
        model = OrderLine

    order = factory.SubFactory(OrderFactory)
    product = factory.SubFactory(ProductFactory)
    quantity = 1
PY

Fields inside Params are not passed to the model. OrderFactory(paid=True) switches the trait on and applies its fields. Traits also pass through sub-factories, so OrderLineFactory(order__paid=True) makes a line on a paid order:

Bash
cat > tests/test_shipping.py <<'PY'
from factories import CustomerFactory
from order_factories import OrderFactory, OrderLineFactory
from shop.orders import can_ship, open_orders_for


def test_paid_trait_sets_status_and_time(session):
    order = OrderFactory(paid=True)
    assert order.status == "paid"
    assert order.paid_at is not None


def test_paid_order_with_stock_can_ship(session):
    line = OrderLineFactory(order__paid=True, quantity=2, product__stock=5)
    assert can_ship(line.order)


def test_draft_order_cannot_ship(session):
    line = OrderLineFactory(quantity=1, product__stock=5)
    assert not can_ship(line.order)


def test_cannot_ship_more_than_stock(session):
    line = OrderLineFactory(order__paid=True, quantity=6, product__stock=5)
    assert not can_ship(line.order)


def test_open_orders_leave_out_cancelled_and_other_customers(session):
    customer = CustomerFactory()
    paid = OrderFactory(customer=customer, paid=True)
    draft = OrderFactory(customer=customer)
    OrderFactory(customer=customer, cancelled=True)
    OrderFactory()
    assert open_orders_for(session, customer) == [paid, draft]
PY
uv run pytest -q

Compare the last test with the fixture-file version. Every order it counts is created in the test, including the two it expects to be left out, so a reader can see why the answer is two.

Check it worked

The full run ends with 12 passed. Remove cancelled=True from the third order in the last test and run it: it fails, because that order is now a draft and the list holds three open orders instead of two. Put it back before you continue.

Step 6 · Build complex orders with a builder

Factories make one row at a time. Some tests need a whole aggregate: a VIP customer, an order with two lines at different prices, and a coupon. Written with factories alone, that is five calls whose order matters. A builder wraps them in methods that read as a description of the order:

Bash
cat > tests/builders.py <<'PY'
from factories import CustomerFactory, ProductFactory
from order_factories import OrderFactory, OrderLineFactory


class OrderBuilder:
    def __init__(self):
        self._customer = {}
        self._order = {}
        self._lines = []

    def for_customer(self, **fields):
        self._customer.update(fields)
        return self

    def with_line(self, quantity=1, **product_fields):
        self._lines.append((quantity, product_fields))
        return self

    def with_coupon(self, code):
        self._order["coupon"] = code
        return self

    def paid(self):
        self._order["paid"] = True
        return self

    def create(self):
        customer = CustomerFactory(**self._customer)
        order = OrderFactory(customer=customer, **self._order)
        for quantity, product_fields in self._lines:
            product = ProductFactory(**product_fields)
            OrderLineFactory(order=order, quantity=quantity, product=product)
        return order


def an_order():
    return OrderBuilder()
PY

Each method records what the test asked for and returns the builder, so calls chain. Nothing touches the database until create(), which hands the work to the factories. The builder owns no defaults of its own: those stay in one place, the factories.

Use it for the VIP rule, where the order of discounts matters:

Bash
cat > tests/test_totals.py <<'PY'
from builders import an_order
from shop.orders import order_total


def test_vip_discount_applies_to_large_orders(session):
    order = (
        an_order()
        .for_customer(vip=True)
        .with_line(quantity=2, price_minor=400_000)
        .with_line(quantity=1, price_minor=300_000)
        .create()
    )
    # 1,100,000 minus the 50,000 VIP discount
    assert order_total(order) == 1_050_000


def test_coupon_can_take_a_vip_order_below_the_threshold(session):
    order = (
        an_order()
        .for_customer(vip=True)
        .with_line(quantity=2, price_minor=400_000)
        .with_line(quantity=1, price_minor=300_000)
        .with_coupon("WELCOME10")
        .create()
    )
    # 1,100,000 minus 10% is 990,000: under 1,000,000, so no VIP discount
    assert order_total(order) == 990_000


def test_builder_orders_can_be_paid(session):
    order = an_order().with_line(quantity=1).paid().create()
    assert order.status == "paid"
    assert len(order.lines) == 1
PY
uv run pytest -q tests/test_totals.py

Reach for a builder when the same multi-object shape appears in many tests, or when the steps to assemble it have rules of their own. For one row, a factory call is clearer.

Check it worked

The run ends with 3 passed. Each test reads top to bottom as the order it describes, and the comments show the arithmetic behind each expected total.

Step 7 · Make fake data the same on every run

Faker picks values at random, so a test that fails with one customer name might pass with the next. That makes failures hard to reproduce. factory_boy keeps one random state that Faker shares, and factory.random.reseed_random() resets it. Append an autouse fixture to tests/conftest.py that reseeds before every test, and a hook that prints the seed at the top of each run:

Bash
cat >> tests/conftest.py <<'PY'


import os

import factory.random

SEED = os.environ.get("FACTORY_SEED", "shop-tests")


def pytest_report_header():
    return f"factory seed: {SEED}"


@pytest.fixture(autouse=True)
def seeded_fake_data():
    factory.random.reseed_random(SEED)
PY

Reseeding before every test, not once per run, means a test gets the same data whether it runs alone, first or last. The FACTORY_SEED environment variable lets you try another seed to shake out a test that only passes with particular data.

See it outside pytest with a short script that seeds and builds three customers:

Bash
cat > show_customers.py <<'PY'
import sys

import factory.random

sys.path.insert(0, "tests")
from factories import CustomerFactory  # noqa: E402

factory.random.reseed_random(sys.argv[1])
for customer in CustomerFactory.build_batch(3):
    print(customer.name, customer.email)
PY
uv run python show_customers.py shop-tests > run1.txt
uv run python show_customers.py shop-tests > run2.txt
diff run1.txt run2.txt && echo "same data both times"
cat run1.txt

Check it worked

diff prints nothing and the script prints same data both times, followed by three Yoruba names with emails ending in @example.test. Run it once more with another seed, uv run python show_customers.py other-seed, and the names change while the emails, which come from a sequence, do not. Then check the suite:

Bash
uv run pytest | grep "factory seed"
uv run pytest -q
FACTORY_SEED=another-seed uv run pytest -q
rm show_customers.py run1.txt run2.txt

The first line reads factory seed: shop-tests, and both runs end with 15 passed. The suite passes with a different seed because no test asserts on a Faker value.

Step 8 · Keep the data a test depends on inside the test

Factories make it easy to slip back into hidden data, this time through defaults. A test that asserts on a default value passes today and breaks when someone changes the default, the order of tests, or the Faker version. Here is one that leans on a sequence value:

Bash
cat > tests/test_skus.py <<'PY'
from factories import ProductFactory


def test_first_product_sku(session):
    assert ProductFactory().sku == "SKU-0000"
PY
uv run pytest -q tests/test_skus.py
uv run pytest -q > skus.txt 2>&1 || echo "pytest exited with status $?"
grep "FAILED tests/test_skus.py" skus.txt

On its own it passes. In the full run it fails, because sequences count across the whole run, not per test, and the shipping tests have already made products. Rewrite it so the value it checks is the value it sets:

Bash
cat > tests/test_skus.py <<'PY'
from sqlalchemy import select

from factories import ProductFactory
from shop.models import Product


def test_products_can_be_found_by_sku(session):
    ProductFactory(sku="RICE-5KG", name="Rice 5kg")
    ProductFactory()
    found = session.scalars(select(Product).where(Product.sku == "RICE-5KG")).one()
    assert found.name == "Rice 5kg"
PY
uv run pytest -q
rm skus.txt

A checklist for reviewing tests that use factories:

  • Every value an assertion depends on is passed in the test, not taken from a factory default.
  • No assertion uses a sequence number or a Faker value. Seeding makes failures repeatable; it does not make those values part of the contract.
  • Factory defaults are valid and boring. A default that triggers a business rule (a VIP customer, a coupon) belongs in a trait or an explicit override.
  • Unique columns use Sequence, not Faker.
  • A builder appears only where several tests need the same multi-object shape.

Check it worked

The fragile version passes alone, then the full run prints pytest exited with status 1 and grep finds FAILED tests/test_skus.py::test_first_product_sku. After the rewrite, the full run ends with 16 passed.

Remove the demo project when you are done:

Bash
cd ~
rm -rf ~/factories-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.