Features¶
Every example on this page uses the models and the factories of the home page. Each one is a script run by the test suite, and the outputs shown are the ones it checks.
Create and await¶
create() builds the instance, adds it to the session, commits, and returns it. It is a coroutine: await it.
import asyncio
from factories import HeroFactory, TeamFactory, engine, session
from sqlmodel import SQLModel
async def main() -> None:
async with engine.begin() as connection:
await connection.run_sync(SQLModel.metadata.create_all)
team = await TeamFactory.create()
print(team.id, team.name)
preventers = await TeamFactory.create(name="Preventers")
print(preventers.id, preventers.name)
heroes = await HeroFactory.create_batch(2, age=30)
print([(hero.name, hero.age) for hero in heroes])
rusty = await HeroFactory.create(name="Rusty-Man", team__name="Avengers")
print(rusty.secret_name, rusty.team.name)
await session.close()
await engine.dispose()
asyncio.run(main())
1 team-0
2 Preventers
[('hero-0', 30), ('hero-1', 30)]
Rusty-Man in disguise Avengers
- A keyword argument overrides the declaration of its field, as in plain
factory_boy:name="Preventers". create_batch(size, **kwargs)awaitscreate()sizetimes, one after the other, and returns the list.team__name="Avengers"reaches into the sub-factory, with the usualfactory_boydouble underscore.
When the instance comes back, its primary key is set and the row is committed, so a second session or an HTTP client in the same test sees it.
factory_boy declarations¶
Declarations are evaluated by factory_boy itself, before the instance is created, so they work as documented in the factory_boy reference:
factory.Sequencefor unique values, such asteam-0,team-1;factory.Fakerfor realistic ones, such as the team'sheadquarters;factory.LazyAttributefor a value computed from the other fields of the same object, such as the hero'ssecret_name;class Paramswithfactory.Traitfor named groups of overrides.
A declaration that reads the result of a sub-factory is the exception: see limits.
Related objects with SubFactory¶
A SubFactory field creates the related object first, waits for it, and passes the instance to the model.
import asyncio
from factories import HeroFactory, TeamFactory, engine, session
from sqlmodel import SQLModel
async def main() -> None:
async with engine.begin() as connection:
await connection.run_sync(SQLModel.metadata.create_all)
heroes = await HeroFactory.create_batch(2)
print([hero.team.name for hero in heroes])
preventers = await TeamFactory.create(name="Preventers")
deadpond = await HeroFactory.create(team=preventers)
print(deadpond.team_id == preventers.id)
spider_boy = await HeroFactory.create(team=TeamFactory.create(name="Z-Force"))
print(spider_boy.team.name)
await session.close()
await engine.dispose()
asyncio.run(main())
['team-0', 'team-1']
True
Z-Force
- Without an argument, each hero gets a new team.
- An instance passed explicitly,
team=preventers, is used as is. - Any awaitable passed as a field value is awaited first, so
team=TeamFactory.create(name="Z-Force")works without awaiting it yourself.
Get or create¶
sqlalchemy_get_or_create in class Meta names the fields that identify a row. Before inserting, the factory looks for a row with the same values for those fields, and returns it if there is one.
import asyncio
from factories import TeamFactory, engine, session
from models import Team
from sqlmodel import SQLModel, select
async def main() -> None:
async with engine.begin() as connection:
await connection.run_sync(SQLModel.metadata.create_all)
first = await TeamFactory.create(name="Preventers", headquarters="Sharp Tower")
second = await TeamFactory.create(name="Preventers", headquarters="Elsewhere")
print(first.id == second.id, second.headquarters)
teams = (await session.exec(select(Team))).all()
print(len(teams))
await session.close()
await engine.dispose()
asyncio.run(main())
True Sharp Tower
1
The existing row is returned as it is: the other values given to create(), here headquarters="Elsewhere", are not applied to it.
If the insert fails on an IntegrityError, for instance because another connection inserted the same key in between, the session is rolled back and the row is looked up again with the values passed explicitly to create(). When none of the get or create fields was passed explicitly, or when that second lookup finds nothing, the IntegrityError is raised.
Every field named in sqlalchemy_get_or_create needs a value, from a declaration or from the call. Otherwise create() raises factory.errors.FactoryError, whose message starts with sqlalchemy_get_or_create.
Build without a database¶
build(), build_batch() and stub() are untouched factory_boy strategies: they are synchronous, and they never reach the session.
from factories import HeroFactory
hero = HeroFactory.build()
print(hero.id, hero.name, hero.team.name)
heroes = HeroFactory.build_batch(2, age=48)
print([(hero.name, hero.age) for hero in heroes])
None hero-0 team-0
[('hero-1', 48), ('hero-2', 48)]
The hero has no primary key, since nothing was inserted, and its sub-factory was built the same way, so hero.team is a Team instance. It suits unit tests of code that only reads the models.
Session settings¶
Two settings matter, both for the same reason: under asyncio, an attribute cannot load itself from the database on first access.
expire_on_commit=Falseon the session.create()commits, and an expired instance would reload itself lazily on the next attribute access.sa_relationship_kwargs={"lazy": "selectin"}on any relationship a test reads back, such asHero.team.
The factory commits once per create(), sub-factories included. That is deliberate: a test that queries or paginates through a second session sees the objects it created.
Using it with pytest¶
The session is read from class Meta when the factory is used. For a fresh database in each test, the tests of this library define the factories inside fixtures, on top of a session fixture. With pytest-asyncio in auto mode, a conftest.py:
from collections.abc import AsyncIterator
import factory
import pytest_asyncio
from models import Hero, Team
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlmodel_async_factory import AsyncSQLModelFactory
@pytest_asyncio.fixture
async def session() -> AsyncIterator[AsyncSession]:
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
async with engine.begin() as connection:
await connection.run_sync(SQLModel.metadata.create_all)
async with AsyncSession(engine, expire_on_commit=False) as session:
yield session
await engine.dispose()
@pytest_asyncio.fixture
async def team_factory(session: AsyncSession) -> type[AsyncSQLModelFactory]:
class TeamFactory(AsyncSQLModelFactory):
class Meta:
model = Team
sqlalchemy_session = session
name = factory.Sequence(lambda n: f"team-{n}")
headquarters = factory.Faker("city")
return TeamFactory
@pytest_asyncio.fixture
async def hero_factory(
session: AsyncSession, team_factory: type[AsyncSQLModelFactory]
) -> type[AsyncSQLModelFactory]:
class HeroFactory(AsyncSQLModelFactory):
class Meta:
model = Hero
sqlalchemy_session = session
name = factory.Sequence(lambda n: f"hero-{n}")
secret_name = factory.LazyAttribute(lambda hero: f"{hero.name} in disguise")
team = factory.SubFactory(team_factory)
return HeroFactory
The tests ask for the factories they need:
from models import Hero, Team
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlmodel_async_factory import AsyncSQLModelFactory
async def test_hero_belongs_to_a_team(
hero_factory: type[AsyncSQLModelFactory],
) -> None:
hero = await hero_factory.create()
assert hero.team.name.startswith("team-")
heroes = await hero_factory.create_batch(3, team=hero.team)
assert all(other.team_id == hero.team_id for other in heroes)
async def test_each_test_starts_from_an_empty_database(
session: AsyncSession, hero_factory: type[AsyncSQLModelFactory]
) -> None:
await hero_factory.create()
assert len((await session.exec(select(Hero))).all()) == 1
assert len((await session.exec(select(Team))).all()) == 1
Auto mode is set in pyproject.toml:
[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"