コード例 #1
0
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",
        )
コード例 #2
0
class ExampleEpochModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = ExampleEpochModel

    name = FactoryFaker("name")
    date = FactoryFaker("date")
    tz_aware_date = FactoryFaker("date_time")
コード例 #3
0
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")
コード例 #4
0
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
    )
コード例 #5
0
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)
コード例 #6
0
class ExampleConditionallyDeletedThingFactory(factory.django.DjangoModelFactory
                                              ):
    class Meta:
        model = ExampleConditionallyDeletedThing

    name = factory.LazyAttributeSequence(lambda o, n: f"thing-{n}")
    should_delete = FactoryFaker("boolean")
コード例 #7
0
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)
コード例 #8
0
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)
コード例 #9
0
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)
コード例 #10
0
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)
コード例 #11
0
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}"
コード例 #12
0
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)
コード例 #13
0
class ExampleSingletonModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = ExampleSingletonModel

    name = FactoryFaker("name")
コード例 #14
0
class ExampleHashableModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = ExampleHashableModel

    name = FactoryFaker("name")