class UserFactory(Factory): class Meta: model = settings.AUTH_USER_MODEL email = factory.Sequence(lambda n: '*****@*****.**' % n) password = factory.PostGeneration( lambda obj, *args, **kwargs: obj.set_password('123123'))
class UserFactory(factory.DjangoModelFactory): FACTORY_FOR = taiga.users.models.User username = factory.Sequence(lambda n: "user{}".format(n)) email = factory.LazyAttribute(lambda obj: '*****@*****.**' % obj.username) password = factory.PostGeneration( lambda obj, *args, **kwargs: obj.set_password(obj.username))
class LearningResourceRunFactory(AbstractCourseFactory): """Factory for LearningResourceRuns""" run_id = factory.Sequence(lambda n: "COURSEN%03d.MIT_run" % n) platform = FuzzyChoice(( PlatformType.mitx.value, PlatformType.ocw.value, PlatformType.micromasters.value, PlatformType.xpro.value, PlatformType.oll.value, PlatformType.bootcamps.value, )) content_object = factory.SubFactory(CourseFactory) object_id = factory.SelfAttribute("content_object.id") content_type = factory.LazyAttribute( lambda o: ContentType.objects.get_for_model(o.content_object)) availability = FuzzyChoice(( AvailabilityType.current.value, AvailabilityType.upcoming.value, AvailabilityType.starting_soon.value, AvailabilityType.archived.value, )) enrollment_start = factory.Faker("date_time", tzinfo=pytz.utc) enrollment_end = factory.LazyAttribute( lambda obj: (obj.enrollment_start + timedelta(days=45)) if obj.enrollment_start else None) start_date = factory.LazyAttribute( lambda obj: obj.enrollment_start + timedelta(days=15)) end_date = factory.LazyAttribute(lambda obj: obj.start_date + timedelta( days=90) if obj.start_date else None) language = factory.Faker("word") year = factory.Faker("year") url = factory.Faker("word") prices = factory.PostGeneration(_post_gen_prices) @factory.post_generation def instructors(self, create, extracted, **kwargs): """Create instructors for course""" if not create: return if extracted is None: extracted = CourseInstructorFactory.create_batch( random.randint(0, 3)) self.instructors.set(extracted) class Meta: model = LearningResourceRun class Params: no_prices = factory.Trait(prices=[]) no_instructors = factory.Trait(instructors=[]) in_past = factory.Trait(enrollment_start=factory.Faker( "date_time_between", end_date="-270d", tzinfo=pytz.utc)) in_future = factory.Trait(enrollment_start=factory.Faker( "date_time_between", start_date="+15d", tzinfo=pytz.utc))
class UserFactory(Factory): class Meta: model = settings.AUTH_USER_MODEL strategy = factory.CREATE_STRATEGY username = factory.Sequence(lambda n: "user{}".format(n)) email = factory.LazyAttribute(lambda obj: '*****@*****.**' % obj.username) password = factory.PostGeneration(lambda obj, *args, **kwargs: obj.set_password(obj.username))
class UserFactory(Factory): class Meta: model = "auth.User" strategy = factory.CREATE_STRATEGY username = factory.Sequence(lambda n: "user{}".format(n)) email = factory.LazyAttribute(lambda obj: '*****@*****.**' % obj.username) password = factory.PostGeneration(lambda obj, *args, **kwargs: obj.set_password('123123'))
class VideoFactory(factory.django.DjangoModelFactory): """Creates a video using a sequence. """ FACTORY_FOR = Video title = factory.Sequence(lambda n: 'Test Video %d' % n) created = datetime.datetime.now() factory.PostGeneration(lambda obj, create, extracted, **kwargs: VideoUrlFactory.create(video=obj))
class UserFactory(Factory): class Meta: model = settings.AUTH_USER_MODEL # modify this to USERNAME_FIELD for custom user model username = factory.Sequence(lambda n: "User{}".format(n)) email = factory.Sequence(lambda n: '*****@*****.**' % n) password = factory.PostGeneration( lambda obj, *args, **kwargs: obj.set_password(obj.phone_number))
class UserFactory(factory.DjangoModelFactory): class Meta: model = settings.AUTH_USER_MODEL strategy = factory.CREATE_STRATEGY # modify this to USERNAME_FIELD for custom user model username = factory.Sequence(lambda n: "user{}".format(n)) email = factory.Sequence(lambda n: '*****@*****.**' % n) password = factory.PostGeneration( lambda obj, *args, **kwargs: obj.set_password(obj.username))
class ProgramFactory(DjangoModelFactory): """Factory for Programs""" title = fuzzy.FuzzyText(prefix="Program ") live = factory.Faker('boolean') description = fuzzy.FuzzyText() price = fuzzy.FuzzyDecimal(low=500, high=2000) num_required_courses = 1 topics = factory.PostGeneration(_post_gen_topics) class Meta: model = Program
class UserFactory(Factory): class Meta: model = settings.AUTH_USER_MODEL strategy = factory.CREATE_STRATEGY username = factory.Sequence(lambda n: 'user%04d' % n) first_name = 'User' last_name = factory.Sequence(lambda n: '%04d' % n) email = factory.LazyAttribute(lambda obj: '*****@*****.**' % obj.username) password = factory.PostGeneration( lambda obj, *args, **kwargs: obj.set_password('test'))
class UserFactory(Factory): class Meta: model = settings.AUTH_USER_MODEL strategy = factory.CREATE_STRATEGY first_name = DEFAULT_USER["first_name"] last_name = DEFAULT_USER["last_name"] email = factory.Sequence(lambda n: f"user{n}@email.com") username = factory.LazyAttribute(lambda obj: obj.email) password = factory.PostGeneration( lambda obj, *args, **kwargs: obj.set_password(obj.username)) profile = factory.RelatedFactory(ProfileFactory, "user")
class TicketFactory(DjangoModelFactory): class Meta: model = 'tickets.Ticket' subject = factory.Faker('word') description = factory.Faker('text') employees = factory.PostGeneration(add_employees) @classmethod def build_dict(cls, **extra_fields): data = factory.build(dict, FACTORY_CLASS=cls, **extra_fields) return data
class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') password = factory.PostGeneration( lambda user, create, extracted: user.set_password( extracted or factory.Faker('password').generate({}))) # Fixed values, can be overridden manually on creation. is_active = True is_staff = False is_superuser = False # Joined in the last month but more recent last_login. date_joined = factory.Faker('date_time_this_month', tzinfo=pytz.utc) last_login = factory.LazyAttribute( lambda o: factory.Faker('date_time_between_dates', datetime_start=o.date_joined, tzinfo=pytz.utc).generate({})) # We pass in 'user' to link the generated Profile to our just-generated User # This will call UserInfoFactory(user=our_new_user), thus skipping the SubFactory. info = factory.RelatedFactory(UserInfoFactory, 'user') profile = factory.RelatedFactory(UserProfileFactory, 'user') @factory.lazy_attribute_sequence def username(self, n): if self.first_name and self.last_name: first_letter = (unicodedata.normalize( 'NFKD', self.first_name).encode('ascii', 'ignore').decode('utf8'))[:1] last_name = (unicodedata.normalize('NFKD', self.last_name).encode( 'ascii', 'ignore').decode('utf8'))[:9] return '{0}{1}{2}'.format(first_letter, last_name, n) else: return factory.Faker('user_name') @factory.lazy_attribute_sequence def email(self, n): if self.first_name and self.last_name: first_letter = (unicodedata.normalize( 'NFKD', self.first_name).encode('ascii', 'ignore').decode('utf8'))[:1] last_name = (unicodedata.normalize('NFKD', self.last_name).encode( 'ascii', 'ignore').decode('utf8'))[:9] return '{0}.{1}{2}@'.format(first_letter, last_name, n, factory.Faker('free_email_domain')) else: return factory.Faker('ascii_safe_email')
class LearningResourceFactory(DjangoModelFactory): """Factory for LearningResource subclasses""" title = factory.Faker("word") short_description = factory.Faker("sentence") topics = factory.PostGeneration(_post_gen_topics) offered_by = factory.RelatedFactoryList( "course_catalog.factories.LearningResourceOfferorFactory", size=1) class Meta: abstract = True class Params: no_topics = factory.Trait(topics=[])
class NewsItemFactory(factory.DjangoModelFactory): class Meta(object): model = NewsItem title = factory.Sequence(lambda n: 'News Title {0}'.format(n)) status = PublishedStatus.published main_image = factory.django.ImageField(color='blue') publication_date = now() - timedelta(days=4) language = 'nl' slug = factory.Sequence(lambda n: 'slug-{0}'.format(n)) author = factory.SubFactory(BlueBottleUserFactory) make_placeholder = factory.PostGeneration( lambda obj, create, extracted, **kwargs: Placeholder.objects. create_for_object(obj, 'blog_contents'))
def build_manytomanyfield(field_cls): field_descriptor = getattr(field_cls.model, field_cls.name) field_through = field_descriptor.through if not field_through._meta.auto_created: return _build_manytomanyfield_with_a_through(field_cls) model_factory = make_django_autofactory(get_related_model(field_cls)) def builder(obj, create, _extracted, **_kwargs): if not create: return manager = getattr(obj, field_cls.name) manager.add(*model_factory.create_batch(2)) return factory.PostGeneration(builder)
class UserFactory(DjangoModelFactory): first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') email = factory.Sequence(lambda n: f'{n}@xyz.com') username = factory.LazyAttribute(lambda user: user.email) password_text = fuzzy.FuzzyText(length=15) password = factory.PostGeneration(lambda user, *args, **kwargs: user.set_password(user.password_text)) class Meta: model = User @classmethod def _create(cls, model_class, *args, **kwargs): password_text = kwargs.pop('password_text') profile_data = { key: kwargs.pop(key) for key in PROFILE_FIELDS if key in kwargs } user = super()._create(model_class, *args, **kwargs) UserSerializer.update_or_create_profile(user, profile_data) user.profile.refresh_from_db() user.password_text = password_text return user
class PhaseFactory(factory.Factory): class Meta: model = Phase class Params: num_actions = factory.Faker('random_int', min=1, max=5) name = factory.Faker('word') actions = ListSubFactory(ActionFactory, count=factory.SelfAttribute('num_actions')) stage = factory.PostGeneration( lambda obj, create, extracted, **kwargs: StageFactory.build(phases=[obj]) ) @classmethod def _create(cls, model_class, *args, **kwargs): actions = kwargs.pop('actions') new_class = type(model_class.__name__, (model_class,), {'actions': actions}) return new_class(*args, **kwargs) @classmethod def _build(cls, model_class, *args, **kwargs): # defer to create because parent uses build return cls._create(model_class, *args, **kwargs)
class SmallVariantFactory(factory.django.DjangoModelFactory): """Factory for creating ``SmallVariant`` objects.""" class Meta: model = SmallVariant exclude = ["case", "variant_set"] class Params: #: The genotypes to create, by default only first is het. the rest is wild-type. genotypes = default_genotypes release = "GRCh37" chromosome = factory.Iterator(list(CHROMOSOME_MAPPING.keys())) chromosome_no = factory.LazyAttribute(lambda o: CHROMOSOME_MAPPING[o.chromosome]) start = factory.Sequence(lambda n: (n + 1) * 100) end = factory.LazyAttribute(lambda o: o.start + len(o.reference) - len(o.alternative)) bin = 0 reference = factory.Iterator("ACGT") alternative = factory.Iterator("CGTA") var_type = "snv" #: Model pseudo-attribute, not stored in database. Instead, ``case_id`` is stored. Also, the case is taken #: from the ``SmallVariantSet`` that is auto-created via a ``SubFactory``. case = factory.PostGeneration( lambda obj, create, extracted, **kwargs: Case.objects.get(id=obj.case_id) ) #: The actual foreign key to the ``Case``. case_id = factory.SelfAttribute("variant_set.case.id") #: Model pseudo-attribute, not stored in database. Instead, ``set_id`` is stored. variant_set = factory.SubFactory(SmallVariantSetFactory) #: The actual reference to the ``SmallVariantSet``. set_id = factory.LazyAttribute(lambda o: o.variant_set.id) @factory.lazy_attribute def genotype(self): """Generate genotype JSON field from already set ``self.case``.""" return { line["patient"]: gt for line, gt in zip(self.variant_set.case.pedigree, self.genotypes()) } @factory.post_generation def fix_bins(obj, *args, **kwargs): obj.bin = binning.assign_bin(obj.start - 1, obj.end) obj.save() num_hom_alt = factory.LazyAttribute(count_gt("0/0")) num_hom_ref = factory.LazyAttribute(count_gt("1/1")) num_het = factory.LazyAttribute(count_gt("0/1", "1/0", "0|1", "1|0")) num_hemi_alt = 0 num_hemi_ref = 0 in_clinvar = False exac_frequency = 0.0001 exac_homozygous = 0 exac_heterozygous = 0 exac_hemizygous = 0 thousand_genomes_frequency = 0.0001 thousand_genomes_homozygous = 0 thousand_genomes_heterozygous = 0 thousand_genomes_hemizygous = 0 gnomad_exomes_frequency = 0.0001 gnomad_exomes_homozygous = 0 gnomad_exomes_heterozygous = 0 gnomad_exomes_hemizygous = 0 gnomad_genomes_frequency = 0.0001 gnomad_genomes_homozygous = 0 gnomad_genomes_heterozygous = 0 gnomad_genomes_hemizygous = 0 refseq_gene_id = factory.Sequence(lambda n: str(n)) refseq_transcript_id = factory.Sequence(lambda n: "NM_%d" % n) refseq_transcript_coding = True refseq_hgvs_c = "c.123C>T" refseq_hgvs_p = "p.I2T" refseq_effect = factory.List(["synonymous_variant"]) refseq_exon_dist = 0 ensembl_gene_id = factory.Sequence(lambda n: "ENSG%d" % n) ensembl_transcript_id = factory.Sequence(lambda n: "ENST%d" % n) ensembl_transcript_coding = True ensembl_hgvs_c = "c.123C>T" ensembl_hgvs_p = "p.I2T" ensembl_effect = factory.List(["synonymous_variant"]) ensembl_exon_dist = 0
class ManyToManyModelFactory(factory.DjangoModelFactory): class Meta: model = models.ManyToManyModel m2m = factory.PostGeneration(create_m2m('m2m'))
class TestObjectFactory(factory.Factory): FACTORY_FOR = TestObject bar = factory.PostGeneration(my_lambda)
class FeatureFactory(DjangoModelFactory): title = factory.PostGeneration(lambda feature, *args, **kwargs: f'Feature {feature.key}') feature_type = fuzzy.FuzzyChoice(Feature.FeatureType.choices, getter=lambda c: c[0]) class Meta: model = Feature