pytest-factoryboy
pytest-factoryboy is a pytest plugin that integrates factory_boy for easily creating test data within your pytest tests. It provides fixtures for generating instances of your factory_boy factories, streamlining setup for database models or complex objects. As of version 2.8.1, it's actively maintained with a stable release cadence.
Warnings
- breaking The `fb` fixture, common in older versions, was removed in `pytest-factoryboy` 2.0.0. Attempting to use it will result in a `FixtureLookupError`.
- breaking Factory resolution and discovery mechanisms underwent significant changes in `pytest-factoryboy` 2.0.0. Tests relying on implicit factory discovery or specific naming conventions from 1.x might break.
- gotcha Factories defined directly within test functions or nested scopes might not be properly discovered or utilized by `pytest-factoryboy`.
Install
-
pip install pytest-factoryboy
Imports
- factory (fixture)
def test_something(factory): ...
Quickstart
import pytest
import factory
# Assume a simple data model for demonstration
class User:
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return f"User(username='{self.username}', email='{self.email}')"
# Define your factory_boy factory (e.g., in factories.py or conftest.py)
class UserFactory(factory.Factory):
class Meta:
model = User # Link to your actual model/class
username = factory.Sequence(lambda n: f'user{n}')
email = factory.LazyAttribute(lambda o: f'{o.username}@example.com')
# In your conftest.py or test file, define a fixture that uses `pytest-factoryboy`'s `factory` fixture
@pytest.fixture
def user_factory(factory):
# `factory` is provided by pytest-factoryboy, it returns a callable bound to UserFactory
return factory(UserFactory)
# Now use your `user_factory` in tests
def test_create_single_user(user_factory):
user = user_factory()
assert user.username.startswith('user')
assert user.email.endswith('@example.com')
assert isinstance(user, User)
def test_create_multiple_users(user_factory):
users = user_factory.create_batch(3)
assert len(users) == 3
assert all(isinstance(u, User) for u in users)
def test_create_user_with_override(user_factory):
user = user_factory(username='admin_user', email='admin@example.com')
assert user.username == 'admin_user'
assert user.email == 'admin@example.com'