### Basic SQLAlchemy Model and Factory Setup Source: https://factoryboy.readthedocs.io/en/stable/orms.html A simple example demonstrating the setup of a SQLAlchemy User model and its corresponding Factory. ```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) ``` -------------------------------- ### SQLAlchemy Example: Configuring Session and Get or Create Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Shows how to set a specific SQLAlchemy session and define fields for the get_or_create functionality. ```python class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = User sqlalchemy_session = session sqlalchemy_get_or_create = ('username',) username = 'john' ``` -------------------------------- ### Install Factory Boy from Source Source: https://factoryboy.readthedocs.io/en/stable/index.html Clone the factory_boy repository and install it using setup.py. This method is useful for developers or those needing the latest unreleased code. ```bash $ git clone git://github.com/FactoryBoy/factory_boy/ $ python setup.py install ``` -------------------------------- ### SQLAlchemy Example: Get or Create Behavior Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Illustrates the behavior of the get_or_create option in SQLAlchemyModelFactory, showing creation and fetching of existing objects. ```python >>> User.query.all() [] >>> UserFactory() # Creates a new user >>> User.query.all() [] >>> UserFactory() # Fetches the existing user >>> User.query.all() # No new user! [] ``` -------------------------------- ### Global Scoped Session Setup in Tests Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Example of setting up a project-wide scoped session for use in tests. ```python # myproject/test/common.py from sqlalchemy import orm Session = orm.scoped_session(orm.sessionmaker()) ``` -------------------------------- ### Install Factory Boy with Pip Source: https://factoryboy.readthedocs.io/en/stable/index.html Use pip to install the factory_boy package. This is the recommended method for most users. ```bash $ pip install factory_boy ``` -------------------------------- ### Install Development Dependencies Source: https://factoryboy.readthedocs.io/en/stable/index.html Install development dependencies in a virtual environment using pip. ```bash pip install --editable '.[dev]' ``` -------------------------------- ### MongoEngine Factory Example Source: https://factoryboy.readthedocs.io/en/stable/orms.html Example demonstrating how to use MongoEngineFactory with EmbeddedDocument and SubFactory for creating nested documents. ```python import mongoengine class Address(mongoengine.EmbeddedDocument): street = mongoengine.StringField() class Person(mongoengine.Document): name = mongoengine.StringField() address = mongoengine.EmbeddedDocumentField(Address) import factory class AddressFactory(factory.mongoengine.MongoEngineFactory): class Meta: model = Address street = factory.Sequence(lambda n: 'street%d' % n) class PersonFactory(factory.mongoengine.MongoEngineFactory): class Meta: model = Person name = factory.Sequence(lambda n: 'name%d' % n) address = factory.SubFactory(AddressFactory) ``` -------------------------------- ### SQLAlchemy Example: Configuring Session Factory Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Demonstrates how to configure a SQLAlchemy session factory within a factory's Meta class. ```python from . import common class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = User sqlalchemy_session_factory = lambda: common.Session() username = 'john' ``` -------------------------------- ### Create Django Model Factory with make_factory Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt This example demonstrates using `make_factory` to create a `factory.django.DjangoModelFactory`. It specifies a custom `FACTORY_CLASS` and defines attributes similar to the previous example. ```python UserFactory = make_factory(models.User, login='john', email=factory.LazyAttribute(lambda u: '%s@example.com' % u.login), FACTORY_CLASS=factory.django.DjangoModelFactory, ) # This is equivalent to: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User login = 'john' email = factory.LazyAttribute(lambda u: '%s@example.com' % u.login) ``` -------------------------------- ### Example of CREATE_STRATEGY Source: https://factoryboy.readthedocs.io/en/stable/reference.html Illustrates the default create strategy which builds and saves an instance. This typically involves instantiating an object and then calling its save method. ```python >>> obj = self._associated_class(*args, **kwargs) >>> obj.save() >>> return obj ``` -------------------------------- ### Debug Output Example Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt An example of the debug output generated when using the `factory.debug()` context manager. This output helps in diagnosing issues by showing factory creation steps. ```ini # Example debug output (artificial indentation): # [DEBUG] factory.debug: Creating instance of TestModel2Factory # [DEBUG] factory.debug: - attribute 'field1': value 'some_value' # [DEBUG] factory.debug: - attribute 'field2': value 123 # [DEBUG] factory.debug: Instance created: ``` -------------------------------- ### SQLAlchemy Model and Factory Setup Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Defines a simple SQLAlchemy User model and its corresponding factory, including session configuration. ```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) ``` -------------------------------- ### MongoEngine Example: Creating Address and Person Factories Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Sets up factories for the previously defined MongoEngine models, including sequence and subfactory usage. ```python import factory class AddressFactory(factory.mongoengine.MongoEngineFactory): class Meta: model = Address street = factory.Sequence(lambda n: 'street%d' % n) class PersonFactory(factory.mongoengine.MongoEngineFactory): class Meta: model = Person name = factory.Sequence(lambda n: 'name%d' % n) address = factory.SubFactory(AddressFactory) ``` -------------------------------- ### Using SQLAlchemyModelFactory with Get or Create Source: https://factoryboy.readthedocs.io/en/stable/orms.html Demonstrates the behavior of UserFactory when sqlalchemy_get_or_create is enabled, showing creation and fetching of users. ```python >>> 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() [, ] ``` -------------------------------- ### Example Factory Declaration Source: https://factoryboy.readthedocs.io/en/stable/internals.html This is a comprehensive example of a factory declaration, showcasing various features like Meta options, Params, Traits, Faker fields, fuzzy date times, conditional flags, and RelatedFactories. ```python 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'), ) ``` -------------------------------- ### Django Password Field Usage Examples Source: https://factoryboy.readthedocs.io/en/stable/orms.html Demonstrates creating users with default, overridden, and unusable passwords using the UserFactory. ```python >>> from django.contrib.auth.hashers import check_password >>> # Create user with the default password from the factory. >>> user = UserFactory.create() >>> check_password('pw', user.password) True >>> # Override user password at call time. >>> other_user = UserFactory.create(password='other_pw') >>> check_password('other_pw', other_user.password) True >>> # Set unusable password >>> no_password_user = UserFactory.create(password=None) >>> no_password_user.has_usable_password() False ``` -------------------------------- ### Iterator Usage Example Source: https://factoryboy.readthedocs.io/en/stable/reference.html Shows how Iterator assigns successive values on each factory instantiation. ```python >>> UserFactory().lang 'en' >>> UserFactory().lang 'fr' ``` -------------------------------- ### Customizing Instance Creation with _create Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Illustrates how to override the `_create` class method in a Factory subclass to customize the instance creation process. This example shows a base backend factory that saves the created object. ```python class BaseBackendFactory(factory.Factory): class Meta: abstract = True # Optional @classmethod def _create(cls, model_class, *args, **kwargs): obj = model_class(*args, **kwargs) obj.save() return obj ``` -------------------------------- ### Forcing Sequence Counter Example Source: https://factoryboy.readthedocs.io/en/stable/reference.html Illustrates forcing the sequence counter to a specific value for an instance. ```python >>> UserFactory() >>> UserFactory() >>> UserFactory(__sequence=42) ``` -------------------------------- ### Generate User with Faker Name Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Example of creating a User instance and accessing the generated 'name' field. ```python >>> user = UserFactory() >>> user.name 'Lucy Cechtelar' ``` -------------------------------- ### Faker with Provider Parameters Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Demonstrates using Faker with providers that accept parameters. This example generates a date within a specific range. ```python class UserFactory(factory.Factory): class Meta: model = User arrival = factory.Faker( 'date_between_dates', date_start=datetime.date(2020, 1, 1), date_end=datetime.date(2020, 5, 31), ) ``` -------------------------------- ### Setting Initial Sequence Value via _setup_next_sequence Source: https://factoryboy.readthedocs.io/en/stable/_sources/recipes.rst.txt Override _setup_next_sequence to define the starting value for the sequence counter when the factory is first used. This prevents 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 ``` -------------------------------- ### SubFactory Declaration Example Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Illustrates how to declare a SubFactory, which calls another Factory subclass. It shows the correct way to pass the Factory class (not an instance) and optional keyword arguments. ```python class FooFactory(factory.Factory): class Meta: model = Foo bar = factory.SubFactory(BarFactory) # Not BarFactory() ``` -------------------------------- ### Generate Log with LazyFunction Timestamp Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Example of creating a Log instance and observing the 'timestamp' field populated by the LazyFunction. ```python >>> LogFactory() ``` -------------------------------- ### Example Debug Output Source: https://factoryboy.readthedocs.io/en/stable/reference.html Illustrates the type of detailed log messages generated when using the factory.debug() context manager, showing the internal steps of factory instantiation and value computation. ```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=) ``` -------------------------------- ### Django FileField Usage Examples Source: https://factoryboy.readthedocs.io/en/stable/orms.html Shows how to create a model instance with file data and how to set the file field to None. ```python >>> MyFactory(the_file__data=b'uhuh').the_file.read() b'uhuh' >>> MyFactory(the_file=None).the_file None ``` -------------------------------- ### MongoEngine Example: Defining Address and Person Models Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Defines embedded and document models for MongoEngine, which will be used with corresponding factories. ```python import mongoengine class Address(mongoengine.EmbeddedDocument): street = mongoengine.StringField() class Person(mongoengine.Document): name = mongoengine.StringField() address = mongoengine.EmbeddedDocumentField(Address) ``` -------------------------------- ### Example: Django Profile Creation with Signals Source: https://factoryboy.readthedocs.io/en/stable/_sources/recipes.rst.txt Demonstrates creating a Django User and its associated Profile using RelatedFactory, while muting post_save signals to avoid double profile creation. ```pycon >>> u = UserFactory(profile__title="Lord") >>> u.get_profile().title "Lord" ``` -------------------------------- ### PostGeneration with Decorator Source: https://factoryboy.readthedocs.io/en/stable/reference.html Implements a post-generation action using a decorator, allowing for more complex logic. This example creates a directory for mailboxes, with an option to specify a custom path. ```python class UserFactory(factory.Factory): class Meta: model = User login = 'john' @factory.post_generation def mbox(obj, create, extracted, **kwargs): if not create: return path = extracted or os.path.join('/tmp/mbox/', obj.login) os.path.makedirs(path) ``` -------------------------------- ### Build Documentation Source: https://factoryboy.readthedocs.io/en/stable/index.html Run the build steps for documentation, including egg_info. ```bash python setup.py egg_info make doc ``` -------------------------------- ### Use Factories for Fixtures Source: https://factoryboy.readthedocs.io/en/stable/_sources/examples.rst.txt This example shows how to use FactoryBoy factories to generate fixtures for a test environment. It includes creating a large batch and specific, known objects. ```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', ) ``` -------------------------------- ### Build and Create User Factories with Post-Generation Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt These examples show how to use the `UserFactory` defined previously. They illustrate building an object without creation, creating objects with default and custom paths, and creating objects with different logins. ```pycon >>> 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 ``` -------------------------------- ### StubObject Instantiation and Attribute Setting Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Example of creating a StubObject and manually setting its attributes. StubObjects are plain objects used when persistence is not required and a model class is not available or needed. ```pycon >>> obj = StubObject() >>> obj.x = 1 >>> obj.y = 2 ``` -------------------------------- ### Run All Tests Source: https://factoryboy.readthedocs.io/en/stable/index.html Launch the complete test suite for the project. ```bash make testall ``` -------------------------------- ### Build Batch of Objects Source: https://factoryboy.readthedocs.io/en/stable/index.html Create multiple objects in a single call using `build_batch`. This example creates 10 user objects, all with the `first_name` overridden to 'Joe'. ```python >>> users = UserFactory.build_batch(10, first_name="Joe") >>> len(users) 10 >>> [user.first_name for user in users] ["Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe"] ``` -------------------------------- ### Using the Basic SQLAlchemy Factory Source: https://factoryboy.readthedocs.io/en/stable/orms.html Demonstrates creating a User instance using the defined UserFactory and verifying its presence in the session. ```python >>> session.query(User).all() [] >>> UserFactory() >>> session.query(User).all() [] ``` -------------------------------- ### Instantiating a Factory Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Demonstrates the basic usage of calling a Factory class to create or build objects. It shows how to pass keyword arguments to customize the created instance. ```pycon >>> UserFactory() # Calls UserFactory.create() >>> UserFactory(login='john') # Calls UserFactory.create(login='john') ``` -------------------------------- ### Django Models for Factory Boy Examples Source: https://factoryboy.readthedocs.io/en/stable/recipes.html Defines Django models for Country, User, and Company, which are used in subsequent factory boy examples. ```python class Country(models.Model): name = models.CharField() lang = models.CharField() class User(models.Model): name = models.CharField() lang = models.CharField() country = models.ForeignKey(Country) class Company(models.Model): name = models.CharField() owner = models.ForeignKey(User) country = models.ForeignKey(Country) ``` -------------------------------- ### __setup_next_sequence(_cls_) Source: https://factoryboy.readthedocs.io/en/stable/reference.html Computes the first value for the sequence counter. ```APIDOC ## _classmethod __setup_next_sequence(_cls_) ### Description This method will compute the first value to use for the sequence counter of this factory. It is called when the first instance of the factory (or one of its subclasses) is created. Subclasses may fetch the next free ID from the database, for instance. ### Method classmethod ``` -------------------------------- ### Generate Timezone-Aware Datetime Range - FuzzyDateTime Source: https://factoryboy.readthedocs.io/en/stable/_sources/fuzzy.rst.txt Instantiate FuzzyDateTime with a start date. The end date defaults to the current UTC time. The output shows the default start and end datetimes. ```pycon >>> fdt = FuzzyDateTime(datetime.datetime(2008, 1, 1, tzinfo=UTC)) >>> fdt.start_dt, fdt.end_dt datetime.datetime(2008, 1, 1, tzinfo=UTC), datetime.datetime(2013, 4, 21, 19, 13, 32, 458487, tzinfo=UTC) ``` -------------------------------- ### Instantiate Factory with Simple Parameters Source: https://factoryboy.readthedocs.io/en/stable/reference.html Demonstrates creating model instances using the `ConferenceFactory` with different `duration` parameters. ```python >>> ConferenceFactory(duration='short') >>> ConferenceFactory(duration='long') ``` -------------------------------- ### factory_boy vs. Manual Object Creation Source: https://factoryboy.readthedocs.io/en/stable/index.html Compares creating an order object using factory_boy with manual instantiation. factory_boy allows specifying only test-specific fields, simplifying complex object setup. ```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 Naive Datetime Range - FuzzyNaiveDateTime Source: https://factoryboy.readthedocs.io/en/stable/_sources/fuzzy.rst.txt Instantiate FuzzyNaiveDateTime with a start date. The end date defaults to the current local time. The output shows the default start and end naive datetimes. ```pycon >>> fdt = FuzzyNaiveDateTime(datetime.datetime(2008, 1, 1)) >>> fdt.start_dt, fdt.end_dt datetime.datetime(2008, 1, 1), datetime.datetime(2013, 4, 21, 19, 13, 32, 458487) ``` -------------------------------- ### Factory Strategies: Create vs. Build Source: https://factoryboy.readthedocs.io/en/stable/_sources/introduction.rst.txt Demonstrates the difference between 'create' (saves to DB) and 'build' (in-memory object) strategies, and how calling a factory directly defaults to 'create'. ```python class MyFactory(factory.Factory): class Meta: model = MyClass ``` -------------------------------- ### Conditional Field Example - True Case Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt When 'is_active' is True, the 'deactivation_date' is set to None. ```python >>> u = UserFactory(is_active=True) >>> u.deactivation_date None ``` -------------------------------- ### Factory Build Batch Strategy Source: https://factoryboy.readthedocs.io/en/stable/reference.html Demonstrates how to create a list of instances using the `_build_batch` class method with the 'build' strategy. ```python _classmethod _build_batch(_cls_ , _size_ , _** kwargs_) ``` -------------------------------- ### Create Instance Helper Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html A shortcut to create a factory for a given class and then create a single instance, typically involving saving it to a database. ```python def create(klass, **kwargs): """Create a factory for the given class, and create an instance.""" return make_factory(klass, **kwargs).create() ``` -------------------------------- ### Django Models with GenericForeignKeys Source: https://factoryboy.readthedocs.io/en/stable/_sources/recipes.rst.txt Example models and factories for Django models utilizing `GenericForeignKey`. ```python from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class TaggedItem(models.Model): 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 "{}: {}".format(self.content_type, self.object_id) class Blog(models.Model): title = models.CharField(max_length=100) body = models.TextField() tags = models.ManyToManyField(TaggedItem, related_name='blogs') def __str__(self): return self.title class Book(models.Model): title = models.CharField(max_length=100) body = models.TextField() tags = models.ManyToManyField(TaggedItem, related_name='books') def __str__(self): return self.title ``` ```python import factory from .models import TaggedItem, Blog, Book class TaggedItemFactory(factory.Factory): class Meta: model = TaggedItem tag = factory.Sequence(lambda n: 'tag-{}'.format(n)) content_type = factory.LazyAttribute( lambda o: ContentType.objects.get_for_model(o.content_object) ) object_id = factory.LazyAttribute(lambda o: o.content_object.pk) # We need to define content_object as a placeholder content_object = factory.SubFactory(BlogFactory) # Default to Blog class BlogFactory(factory.Factory): class Meta: model = Blog title = factory.Sequence(lambda n: 'Blog post #%d' % n) body = factory.Faker('text') # We need to define tags as a placeholder tags = factory.RelatedFactory(TaggedItemFactory, 'content_object') class BookFactory(factory.Factory): class Meta: model = Book title = factory.Sequence(lambda n: 'Book title #%d' % n) body = factory.Faker('text') # We need to define tags as a placeholder tags = factory.RelatedFactory(TaggedItemFactory, 'content_object') ``` -------------------------------- ### FuzzyDateTime _check_bounds() method Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/fuzzy.html Validates that the start and end datetimes are timezone-aware and that start_dt is not after end_dt. ```python def _check_bounds(self, start_dt, end_dt): if start_dt.tzinfo is None: raise ValueError( "FuzzyDateTime requires timezone-aware datetimes, got start=%r" % start_dt) if end_dt.tzinfo is None: raise ValueError( "FuzzyDateTime requires timezone-aware datetimes, got end=%r" % end_dt) super()._check_bounds(start_dt, end_dt) ``` -------------------------------- ### FuzzyNaiveDateTime _check_bounds() method Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/fuzzy.html Validates that the start and end datetimes are naive and that start_dt is not after end_dt. ```python def _check_bounds(self, start_dt, end_dt): if start_dt.tzinfo is not None: raise ValueError( "FuzzyNaiveDateTime only handles naive datetimes, got start=%r" % start_dt) if end_dt.tzinfo is not None: raise ValueError( "FuzzyNaiveDateTime only handles naive datetimes, got end=%r" % end_dt) super()._check_bounds(start_dt, end_dt) ``` -------------------------------- ### Create and Query Users with SQLAlchemy Factory Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Demonstrates creating a User instance using UserFactory and querying all users from the session. ```pycon >>> UserFactory(username='jack') # Creates another user >>> User.query.all() [, ] ``` ```pycon >>> session.query(User).all() [] >>> UserFactory() >>> session.query(User).all() [] ``` -------------------------------- ### Conditional Field Example - False Case Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt When 'is_active' is False, the 'deactivation_date' is set to a fuzzy datetime. ```python >>> u = UserFactory(is_active=False) >>> u.deactivation_date datetime.datetime(2017, 4, 1, 23, 21, 23, tzinfo=UTC) ``` -------------------------------- ### SelfAttribute Usage Example Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Shows how a SelfAttribute declaration fetches a nested attribute from the object being created. ```pycon >>> u = UserFactory() >>> u.birthdate date(2000, 3, 15) >>> u.birthmonth 3 ``` -------------------------------- ### FuzzyDate fuzz() method Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/fuzzy.html Generates a random date within the initialized start and end dates. ```python def fuzz(self): return datetime.date.fromordinal(random.randgen.randint(self.start_date, self.end_date)) ``` -------------------------------- ### _simple_generate_batch(_cls_, _create_, _size_, _**kwargs_) Source: https://factoryboy.readthedocs.io/en/stable/reference.html Provides a list of instances, either built or created. ```APIDOC ## _classmethod _simple_generate_batch(_cls_, _create_, _size_, _**kwargs_) ### Description Provides a list of `size` instances, either built or created according to `create`. ### Method classmethod ### Parameters #### Path Parameters - **create** (bool) - Required - If True, instances will be created; otherwise, they will be built. - **size** (int) - Required - The number of instances to generate. #### Keyword Arguments - **kwargs**: Arbitrary keyword arguments for instance generation. ``` -------------------------------- ### Sequence Counter Sharing in Inheritance Example Source: https://factoryboy.readthedocs.io/en/stable/reference.html Demonstrates the shared sequence counter behavior in an inheritance scenario. ```python >>> u = UserFactory() >>> u.phone '123-555-0000' >>> e = EmployeeFactory() >>> e.phone, e.office_phone '123-555-0001', '0001' >>> u2 = UserFactory() >>> u2.phone '123-555-0002' ``` -------------------------------- ### Factory Strategies in Python Console Source: https://factoryboy.readthedocs.io/en/stable/_sources/introduction.rst.txt Illustrates the output of 'create' and 'build' strategies, and the default behavior when calling a factory directly. ```pycon >>> MyFactory.create() >>> MyFactory.build() >>> MyFactory() # equivalent to MyFactory.create() ``` -------------------------------- ### Build Instance Helper Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html A shortcut to create a factory for a given class and then build a single instance of that class. ```python def build(klass, **kwargs): """Create a factory for the given class, and build an instance.""" return make_factory(klass, **kwargs).build() ``` -------------------------------- ### SelfAttribute Parent Referencing Example Source: https://factoryboy.readthedocs.io/en/stable/reference.html Shows how SelfAttribute correctly resolves parent attributes in a nested factory structure. ```python >>> company = CompanyFactory() >>> company.country.language 'fr' >>> company.owner.language 'fr' ``` -------------------------------- ### Simple Generate Instance Helper Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html A shortcut to create a factory for a given class and then perform a simple generation of an instance, using a boolean to indicate creation or building. ```python def simple_generate(klass, create, **kwargs): """Create a factory for the given class, and simple_generate an instance.""" return make_factory(klass, **kwargs).simple_generate(create) ``` -------------------------------- ### Factory Build Strategy Source: https://factoryboy.readthedocs.io/en/stable/reference.html Shows how to use the `_build` class method to create an object using the 'build' strategy, which typically instantiates the model without saving it. ```python _classmethod _build(_cls_ , _** kwargs_) ``` -------------------------------- ### LazyAttributeSequence Example Source: https://factoryboy.readthedocs.io/en/stable/reference.html Demonstrates generating email addresses using LazyAttributeSequence, showing dependency on object attributes and sequence counter. ```python >>> UserFactory().email 'john@s0.example.com' >>> UserFactory(login='jack').email 'jack@s1.example.com' ``` -------------------------------- ### SelfAttribute Parent Navigation Example Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Illustrates how SelfAttribute with '..' notation fetches attributes from parent factories, propagating values. ```pycon >>> company = CompanyFactory() >>> company.country.language 'fr' >>> company.owner.language 'fr' Obviously, this "follow parents" ability also handles overriding some attributes on call: >>> company = CompanyFactory(country=china) >>> company.owner.language 'cn' ``` -------------------------------- ### Generate User with French Locale Source: https://factoryboy.readthedocs.io/en/stable/_sources/reference.rst.txt Example of creating a User instance with a French locale and accessing the generated 'name' field. ```python >>> user = UserFactory() >>> user.name 'Jean Valjean' ``` -------------------------------- ### Generate Instance Helper Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html A shortcut to create a factory for a given class and then generate a single instance using a specified strategy (e.g., 'build', 'create'). ```python def generate(klass, strategy, **kwargs): """Create a factory for the given class, and generate an instance.""" return make_factory(klass, **kwargs).generate(strategy) ``` -------------------------------- ### Instantiate Users with Different Language Defaults Source: https://factoryboy.readthedocs.io/en/stable/_sources/introduction.rst.txt Create user instances using factories with language-specific defaults. ```pycon >>> EnglishUserFactory() >>> FrenchUserFactory() ``` -------------------------------- ### _create_batch(_cls_, _size_, _**kwargs_) Source: https://factoryboy.readthedocs.io/en/stable/reference.html Provides a list of instances using the 'create' strategy. ```APIDOC ## _classmethod _create_batch(_cls_, _size_, _**kwargs_) ### Description Provides a list of `size` instances from the `Factory`, through the ‘create’ strategy. ### Method classmethod ### Parameters #### Path Parameters - **size** (int) - Required - The number of instances to create. #### Keyword Arguments - **kwargs**: Arbitrary keyword arguments for object creation. ``` -------------------------------- ### FileField Usage with Factory Source: https://factoryboy.readthedocs.io/en/stable/_sources/orms.rst.txt Shows how to create instances with FileField data and how to handle None values. ```python MyFactory(the_file__data=b'uhuh').the_file.read() MyFactory(the_file=None).the_file ``` -------------------------------- ### Resetting Sequence Counter to Specific Value Source: https://factoryboy.readthedocs.io/en/stable/_sources/recipes.rst.txt Call reset_sequence(value) to reset the sequence counter to a specific starting number. ```python >>> AccountFactory.reset_sequence(10) >>> AccountFactory().uid 10 >>> AccountFactory().uid 11 ``` -------------------------------- ### Get or Create Behavior with Unused Fields Source: https://factoryboy.readthedocs.io/en/stable/orms.html Illustrates that fields not included in sqlalchemy_get_or_create are not used to update existing models when fetching. ```python >>> 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" ``` -------------------------------- ### Instantiate Factory with SubFactory (Create Strategy) Source: https://factoryboy.readthedocs.io/en/stable/index.html Instantiate a factory that uses `SubFactory`. When using the default `create` strategy, both the main object (`Post`) and the associated object (`User`) are built and saved. ```python # Builds and saves a User and a Post >>> post = PostFactory() >>> post.id is None # Post has been 'saved' False >>> post.author.id is None # post.author has been saved False ``` -------------------------------- ### SQLAlchemyModelFactory with Session and Get or Create Source: https://factoryboy.readthedocs.io/en/stable/orms.html Configures a UserFactory to use a specific SQLAlchemy session and defines fields for the get_or_create logic. ```python class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = User sqlalchemy_session = session sqlalchemy_get_or_create = ('username',) username = 'john' ``` -------------------------------- ### create Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html Creates a factory for the given class and creates an instance. ```APIDOC ## create ### Description Create a factory for the given class, and create an instance. ### Parameters #### Arguments - **klass** (type) - The class for which to create a factory. - **kwargs** - Additional keyword arguments to configure the factory. ``` -------------------------------- ### Django ImageField Usage Examples Source: https://factoryboy.readthedocs.io/en/stable/orms.html Demonstrates overriding image properties like width during creation and setting the image field to None. ```python >>> MyFactory(the_image__width=42).the_image.width 42 >>> MyFactory(the_image=None).the_image None ``` -------------------------------- ### Refine Factory for Specific Variants Source: https://factoryboy.readthedocs.io/en/stable/_sources/examples.rst.txt This example shows how to create a specialized factory, FemaleProfileFactory, by inheriting from ProfileFactory and overriding specific attributes. ```python class FemaleProfileFactory(ProfileFactory): gender = objects.Profile.GENDER_FEMALE firstname = 'Jane' account__username = factory.Sequence(lambda n: 'jane%s' % n) ``` -------------------------------- ### BaseFuzzyDateTime fuzz() method Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/fuzzy.html Generates a random datetime within the initialized start and end datetimes, applying forced components if specified. ```python def fuzz(self): delta = self.end_dt - self.start_dt microseconds = delta.microseconds + 1000000 * (delta.seconds + (delta.days * 86400)) offset = random.randgen.randint(0, microseconds) result = self.start_dt + datetime.timedelta(microseconds=offset) if self.force_year is not None: result = result.replace(year=self.force_year) if self.force_month is not None: result = result.replace(month=self.force_month) if self.force_day is not None: result = result.replace(day=self.force_day) if self.force_hour is not None: result = result.replace(hour=self.force_hour) if self.force_minute is not None: result = result.replace(minute=self.force_minute) if self.force_second is not None: result = result.replace(second=self.force_second) if self.force_microsecond is not None: result = result.replace(microsecond=self.force_microsecond) return result ``` -------------------------------- ### Building Factory Output as a Dictionary Source: https://factoryboy.readthedocs.io/en/stable/recipes.html Demonstrates how to obtain the output of a factory as a dictionary instead of a model instance. This is useful for injecting data into APIs or other systems. ```python >>> factory.build(dict, FACTORY_CLASS=UserFactory) {'first_name': "Agent 000", 'username': 'john_doe'} ``` -------------------------------- ### _FactoryWrapper Get Method Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/declarations.html Retrieves the Factory class associated with the wrapper. If not already loaded, it imports the factory using its module and name. ```python def get(self): if self.factory is None: self.factory = utils.import_object( self.module, self.name, ) return self.factory ``` -------------------------------- ### Build Batch Helper Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html A shortcut to create a factory for a given class and then build a specified number of instances. ```python def build_batch(klass, size, **kwargs): """Create a factory for the given class, and build a batch of instances.""" return make_factory(klass, **kwargs).build_batch(size) ``` -------------------------------- ### Example of Maybe Declaration Usage (Decider False) Source: https://factoryboy.readthedocs.io/en/stable/reference.html Shows the result when the 'is_active' decider field is False. The 'no_declaration' (a FuzzyDateTime) is applied to 'deactivation_date'. ```python >>> u = UserFactory(is_active=False) >>> u.deactivation_date datetime.datetime(2017, 4, 1, 23, 21, 23, tzinfo=UTC) ``` -------------------------------- ### Example of Maybe Declaration Usage (Decider True) Source: https://factoryboy.readthedocs.io/en/stable/reference.html Shows the result when the 'is_active' decider field is True. The 'yes_declaration' (None) is applied to 'deactivation_date'. ```python >>> u = UserFactory(is_active=True) >>> u.deactivation_date None ``` -------------------------------- ### _simple_generate(_cls_, _create_, _**kwargs_) Source: https://factoryboy.readthedocs.io/en/stable/reference.html Provides a new instance, either built or created. ```APIDOC ## _classmethod _simple_generate(_cls_, _create_, _**kwargs_) ### Description Provide a new instance, either built (`create=False`) or created (`create=True`). ### Method classmethod ### Parameters #### Path Parameters - **create** (bool) - Required - If True, the instance will be created; otherwise, it will be built. #### Keyword Arguments - **kwargs**: Arbitrary keyword arguments for instance generation. ``` -------------------------------- ### Defining a Django Model Factory Source: https://factoryboy.readthedocs.io/en/stable/recipes.html Example of a DjangoModelFactory with a sequence for first name and a Faker for username. This factory can be used to build user instances. ```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') ``` -------------------------------- ### Create Batch Helper Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html A shortcut to create a factory for a given class and then create a specified number of instances, typically involving saving them to a database. ```python def create_batch(klass, size, **kwargs): """Create a factory for the given class, and create a batch of instances.""" return make_factory(klass, **kwargs).create_batch(size) ``` -------------------------------- ### Create a Single Instance Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/base.html Use the `create` method to generate an instance of the associated class and ensure it is saved and persisted to its datastore. This is the typical method for creating objects in a live environment. ```python cls.create(**kwargs) ``` -------------------------------- ### Toggle Factory Boy Trait with Boolean Source: https://factoryboy.readthedocs.io/en/stable/introduction.html Traits can be toggled using a single boolean value. This example shows how to activate the 'shipped' trait. ```python class Params: shipped = factory.Trait( status='shipped', shipped_by=factory.SubFactory(EmployeeFactory), shipped_on=factory.LazyFunction(datetime.date.today), ) ``` -------------------------------- ### build Source: https://factoryboy.readthedocs.io/en/stable/_modules/factory/helpers.html Creates a factory for the given class and builds an instance. ```APIDOC ## build ### Description Create a factory for the given class, and build an instance. ### Parameters #### Arguments - **klass** (type) - The class for which to create a factory. - **kwargs** - Additional keyword arguments to configure the factory. ``` -------------------------------- ### Forcing Sequence Counter Value Per Call Example Source: https://factoryboy.readthedocs.io/en/stable/_sources/recipes.rst.txt Demonstrates how to force the sequence counter for a specific factory instantiation using __sequence. ```python >>> obj1 = AccountFactory(name="John Doe", __sequence=10) >>> obj1.uid # Taken from the __sequence counter 10 >>> obj2 = AccountFactory(name="Jane Doe") >>> obj2.uid # The base sequence counter hasn't changed 1 ``` -------------------------------- ### Instantiate Objects with Different Factories Source: https://factoryboy.readthedocs.io/en/stable/introduction.html Create instances using different factories, demonstrating the effect of their specific default attributes. ```python >>> EnglishUserFactory() >>> FrenchUserFactory() ```