### Install factory_boy from source Source: https://github.com/factoryboy/factory_boy/blob/master/docs/index.md Commands to clone the repository and install the package from source. ```sh $ git clone git://github.com/FactoryBoy/factory_boy/ $ python setup.py install ``` -------------------------------- ### Example Logging Output Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst This is an example of the detailed logging output generated during factory preparation, useful for debugging complex object instantiation. ```text BaseFactory: Preparing tests.test_using.TestModel2Factory(extra={}) LazyStub: Computing values for tests.test_using.TestModel2Factory(two=>) SubFactory: Instantiating tests.test_using.TestModelFactory(__containers=(,), one=4), create=True BaseFactory: Preparing tests.test_using.TestModelFactory(extra={'__containers': (,), 'one': 4}) LazyStub: Computing values for tests.test_using.TestModelFactory(one=4) LazyStub: Computed values, got tests.test_using.TestModelFactory(one=4) BaseFactory: Generating tests.test_using.TestModelFactory(one=4) LazyStub: Computed values, got tests.test_using.TestModel2Factory(two=) BaseFactory: Generating tests.test_using.TestModel2Factory(two=) ``` -------------------------------- ### FuzzyDate Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/fuzzy.md Demonstrates initializing FuzzyDate with a start date. If an end date is not provided, it defaults to the current date. ```python >>> fd = FuzzyDate(datetime.date(2008, 1, 1)) >>> fd.start_date, fd.end_date datetime.date(2008, 1, 1), datetime.date(2013, 4, 16) ``` -------------------------------- ### Install factory_boy Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Installation commands for the factory_boy package. ```sh $ pip install factory_boy ``` ```sh $ git clone git://github.com/FactoryBoy/factory_boy/ $ python setup.py install ``` -------------------------------- ### Install factory_boy via pip Source: https://github.com/factoryboy/factory_boy/blob/master/docs/index.md Standard installation command for the factory_boy package. ```sh $ pip install factory_boy ``` -------------------------------- ### SQLAlchemy Setup and Model Definitions Source: https://context7.com/factoryboy/factory_boy/llms.txt Sets up an in-memory SQLite database, defines SQLAlchemy models for Author and Book, and creates the tables. ```python import factory from factory.alchemy import SQLAlchemyModelFactory from sqlalchemy import Column, Integer, String, ForeignKey, create_engine from sqlalchemy.orm import declarative_base, sessionmaker, scoped_session, relationship # SQLAlchemy setup Base = declarative_base() engine = create_engine("sqlite:///:memory:") Session = scoped_session(sessionmaker(bind=engine)) # Models class Author(Base): __tablename__ = "authors" id = Column(Integer, primary_key=True) name = Column(String(100)) email = Column(String(100), unique=True) books = relationship("Book", back_populates="author") class Book(Base): __tablename__ = "books" id = Column(Integer, primary_key=True) title = Column(String(200)) author_id = Column(Integer, ForeignKey("authors.id")) author = relationship("Author", back_populates="books") Base.metadata.create_all(engine) ``` -------------------------------- ### Usage of Fuzzy Attributes Source: https://context7.com/factoryboy/factory_boy/llms.txt Shows a basic example of creating a product instance using the ProductFactory with fuzzy attributes. ```python # Usage product = ProductFactory() # product.price is between 0.99 and 999.99 ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/factoryboy/factory_boy/blob/master/docs/index.md Install the project's development dependencies in a virtual environment using pip. This command ensures all necessary packages for development and testing are available. ```sh $ pip install --editable '.[dev]' ``` -------------------------------- ### Use Helper Functions for Object Creation Source: https://context7.com/factoryboy/factory_boy/llms.txt Provides examples of using build, build_batch, make_factory, and stub for creating objects without explicit class definitions. ```python import factory class User: def __init__(self, name, email, age): self.name = name self.email = email self.age = age class Post: def __init__(self, title, content, author): self.title = title self.content = content self.author = author # build() - Create instance without saving user = factory.build( User, name="John Doe", email=factory.LazyAttribute(lambda o: f"{o.name.lower().replace(' ', '.')}@example.com"), age=factory.fuzzy.FuzzyInteger(18, 65) ) # build_batch() - Create multiple instances users = factory.build_batch( User, 5, name=factory.Sequence(lambda n: f"User {n}"), email=factory.Sequence(lambda n: f"user{n}@example.com"), age=25 ) # make_factory() - Create reusable factory class dynamically UserFactory = factory.make_factory( User, name="Default User", email=factory.LazyAttribute(lambda o: f"{o.name.lower().replace(' ', '_')}@example.com"), age=30 ) user1 = UserFactory() user2 = UserFactory(name="Custom Name") # Inherit from specific factory class from factory.django import DjangoModelFactory DjangoUserFactory = factory.make_factory( User, FACTORY_CLASS=DjangoModelFactory, name=factory.Faker("name"), email=factory.Faker("email"), age=factory.fuzzy.FuzzyInteger(18, 80) ) # stub() - Create stub object (no model needed) stub = factory.stub( dict, name="Test", value=factory.Sequence(int) ) # Debug factory execution with factory.debug(): user = UserFactory() ``` -------------------------------- ### Example Usage of post_generation Decorator Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Demonstrates creating users with default and custom parameters, showing how the mbox post-generation logic is triggered and how to override paths. ```python >>> UserFactory.build() # Nothing was created >>> UserFactory.create() # Creates dir /tmp/mbox/john >>> UserFactory.create(login='jack') # Creates dir /tmp/mbox/jack >>> UserFactory.create(mbox='/tmp/alt') # Creates dir /tmp/alt ``` -------------------------------- ### Sequence Generation Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Demonstrates the sequential generation of unique phone numbers using the Sequence declaration. ```python UserFactory().phone ``` ```python UserFactory().phone ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Install Factory Boy in editable mode with development dependencies using pip. ```sh pip install --editable '.[dev]' ``` -------------------------------- ### Factory Traits Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Demonstrates how to define and use traits to conditionally set multiple attributes on a factory. ```APIDOC ## Traits A trait's parameters are the fields it should alter when enabled. ### Example: Defining and Using Traits ```python import factory import datetime # Assume Order and EmployeeFactory are defined elsewhere # class Order: # pass # class EmployeeFactory: # pass class OrderFactory(factory.Factory): class Meta: model = Order state = 'pending' shipped_on = None shipped_by = None received_on = None received_by = None class Params: shipped = factory.Trait( state='shipped', shipped_on=datetime.date.today, shipped_by=factory.SubFactory(EmployeeFactory), ) received = factory.Trait( shipped=True, state='received', shipped_on=datetime.date.today - datetime.timedelta(days=4), received_on=datetime.date.today, received_by=factory.SubFactory(CustomerFactory), # Assume CustomerFactory is defined ) ``` Traits are activated or disabled by a single boolean field. Values set in a trait can be overridden by call-time values. Traits can also be chained. ### Overriding Traits in Subclasses ```python class ShippedOrderFactory(OrderFactory): shipped = True class LocalOrderFactory(OrderFactory): class Params: received = factory.Trait( shipped=True, state='received', shipped_on=datetime.date.today - datetime.timedelta(days=1), received_on=datetime.date.today, received_by=factory.SubFactory(CustomerFactory), ) ``` **Note:** When overriding a trait in a subclass, the whole declaration must be replaced. ``` -------------------------------- ### Execute circular factory relationships Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Example of instantiating factories involved in a circular dependency. ```pycon >>> owner = UserFactory(main_group=None) >>> UserFactory(main_group__owner=owner) ``` -------------------------------- ### Use Factories for Fixtures Source: https://github.com/factoryboy/factory_boy/blob/master/docs/examples.md Illustrates generating a large number of fixtures using `create_batch` and then creating specific, known objects with overridden attributes for use in testing or setup routines. ```python from . import factories def make_objects(): factories.ProfileFactory.create_batch(size=50) # Let's create a few, known objects. factories.ProfileFactory( gender=objects.Profile.GENDER_MALE, firstname='Luke', lastname='Skywalker', planet='Tatooine', ) factories.ProfileFactory( gender=objects.Profile.GENDER_FEMALE, firstname='Leia', lastname='Organa', planet='Alderaan', ) ``` -------------------------------- ### Django FileField Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Demonstrates creating a FileField with specific data and how to set it to None to disable generation. ```python class MyFactory(factory.django.DjangoModelFactory): class Meta: model = models.MyModel the_file = factory.django.FileField(filename='the_file.dat') ``` -------------------------------- ### Call and override SubFactory fields Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Examples of instantiating factories and overriding fields within a SubFactory. ```pycon >>> c = CompanyFactory() >>> c # Notice that the first_name was overridden >>> c.owner >>> c.owner.email jack.de@example.org ``` ```pycon >>> c = CompanyFactory(owner__first_name='Henry') >>> c.owner # Notice that the updated first_name was propagated to the email LazyAttribute. >>> c.owner.email henry.doe@example.org # It is also possible to override other fields of the SubFactory >>> c = CompanyFactory(owner__last_name='Jones') >>> c.owner >>> c.owner.email henry.jones@example.org ``` -------------------------------- ### FuzzyInteger Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/fuzzy.md Demonstrates how to set the low and high bounds for FuzzyInteger. If only one argument is provided, it is used as the high bound and the low bound defaults to 0. ```python >>> fi = FuzzyInteger(0, 42) >>> fi.low, fi.high 0, 42 >>> fi = FuzzyInteger(42) >>> fi.low, fi.high 0, 42 ``` -------------------------------- ### Configure scoped_session for tests Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Examples showing how to define, use, and configure a scoped_session for factory_boy in a test environment. ```python # myproject/test/common.py from sqlalchemy import orm Session = orm.scoped_session(orm.sessionmaker()) ``` ```python # myproject/factories.py import factory from . import models from .test import common class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = models.User # Use the not-so-global scoped_session # Warning: DO NOT USE common.Session()! sqlalchemy_session = common.Session name = factory.Sequence(lambda n: "User %d" % n) ``` ```python # myproject/test/runtests.py import sqlalchemy from . import common def runtests(): engine = sqlalchemy.create_engine('sqlite://') # It's a scoped_session, and now is the time to configure it. common.Session.configure(bind=engine) run_the_tests ``` ```python # myproject/test/test_stuff.py import unittest from . import common class MyTest(unittest.TestCase): def setUp(self): # Prepare a new, clean session self.session = common.Session() def test_something(self): u = factories.UserFactory() self.assertEqual([u], self.session.query(User).all()) def tearDown(self): # Rollback the session => no changes to the database self.session.rollback() # Remove it, so that the next test gets a new Session() common.Session.remove() ``` -------------------------------- ### Django ImageField Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Illustrates defining an ImageField with custom color and how to disable its generation. ```python class MyFactory(factory.django.DjangoModelFactory): class Meta: model = models.MyModel the_image = factory.django.ImageField(color='blue') ``` -------------------------------- ### Example Factory Declaration Source: https://github.com/factoryboy/factory_boy/blob/master/docs/internals.md A comprehensive factory definition demonstrating traits, fuzzy fields, conditional logic, and related factories. ```default class UserFactory(factory.Factory): class Meta: model = User class Params: # Allow us to quickly enable staff/superuser flags superuser = factory.Trait( is_superuser=True, is_staff=True, ) # Meta parameter handling all 'enabled'-related fields enabled = True # Classic fields username = factory.Faker('user_name') full_name = factory.Faker('name') creation_date = factory.fuzzy.FuzzyDateTime( datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc), datetime.datetime(2015, 12, 31, 20, tzinfo=datetime.timezone.utc) ) # Conditional flags is_active = factory.SelfAttribute('enabled') deactivation_date = factory.Maybe( 'enabled', None, factory.fuzzy.FuzzyDateTime( datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) - datetime.timedelta(days=10), datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) - datetime.timedelta(days=1), ), ) # Related logs creation_log = factory.RelatedFactory( UserLogFactory, factory_related_name='user', action='create', timestamp=factory.SelfAttribute('user.creation_date'), ) ``` -------------------------------- ### Refine a Factory for Specific Variants Source: https://github.com/factoryboy/factory_boy/blob/master/docs/examples.md This example shows how to create a specialized factory (FemaleProfileFactory) by inheriting from a base factory (ProfileFactory) and overriding specific attributes like gender and firstname, and modifying related attributes like account__username. ```python class FemaleProfileFactory(ProfileFactory): gender = objects.Profile.GENDER_FEMALE firstname = 'Jane' account__username = factory.Sequence(lambda n: 'jane%s' % n) ``` -------------------------------- ### Django FileField Usage Examples Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Shows how to read file data and how to disable FileField generation by passing None. ```python >>> MyFactory(the_file__data=b'uhuh').the_file.read() b'uhuh' ``` ```python >>> MyFactory(the_file=None).the_file None ``` -------------------------------- ### Django ImageField Usage Examples Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Demonstrates accessing image properties like width and disabling ImageField generation. ```python >>> MyFactory(the_image__width=42).the_image.width 42 ``` ```python >>> MyFactory(the_image=None).the_image None ``` -------------------------------- ### Define standard and nested factories Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Basic setup for a factory and a factory that uses a SubFactory to manage related objects. ```python class UserFactory(factory.Factory): class Meta: model = User # Various fields first_name = 'John' last_name = factory.Sequence(lambda n: 'D%se' % ('o' * n)) # De, Doe, Dooe, Doooe, ... email = factory.LazyAttribute(lambda o: '%s.%s@example.org' % (o.first_name.lower(), o.last_name.lower())) # A factory for an object with a 'User' field class CompanyFactory(factory.Factory): class Meta: model = Company name = factory.Sequence(lambda n: 'FactoryBoyz' + 'z' * n) # Let's use our UserFactory to create that user, and override its first name. owner = factory.SubFactory(UserFactory, first_name='Jack') ``` -------------------------------- ### FuzzyFloat Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/fuzzy.md Illustrates setting the inclusive range for FuzzyFloat. If only the high bound is provided, the low bound defaults to 0.0. ```python >>> FuzzyFloat(0.5, 42.7) >>> fi.low, fi.high 0.5, 42.7 >>> fi = FuzzyFloat(42.7) >>> fi.low, fi.high 0.0, 42.7 ``` -------------------------------- ### Mute Signals Decorator Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Shows how to use the mute_signals decorator to prevent specific signals from being emitted during factory calls. ```python # foo/factories.py import factory from . import models from . import signals @factory.django.mute_signals(signals.pre_save, signals.post_save) class FooFactory(factory.django.DjangoModelFactory): class Meta: model = models.Foo # ... ``` -------------------------------- ### Mute Signals During Factory Creation Source: https://context7.com/factoryboy/factory_boy/llms.txt Provides an example of using the 'mute_signals' context manager to temporarily disable signals, such as 'post_save', during factory creation. ```python def create_test_data(): with mute_signals(post_save): users = UserFactory.create_batch(10) return users ``` -------------------------------- ### Mute Signals Context Manager Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Demonstrates using mute_signals as a context manager to disable signals within a specific block of code. ```python def make_chain(): with factory.django.mute_signals(signals.pre_save, signals.post_save): # pre_save/post_save won't be called here. return SomeFactory(), SomeOtherFactory() ``` -------------------------------- ### Example of factory.Maybe Usage Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Demonstrates the behavior of factory.Maybe with different values for the 'is_active' field. When 'is_active' is True, 'deactivation_date' is None. When 'is_active' is False, 'deactivation_date' is set to a fuzzy datetime. ```python >>> u = UserFactory(is_active=True) >>> u.deactivation_date None >>> u = UserFactory(is_active=False) >>> u.deactivation_date datetime.datetime(2017, 4, 1, 23, 21, 23, tzinfo=UTC) ``` -------------------------------- ### Build Documentation Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Build the project documentation using setup.py and make. ```sh python setup.py egg_info make doc ``` -------------------------------- ### Use factory instantiation strategies Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Demonstrates the build and create strategies for generating object instances. ```python # Returns a User instance that's not saved user = UserFactory.build() # Returns a saved User instance. # UserFactory must subclass an ORM base class, such as DjangoModelFactory. user = UserFactory.create() ``` -------------------------------- ### Use factory strategies Source: https://github.com/factoryboy/factory_boy/blob/master/docs/introduction.md Demonstrates the difference between build and create strategies for object instantiation. ```python class MyFactory(factory.Factory): class Meta: model = MyClass ``` ```pycon >>> MyFactory.create() >>> MyFactory.build() >>> MyFactory() # equivalent to MyFactory.create() ``` -------------------------------- ### Use factory instantiation strategies Source: https://github.com/factoryboy/factory_boy/blob/master/docs/index.md Demonstrates the build, create, and stub methods for generating objects. ```python # Returns a User instance that's not saved user = UserFactory.build() # Returns a saved User instance. # UserFactory must subclass an ORM base class, such as DjangoModelFactory. user = UserFactory.create() # Returns a stub object (just a bunch of attributes) obj = UserFactory.stub() ``` -------------------------------- ### Simple Instance Generation Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use factory.simple_generate for a straightforward way to generate instances, abstracting the strategy choice. ```python factory.simple_generate(klass, create, FACTORY_CLASS=None, **kwargs) ``` -------------------------------- ### Overriding LazyFunction Values Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md LazyFunction values can be overridden during factory instantiation, as shown in this example with a timestamp. ```python LogFactory(timestamp=now - timedelta(days=1)) ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Launch the complete test suite for Factory Boy using the make command. ```sh make testall ``` -------------------------------- ### Batch Creation with SQLAlchemy Factories Source: https://context7.com/factoryboy/factory_boy/llms.txt Shows how to create multiple instances of Author and Book models efficiently using create_batch. ```python # Batch creation authors = AuthorFactory.create_batch(5) books = BookFactory.create_batch(10) ``` -------------------------------- ### Create an Instance with factory.create Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use factory.create to create an instance of a class using a dynamically generated factory. This method uses the CREATE_STRATEGY. ```python factory.create(klass, FACTORY_CLASS=None, **kwargs) ``` -------------------------------- ### Basic Faker Integration in Factory Boy Source: https://context7.com/factoryboy/factory_boy/llms.txt Demonstrates using basic Faker providers like name, email, address, and phone number. Also shows how to use date range providers and override locales for specific fields. ```python import factory from datetime import date class Person: def __init__(self, name, email, address, phone, bio, birthdate, company): self.name = name self.email = email self.address = address self.phone = phone self.bio = bio self.birthdate = birthdate self.company = company class PersonFactory(factory.Factory): class Meta: model = Person # Basic Faker providers name = factory.Faker("name") email = factory.Faker("email") address = factory.Faker("address") phone = factory.Faker("phone_number") bio = factory.Faker("paragraph", nb_sentences=3) # Date range provider birthdate = factory.Faker( "date_between_dates", date_start=date(1970, 1, 1), date_end=date(2000, 12, 31) ) company = factory.Faker("company") ``` ```python # Override locale for specific field class FrenchPersonFactory(factory.Factory): class Meta: model = Person name = factory.Faker("name", locale="fr_FR") email = factory.Faker("email") address = factory.Faker("address", locale="fr_FR") phone = factory.Faker("phone_number", locale="fr_FR") bio = factory.Faker("paragraph", locale="fr_FR") birthdate = factory.Faker("date_of_birth") company = factory.Faker("company", locale="fr_FR") ``` -------------------------------- ### Basic Factory Usage in Python Source: https://context7.com/factoryboy/factory_boy/llms.txt Define a factory for a model with default attributes and demonstrate overriding them. Shows build and create strategies, and batch creation. ```python import factory # Simple model class class User: def __init__(self, username, email, is_active=True): self.username = username self.email = email self.is_active = is_active # Define a factory for the User model class UserFactory(factory.Factory): class Meta: model = User username = "john_doe" email = "john@example.com" is_active = True # Usage examples user1 = UserFactory() # Creates User with defaults # user1.username == "john_doe" # user1.email == "john@example.com" user2 = UserFactory(username="jane_doe", email="jane@example.com") # Override defaults # user2.username == "jane_doe" # Build vs Create strategies built_user = UserFactory.build() # Creates instance without saving created_user = UserFactory.create() # Creates and saves instance (ORM-specific) # Batch creation users = UserFactory.build_batch(5) # Creates list of 5 User instances ``` -------------------------------- ### Instantiate Users with Language Specific Factories Source: https://github.com/factoryboy/factory_boy/blob/master/docs/introduction.md Use different factories to create User instances with specific language attributes. ```python >>> EnglishUserFactory() >>> FrenchUserFactory() ``` -------------------------------- ### Instantiate User Objects Source: https://github.com/factoryboy/factory_boy/blob/master/docs/introduction.md Create new User instances using the defined factory. Default values are used unless overridden. ```python >>> john = UserFactory() ``` ```python >>> jack = UserFactory(firstname="Jack") ``` -------------------------------- ### Build an Instance with factory.build Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use factory.build to create an instance of a class using a dynamically generated factory. This method uses the BUILD_STRATEGY. ```python factory.build(klass, FACTORY_CLASS=None, **kwargs) ``` -------------------------------- ### Use Sequence for Unique Field Values Source: https://github.com/factoryboy/factory_boy/blob/master/docs/introduction.md Employ factory.Sequence to automatically generate unique values for a field, typically starting from 0. ```python class UserFactory(factory.Factory): class Meta: model = models.User username = factory.Sequence(lambda n: 'user%d' % n) ``` -------------------------------- ### Default instantiation shortcut Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Uses the factory class directly as a shortcut for the default create strategy. ```python # Same as UserFactory.create() user = UserFactory() ``` -------------------------------- ### Django GenericForeignKey Model Definition Source: https://github.com/factoryboy/factory_boy/blob/master/docs/recipes.md Example model definition for a TaggedItem that uses Django's GenericForeignKey. This allows the item to be associated with any other model. ```python from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class TaggedItem(models.Model): """Example GenericForeignKey model from django docs""" tag = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag ``` -------------------------------- ### Set Initial Sequence Value via _setup_next_sequence Source: https://github.com/factoryboy/factory_boy/blob/master/docs/recipes.md Set the initial sequence counter value automatically upon the first call by overriding the _setup_next_sequence class method. This is useful for avoiding conflicts with existing data. ```python class AccountFactory(factory.django.DjangoModelFactory): class Meta: model = models.Account @classmethod def _setup_next_sequence(cls): try: return models.Accounts.objects.latest('uid').uid + 1 except models.Account.DoesNotExist: return 1 ``` ```python >>> Account.objects.create(uid=42, name="Blah") >>> AccountFactory.create() # Sets up the account number based on the latest uid ``` -------------------------------- ### List Tox Environments Source: https://github.com/factoryboy/factory_boy/blob/master/docs/index.md View all available tox testing environments by running 'tox --listenvs'. This command is useful for understanding the different testing configurations. ```sh $ tox --listenvs ``` -------------------------------- ### Define factories Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Shows how to define factories by specifying the model in a Meta class and setting default attributes. ```python import factory from . import models class UserFactory(factory.Factory): class Meta: model = models.User first_name = 'John' last_name = 'Doe' admin = False # Another, different, factory for the same object class AdminFactory(factory.Factory): class Meta: model = models.User first_name = 'Admin' last_name = 'User' admin = True ``` -------------------------------- ### Create an Object Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use the `create` class method to generate a new object using the 'create' strategy. This typically involves persistence. ```python #### *classmethod* create(cls, **kwargs) Provides a new object, using the ‘create’ strategy. ``` -------------------------------- ### FuzzyDecimal Example Source: https://github.com/factoryboy/factory_boy/blob/master/docs/fuzzy.md Shows how to define the low, high, and precision for FuzzyDecimal. Omitting the low bound defaults it to 0.0. Precision controls the number of digits after the decimal point. ```python >>> FuzzyDecimal(0.5, 42.7) >>> fi.low, fi.high 0.5, 42.7 >>> fi = FuzzyDecimal(42.7) >>> fi.low, fi.high 0.0, 42.7 >>> fi = FuzzyDecimal(0.5, 42.7, 3) >>> fi.low, fi.high, fi.precision 0.5, 42.7, 3 ``` -------------------------------- ### Create Strategy Implementation Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md The default create strategy instantiates the model and calls its save method. ```pycon >>> obj = self._associated_class(*args, **kwargs) >>> obj.save() >>> return obj ``` -------------------------------- ### Override Default Create Method in Factory Source: https://github.com/factoryboy/factory_boy/blob/master/docs/recipes.md Override the _create class method to customize how model instances are created, for example, by calling a specific manager method like create_user. ```python class UserFactory(factory.django.DjangoModelFactory): class Meta: model = UserenaSignup username = "l7d8s" email = "my_name@example.com" password = "my_password" @classmethod def _create(cls, model_class, *args, **kwargs): """Override the default ``_create`` with our custom call.""" manager = cls._get_manager(model_class) # The default would use ``manager.create(*args, **kwargs)`` return manager.create_user(*args, **kwargs) ``` -------------------------------- ### Run All Tests Source: https://github.com/factoryboy/factory_boy/blob/master/docs/index.md Execute the entire test suite for factory_boy using the 'make testall' command. This is a standard way to ensure code integrity before contributing. ```sh $ make testall ``` -------------------------------- ### Factory Boy Trait Usage Examples Source: https://context7.com/factoryboy/factory_boy/llms.txt Illustrates how to use defined traits to create different states of an Order object, including chaining traits and overriding trait values during instantiation. ```python # Usage - default pending order order1 = OrderFactory() # order1.status == "pending" # order1.shipped_at is None # Enable shipped trait order2 = OrderFactory(shipped=True) # order2.status == "shipped" # order2.shipped_at == today # order2.tracking_number is set # Enable delivered trait (chains shipped) order3 = OrderFactory(delivered=True) # order3.status == "delivered" # order3.shipped_at is set (from shipped trait) # order3.delivered_at is set # Combine traits order4 = OrderFactory(shipped=True, rush=True) # order4.status == "shipped" # order4.priority == "rush" # order4.total == 149.985 (99.99 * 1.5) # Override trait values order5 = OrderFactory(shipped=True, tracking_number="CUSTOM123") # order5.tracking_number == "CUSTOM123" ``` -------------------------------- ### Build a Batch of Objects Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use `build_batch` to generate a list of objects using the 'build' strategy. Specify the desired size of the list. ```python #### *classmethod* build_batch(cls, size, **kwargs) Provides a list of `size` instances from the [`Factory`](#factory.Factory), through the ‘build’ strategy. ``` -------------------------------- ### Seed Random Engine with Factory Boy Source: https://github.com/factoryboy/factory_boy/blob/master/docs/recipes.md Use this to manage randomness in tests by pushing a selected seed when starting tests. This seeds the random engine used in factory.Faker and factory.fuzzy objects. ```python import factory.random # Pass in any value factory.random.reseed_random('my awesome project') ``` -------------------------------- ### Convert Factory Output to Dict Source: https://github.com/factoryboy/factory_boy/blob/master/docs/recipes.md Use factory.build() with a dict type to get the factory's data as a dictionary. This is useful for injecting data into APIs or other systems that expect dictionary input. ```python class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User first_name = factory.Sequence(lambda n: "Agent %03d" % n) # Agent 000, Agent 001, Agent 002 username = factory.Faker('user_name') ``` ```python factory.build(dict, FACTORY_CLASS=UserFactory) ``` -------------------------------- ### Create a Batch of Objects Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use `create_batch` to generate a list of objects using the 'create' strategy. Specify the desired size of the list. ```python #### *classmethod* create_batch(cls, size, **kwargs) Provides a list of `size` instances from the [`Factory`](#factory.Factory), through the ‘create’ strategy. ``` -------------------------------- ### Calling a Factory Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Instantiate a factory by calling it directly. This invokes the default strategy (create or build). ```python >>> UserFactory() # Calls UserFactory.create() >>> UserFactory(login='john') # Calls UserFactory.create(login='john') ``` -------------------------------- ### List Tox Environments Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst List all available test environments managed by tox. ```sh tox --listenvs ``` -------------------------------- ### Instance Generation Methods Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Methods for building, creating, or stubbing instances using dynamic factories. ```APIDOC ## factory.build / factory.build_batch ### Description Creates a factory and returns an instance (or list of instances) using the BUILD_STRATEGY. ### Parameters - **klass** (type) - Required - Class of the instance to build. - **size** (int) - Required (for batch) - Number of instances to build. - **kwargs** (dict) - Required - Declarations for the factory. - **FACTORY_CLASS** (class) - Optional - Alternate base class. ## factory.create / factory.create_batch ### Description Creates a factory and returns an instance (or list of instances) using the CREATE_STRATEGY. ### Parameters - **klass** (type) - Required - Class of the instance to create. - **size** (int) - Required (for batch) - Number of instances to create. - **kwargs** (dict) - Required - Declarations for the factory. - **FACTORY_CLASS** (class) - Optional - Alternate base class. ## factory.stub / factory.stub_batch ### Description Creates a factory and returns an instance (or list of instances) using the STUB_STRATEGY. ### Parameters - **klass** (type) - Required - Class of the instance to stub. - **size** (int) - Required (for batch) - Number of instances to stub. - **kwargs** (dict) - Required - Declarations for the factory. - **FACTORY_CLASS** (class) - Optional - Alternate base class. ``` -------------------------------- ### Inherit and override factory declarations Source: https://github.com/factoryboy/factory_boy/blob/master/docs/introduction.md Demonstrates creating a base factory and extending it with a subclass that overrides specific fields. ```python class UserFactory(factory.Factory): class Meta: model = base.User firstname = "John" lastname = "Doe" group = 'users' class AdminFactory(UserFactory): admin = True group = 'admins' ``` ```pycon >>> user = UserFactory() >>> user >>> user.group 'users' >>> admin = AdminFactory() >>> admin >>> admin.group # The AdminFactory field has overridden the base field 'admins' ``` -------------------------------- ### Define a basic SQLAlchemy model factory Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Sets up a simple SQLAlchemy model and a corresponding factory using SQLAlchemyModelFactory. ```python from sqlalchemy import Column, Integer, Unicode, create_engine from sqlalchemy.orm import declarative_base, scoped_session, sessionmaker engine = create_engine('sqlite://') session = scoped_session(sessionmaker(bind=engine)) Base = declarative_base() class User(Base): """ A SQLAlchemy simple model class who represents a user """ __tablename__ = 'UserTable' id = Column(Integer(), primary_key=True) name = Column(Unicode(20)) Base.metadata.create_all(engine) import factory class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = User sqlalchemy_session = session # the SQLAlchemy session object id = factory.Sequence(lambda n: n) name = factory.Sequence(lambda n: 'User %d' % n) ``` -------------------------------- ### Dynamic Session Factory with SQLAlchemyModelFactory Source: https://context7.com/factoryboy/factory_boy/llms.txt Illustrates using a dynamic session factory for creating sessions on demand with SQLAlchemyModelFactory. ```python # Using session factory (dynamic session creation) class DynamicSessionFactory(SQLAlchemyModelFactory): class Meta: model = Author sqlalchemy_session_factory = lambda: Session() ``` -------------------------------- ### Simple Batch Object Generation Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use `simple_generate_batch` to create a list of objects, choosing between building or creating based on the `create` parameter. Specify the desired size of the list. ```python #### *classmethod* simple_generate_batch(cls, create, size, **kwargs) Provides a list of `size` instances, either built or created according to `create`. ``` -------------------------------- ### Build a Batch of Instances with factory.build_batch Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use factory.build_batch to create a specified number of instances of a class using a dynamically generated factory. This method uses the BUILD_STRATEGY. ```python factory.build_batch(klass, size, FACTORY_CLASS=None, **kwargs) ``` -------------------------------- ### Propagate strategies to subfactories Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Demonstrates how build or create strategies propagate to nested subfactories. ```pycon >>> c = CompanyFactory() >>> c.pk # Saved to the database 3 >>> c.owner.pk # Saved to the database 8 >>> c = CompanyFactory.build() >>> c.pk # Not saved None >>> c.owner.pk # Not saved either None ``` -------------------------------- ### Define a Basic User Factory Source: https://github.com/factoryboy/factory_boy/blob/master/docs/introduction.md Subclass factory.Factory, define a Meta class with the model, and set default attributes for object instantiation. ```python import factory from . import base class UserFactory(factory.Factory): class Meta: model = base.User firstname = "John" lastname = "Doe" ``` -------------------------------- ### factory.simple_generate_batch Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Generates a batch of instances using a factory. Allows specifying the class, whether to create or build, the number of instances, and factory declarations. ```APIDOC ## factory.simple_generate_batch(klass, create, size, FACTORY_CLASS=None, **kwargs) ### Description Create a factory for `klass` using declarations passed in kwargs; return an instance generated from that factory according to the `create` flag, or a list of `size` instances. ### Parameters #### Path Parameters - **klass** (type) - Required - Class of the instance to generate - **create** (bool) - Required - Whether to build (`False`) or create (`True`) instances - **size** (int) - Required - Number of instances to generate #### Query Parameters - **FACTORY_CLASS** - Optional - Alternate base class (instead of `Factory`) #### Request Body - **kwargs** - Required - Declarations to use for the generated factory ``` -------------------------------- ### SQLAlchemy get_or_create Behavior Source: https://context7.com/factoryboy/factory_boy/llms.txt Demonstrates the 'get_or_create' functionality by creating two authors with the same email, showing that the second call returns the existing author. ```python # get_or_create behavior author1 = AuthorFactory(email="same@example.com") author2 = AuthorFactory(email="same@example.com") # Returns existing # author1.id == author2.id ``` -------------------------------- ### Create a Batch of Instances with factory.create_batch Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use factory.create_batch to create a specified number of instances of a class using a dynamically generated factory. This method uses the CREATE_STRATEGY. ```python factory.create_batch(klass, size, FACTORY_CLASS=None, **kwargs) ``` -------------------------------- ### Simple Object Generation Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use `simple_generate` to create an object, choosing between building (`create=False`) or creating (`create=True`). ```python #### *classmethod* simple_generate(cls, create, **kwargs) Provide a new instance, either built (`create=False`) or created (`create=True`). ``` -------------------------------- ### Defining Factory Parameters Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Shows how to use the Params class to define conditional logic for factory attributes. ```python class ConferenceFactory(factory.Factory): class Meta: model = Conference class Params: duration = 'short' # Or 'long' start_date = factory.fuzzy.FuzzyDate() end_date = factory.LazyAttribute( lambda o: o.start_date + datetime.timedelta(days=2 if o.duration == 'short' else 7) ) sprints_start = factory.LazyAttribute( lambda o: o.end_date - datetime.timedelta(days=0 if o.duration == 'short' else 1) ) ``` ```pycon >>> ConferenceFactory(duration='short') >>> ConferenceFactory(duration='long') ``` -------------------------------- ### Demonstrate django_get_or_create behavior with existing models Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Illustrates that new values passed to a factory are ignored when fetching an existing model via django_get_or_create. ```pycon >>> john = UserFactory(username="john") # Fetches the existing user >>> john.email "john@example.com" >>> john = UserFactory( # Fetches the existing user >>> username="john", # and provides a new email value >>> email="a_new_email@example.com" >>> ) >>> john.email # The email value was not updated "john@example.com" ``` -------------------------------- ### Configure Inline Arguments for Factory Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md When a factory's model requires non-keyword arguments for its `__init__`, list them in order in the `inline_args` attribute of the `Meta` class. ```python class UserFactory(factory.Factory): class Meta: model = User inline_args = ('login', 'email') login = 'john' email = factory.LazyAttribute(lambda o: '%s@example.com' % o.login) firstname = "John" ``` -------------------------------- ### Use Factories in Unit Tests Source: https://github.com/factoryboy/factory_boy/blob/master/docs/examples.md Demonstrates how to use FactoryBoy factories within a unittest to create objects for testing business logic. It shows creating a single account and then batches of profiles with specific overrides. ```python import unittest from . import business_logic from . import factories from . import objects class MyTestCase(unittest.TestCase): def test_send_mail(self): account = factories.AccountFactory() email = business_logic.prepare_email(account, subject='Foo', text='Bar') self.assertEqual(email.to, account.email) def test_get_profile_stats(self): profiles = [] profiles.extend(factories.ProfileFactory.create_batch(4)) profiles.extend(factories.FemaleProfileFactory.create_batch(2)) profiles.extend(factories.ProfileFactory.create_batch(2, planet="Tatooine")) stats = business_logic.profile_stats(profiles) self.assertEqual({'Earth': 6, 'Mars': 2}, stats.planets) self.assertLess(stats.genders[objects.Profile.GENDER_FEMALE], 2) ``` -------------------------------- ### Verify factory creation with session Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Interactive check to verify that the factory correctly persists objects to the SQLAlchemy session. ```pycon >>> session.query(User).all() [] >>> UserFactory() >>> session.query(User).all() [] ``` -------------------------------- ### Factory Strategies Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Explains the different strategies available for generating model instances with Factory Boy. ```APIDOC ### Strategies factory_boy supports two main strategies for generating instances, plus stubs. #### `factory.BUILD_STRATEGY` The ‘build’ strategy is used when an instance should be created, but not persisted to any datastore. It is usually a simple call to the `__init__()` method of the model class. #### `factory.CREATE_STRATEGY` The ‘create’ strategy builds and saves an instance into its appropriate datastore. This is the default strategy. It typically instantiates an object, then saves it. ```python # Example of create strategy logic obj = self._associated_class(*args, **kwargs) obj.save() return obj ``` #### `factory.STUB_STRATEGY` The ‘stub’ strategy doesn’t return an instance of the model class and doesn’t require one to be present. Instead, it returns an instance of `StubObject` whose attributes have been set according to the declarations. ### `factory.use_strategy(strategy)` **Deprecated since version 3.2:** Use `factory.FactoryOptions.strategy` instead. *Decorator* Changes the default strategy of the decorated `Factory` to the chosen `strategy`. ```python @factory.use_strategy(factory.BUILD_STRATEGY) class UserBuildingFactory(UserFactory): pass ``` ### *class* `factory.StubObject` A plain object with no methods, simply a bunch of attributes. ```python # Example of StubObject usage obj = factory.StubObject() obj.x = 1 obj.y = 2 ``` ### *class* `factory.StubFactory(Factory)` An abstract `Factory`, with a default strategy set to `STUB_STRATEGY`. ``` -------------------------------- ### Compare factory_boy with manual object creation Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Demonstrates how factory_boy reduces boilerplate code when setting up complex test objects compared to manual instantiation. ```python class FooTests(unittest.TestCase): def test_with_factory_boy(self): # We need a 200€, paid order, shipping to australia, for a VIP customer order = OrderFactory( amount=200, status='PAID', customer__is_vip=True, address__country='AU', ) # Run the tests here def test_without_factory_boy(self): address = Address( street="42 fubar street", zipcode="42Z42", city="Sydney", country="AU", ) customer = Customer( first_name="John", last_name="Doe", phone="+1234", email="john.doe@example.org", active=True, is_vip=True, address=address, ) # etc. ``` -------------------------------- ### Generate an Instance with a Specific Strategy Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use factory.generate to create an instance of a class using a dynamically generated factory with a specified strategy. ```python factory.generate(klass, strategy, FACTORY_CLASS=None, **kwargs) ``` -------------------------------- ### Use Non-Default Database with DjangoModelFactory Source: https://context7.com/factoryboy/factory_boy/llms.txt Illustrates how to specify a non-default database for a factory by setting the 'database' attribute in the Meta class. ```python class MultiDbUserFactory(DjangoModelFactory): class Meta: model = "myapp.User" database = "replica" # Use 'replica' database ``` -------------------------------- ### Run Test Coverage Source: https://github.com/factoryboy/factory_boy/blob/master/README.rst Generate a test coverage report for Factory Boy using the make command. ```sh make coverage ``` -------------------------------- ### Build an Object Source: https://github.com/factoryboy/factory_boy/blob/master/docs/reference.md Use the `build` class method to create a new object using the 'build' strategy. This does not persist the object. ```python #### *classmethod* build(cls, **kwargs) Provides a new object, using the ‘build’ strategy. ``` -------------------------------- ### Implement SQLAlchemy get_or_create Source: https://github.com/factoryboy/factory_boy/blob/master/docs/orms.md Define fields in sqlalchemy_get_or_create to perform lookup queries instead of always creating new records. ```python class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = User sqlalchemy_session = session sqlalchemy_get_or_create = ('username',) username = 'john' ``` ```pycon >>> User.query.all() [] >>> UserFactory() # Creates a new user >>> User.query.all() [] >>> UserFactory() # Fetches the existing user >>> User.query.all() # No new user! [] >>> UserFactory(username='jack') # Creates another user >>> User.query.all() [, ] ```