class CustomerFactory(factory.django.DjangoModelFactory): class Meta: model = Customer customer_type = CustomerType.MULTIPLE name = FactoryFaker("name") official_name = FactoryFaker("name") company_type = Customer.CompanyTypes.NON_PROFIT registered_id = factory.LazyAttributeSequence( lambda o, n: f"{slugify(o.name)}-{n}") description = FactoryFaker("text") url = FactoryFaker("url") @factory.lazy_attribute def vat_number(self): return fake.vat_id() @factory.lazy_attribute def logo(self): return SimpleUploadedFile( name=f"{self.name}_logo.png", content=b"I am a fake image", content_type="image/png", )
class ExampleEpochModelFactory(factory.django.DjangoModelFactory): class Meta: model = ExampleEpochModel name = FactoryFaker("name") date = FactoryFaker("date") tz_aware_date = FactoryFaker("date_time")
class ExampleBulkModelFactory(factory.django.DjangoModelFactory): class Meta: model = ExampleBulkModel something_unique = FactoryFaker( "validated_word", validators=[ lambda x: not ExampleBulkModel.objects.filter(something_unique=x). exists() ] + ExampleBulkModel._meta.get_field("something_unique").validators, ) something_non_unique = FactoryFaker("word")
class ExampleProfileFactory(factory.django.DjangoModelFactory): class Meta: model = ExampleProfile age = FactoryFaker("pyint", min_value=1, max_value=100) height = FactoryFaker("pyfloat", min_value=150.0, max_value=215.0) weight = FactoryFaker("pyfloat", min_value=20.0, max_value=150.0) # "example_profile=None" means that if I create an ExampleProfile explicitly, another profile won't be created # (it disables the RelatedFactory below) user = factory.SubFactory( "example.tests.factories.UserFactory", example_profile=None )
class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ["email"] email = FactoryFaker("email") name = FactoryFaker("name") description = optional_declaration(FactoryFaker("sentence", nb_words=10), chance=50) registration_stage = None accepted_terms = True is_approved = False @factory.lazy_attribute def username(self): return self.email.split("@")[0] @factory.lazy_attribute def avatar(self): return SimpleUploadedFile( name=f"{self.username}_avatar.png", content=b"I am a fake image", content_type="image/png", ) @factory.post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = generate_password() self.raw_password = ( password # the instance has a "raw_password" variable to use in tests ) self.set_password(password) @factory.post_generation def emailaddress_set(self, create: bool, extracted: Sequence[Any], **kwargs): if not create: return if extracted: # I am very unlikely to be here, creating loads of emailaddresses for emailaddress in extracted: self.emailaddress_set.add(emailaddress) else: emailaddress = EmailAddressFactory(user=self, email=self.email, primary=True, verified=False)
class ExampleConditionallyDeletedThingFactory(factory.django.DjangoModelFactory ): class Meta: model = ExampleConditionallyDeletedThing name = factory.LazyAttributeSequence(lambda o, n: f"thing-{n}") should_delete = FactoryFaker("boolean")
class UserRoleFactory(factory.django.DjangoModelFactory): class Meta: model = UserRole description = optional_declaration(FactoryFaker("sentence", nb_words=10), chance=50) @factory.lazy_attribute_sequence def name(self, n): word = fake.word() return f"{word.title()}{n}Role" @factory.post_generation def permissions(self, create: bool, extracted: Sequence[Any], **kwargs): N_PERMISSIONS = 2 if not create: return if extracted: for permission in extracted: self.permissions.add(permission) else: for _ in range(N_PERMISSIONS): permission = UserPermissionFactory() self.permissions.add(permission)
class DatabaseLogRecordFactory(factory.django.DjangoModelFactory): class Meta: model = DatabaseLogRecord logger_name = "db" level = FactoryFaker( "random_element", elements=[x[0] for x in DatabaseLogRecord.LevelChoices]) message = FactoryFaker("sentence", nb_words=10) @factory.post_generation def tags(self, create, extracted, **kwargs): if not create: return if extracted: for tag in tags: self.tags.add(tag)
class MessageFactory(factory.django.DjangoModelFactory): class Meta: model = Message title = FactoryFaker("sentence", nb_words=10) sender = FactoryFaker("email") content = FactoryFaker("text") # user = factory.SubFactory(UserFactory, messages=None) @factory.post_generation def attachments(obj, create, extracted, **kwargs): if not create: return if extracted: # MessageFactory(attachments=10) will generate a Message w/ 10 attachments for n in range(extracted): MessageAttachmentFactory(message=obj)
class UserFactory(factory.django.DjangoModelFactory): class Meta: model = get_user_model() django_get_or_create = ["username"] username = FactoryFaker("user_name") email = FactoryFaker("email") @factory.post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password_kwargs = { "length": 42, "special_chars": True, "digits": True, "upper_case": True, "lower_case": True, } password = fake.password(**password_kwargs) self.set_password(password)
class UserPermissionFactory(factory.django.DjangoModelFactory): class Meta: model = UserPermission description = optional_declaration(FactoryFaker("sentence", nb_words=10), chance=50) @factory.lazy_attribute_sequence def name(self, n): words = fake.words(nb=2) return f"can_{'_'.join(words)}_{n}"
class EmailAddressFactory(factory.django.DjangoModelFactory): """ I don't really use this on its own. Instead I create an (unverified) email address when a user is created above. This is done by default when I create a user via the registration views. But if I am bypassing that, I still need an EmailAddress instance to exist. """ class Meta: model = EmailAddress verified = False primary = True email = FactoryFaker("email") user = factory.SubFactory(UserFactory, emailaddress_set=None)
class ExampleSingletonModelFactory(factory.django.DjangoModelFactory): class Meta: model = ExampleSingletonModel name = FactoryFaker("name")
class ExampleHashableModelFactory(factory.django.DjangoModelFactory): class Meta: model = ExampleHashableModel name = FactoryFaker("name")