class ContactMessageFactory(DjangoModelFactory): class Meta: model = ContactMessage subject = ContactMessage.OTHER name = 'Jane Doe' email = LazyAttribute( lambda obj: '*****@*****.**' % obj.name.replace(' ', '')) message = Sequence(lambda n: 'Test message %d' % n) ip_address = '127.0.0.1'
class PostFactory(DjangoModelFactory): class Meta: model = Post author = SubFactory(UserFactory) title = LazyFunction(lambda: fake.text(randint(5, 20))) content = LazyFunction(lambda: fake.text(randint(20, 500))) created = LazyFunction(lambda: now() - delta(days=365)) updated = LazyAttribute(lambda o: o.created + delta(days=randint(0, 365)))
class UserFactory(BaseModelFactory): # pylint: disable=too-few-public-methods """test user model factory""" class Meta: # pylint: disable=too-few-public-methods """test user model factory""" model = User username = '******' password = LazyAttribute(lambda x: PWS.hash(PWS.generate())) active = True roles = ['user']
class MozfestPrimaryPageFactory(PageFactory): class Meta: model = MozfestPrimaryPage exclude = ('header_text') header = LazyAttribute(lambda o: o.header_text.rstrip('.')) banner = SubFactory(ImageFactory) intro = Faker('paragraph', nb_sentences=3, variable_nb_sentences=False) body = Faker('streamfield', fields=streamfield_fields) header_text = Faker('sentence', nb_words=6, variable_nb_words=True)
class GenericEventFactory(DjangoModelFactory): class Meta: model = conf.GenericEvent e_title = Sequence(lambda n: 'Test Generic Event %d' % n) e_description = LazyAttribute(lambda a: "Description for %s" % a.e_title) duration = Duration(hours=1) type = 'Special' volunteer_type = SubFactory(AvailableInterestFactory) e_conference = SubFactory(ConferenceFactory)
class ProductPageFactory(PageFactory): class Meta: model = ProductPage title = Faker('sentence') privacy_ding = Faker('boolean') adult_content = Faker('boolean') uses_wifi = Faker('boolean') uses_bluetooth = Faker('boolean') company = Faker('company') blurb = Faker('sentence') product_url = Faker('url') price = LazyAttribute(lambda _: randint(49, 1500)) worst_case = Faker('sentence') first_published_at = Faker('past_datetime', start_date='-2d', tzinfo=timezone.utc) last_published_at = Faker('past_datetime', start_date='-1d', tzinfo=timezone.utc) @post_generation def assign_random_categories(self, create, extracted, **kwargs): # late import to prevent circular dependency from networkapi.wagtailpages.models import ProductPageCategory ceiling = 1.0 while True: odds = random() if odds < ceiling: category = get_lowest_content_page_category() ProductPageCategory.objects.get_or_create(product=self, category=category) ceiling = ceiling / 5 else: return @post_generation def set_random_review_date(self, create, extracted, **kwargs): if "Percy" not in self.title: start_date = date(2020, 10, 1) end_date = date(2021, 1, 30) time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_number_of_days = randrange(days_between_dates) self.review_date = start_date + timedelta( days=random_number_of_days) @post_generation def set_random_creepiness(self, create, extracted, **kwargs): self.get_or_create_votes() single_vote = [0, 0, 0, 0, 1] shuffle(single_vote) self.votes.set_votes(single_vote) self.creepiness_value = randint(0, 100)
class RegionFactory(Factory): """Create a new region for OnDemand testing. This is a factory which can be configured by passing in optional parameters for region customization via the nested class method. Multiple rides may be created using the factory by calling a batch method. Optional parameters must match fields defined in the Region data class. :example usage: API: RegionFactory.create(name='Rochester Area') Non-API: RegionFactory.build(name='Triangle Area') """ class Meta: model = Region _api: RegionsAPI = RegionsAPI() name: str = LazyAttribute( lambda _: f'{fake.company()}-{process_time()}-Region') geometry: dict = { 'type': 'MultiPolygon', 'coordinates': [ [ [ [-78.85182348156738, 35.87850360073744], [-78.85439840222168, 35.87259202888435], [-78.842210444458, 35.87113145494405], [-78.84143796826172, 35.87815587342781], ], ], ], } @classmethod def _build(cls, model_class: Callable, **kwargs: Any) -> dict: """Override the default _build method to build a new Region. :param model_class: The factory model used for generation. :param kwargs: Additional arguments being passed for generation. """ return model_class(**kwargs).__dict__ @classmethod def _create(cls, model_class: Callable, **kwargs: Any) -> dict: """Override the default _create method to post against the Regions API. :param app: The application under test. :param model_class: The factory model used for generation. :param kwargs: Additional arguments being passed for generation. """ _region_dict: dict = model_class(**kwargs).__dict__ return cls._api.create_region(region_data=_region_dict)
class BaseContentMixinFactory(FeincmsBaseMixinFactory, TimeStampedMixinFactory, PublishedContentMixinFactory): """BaseContentMixinFactory.""" title = Faker('text', max_nb_chars=100) slug = LazyAttribute(lambda obj: slugify(obj.title)[:100]) class Meta(object): """Meta class.""" abstract = True
def FakerAttribute(provider, **kwargs): """Attribute that lazily generates a value using the Faker library. Example: :: class UserFactory(ModularOdmFactory): name = FakerAttribute('name') """ fake_gen = getattr(fake, provider) if not fake_gen: raise ValueError('{0!r} is not a valid faker provider.'.format(provider)) return LazyAttribute(lambda x: fake_gen(**kwargs))
class ProfileFactory(DjangoModelFactory): class Meta: model = Profile first_name = Faker('first_name') last_name = Faker('last_name') birthday = fuzzy.FuzzyDate(date(1940, 1, 1), date.today() - years_ago(16)) email = Faker('email') jabber = Faker('email') skype = LazyAttribute(lambda o: '%s.%s' % (o.first_name, o.last_name)) biography = fuzzy.FuzzyText(length=50) contacts = fuzzy.FuzzyText(length=50)
class TaskFactory(DjangoModelFactory): class Meta: model = Task name = Faker('company') campaign = SubFactory(CampaignFactory) kind = LazyAttribute(lambda o: o.campaign.kind) link = Faker('url') # TODO: reward status = Iterator(ActiveInactiveStatus, getter=lambda c: c) max_interactions = Faker('pyint')
class PositionFactory(DjangoModelFactory): class Meta: model = Position django_get_or_create = ( 'owner', 'code', ) owner = SubFactory(AccountFactory) code = LazyAttribute(lambda obj: generate_unique_code( obj, 'code', 'name', min_len=2, max_len=4))
class PaperApplicationFactory(DjangoModelFactory): cfp = SubFactory(CallForPaperFactory) applicant = SubFactory(ApplicantFactory) title = Faker('sentence') about = Faker('sentence') abstract = Faker('sentence') skill_level = LazyAttribute( lambda a: AudienceSkillLevel.objects.order_by('?').first()) class Meta: model = PaperApplication
class EmailContentShareLinkFactory(factory.django.DjangoModelFactory): class Meta: model = EmailContent title = 'Share Link' # create lazy slug slug = LazyAttribute( lambda media_content: slugify(media_content.title).lower()) subject = 'Share Link' text = '{link}' html = '{link}'
class TaggedItemsFactory(DjangoModelFactory): content_type = LazyAttribute( lambda o: ContentType.objects.get_for_model(o.content_object)) content_object = SubFactory(ResourceFactory) object_id = SelfAttribute('content_object.id') tag = SubFactory(CustomTagFactory) class Meta: model = TaggedItems django_get_or_create = ["content_type", "object_id", "tag"]
class SessionFactory(DjangoModelFactory): class Meta: model = Session space = SubFactory(SpaceFactory) name = Faker('name') slug = LazyAttribute(lambda obj: slugify(obj.name)) start = Faker('date_time', tzinfo=settings.TZINFO) end = Faker('date_time', tzinfo=settings.TZINFO) template = SubFactory(TicketTemplateFactory)
class PostFactory(DjangoModelFactory): event = SubFactory(EventFactory) title = Faker('sentence') slug = LazyAttribute(lambda x: slugify(x.title)[0:50]) author = SubFactory(UserFactory) is_sponsored = Faker('boolean') lead = Faker('text') body = Faker('text') class Meta: model = Post
class AdminUserFactory(DjangoModelFactory): class Meta: model = User class Params: raw_password = LazyFunction(fake.password) username = LazyFunction(fake.user_name) password = LazyAttribute(lambda a: make_password(a.raw_password)) is_staff = True is_active = True
class UserAccountFactory(DjangoModelFactory): person = SubFactory(PersonFactory) username = Faker('user_name') clear_password = Faker('password') password = LazyAttribute(lambda o: make_password(o.clear_password)) class Meta: model = UserAccount exclude = [ 'clear_password', ]
class DepositSenderWalletFactory(WalletFactory): kind = LazyAttribute(lambda o: WalletKind.EXTERNAL) @post_generation def balance(self, create: bool, extracted: Optional[ProjectMoney], **kwargs): if extracted is not None: self.balance = extracted else: self.balance = ProjectMoney( amount=settings.MINIMUM_TRANSFER_BALANCE + Faker().pyint())
class BaseBookFactory(DjangoModelFactory): """Base book factory.""" title = Faker('text', max_nb_chars=100) summary = Faker('text') publisher = SubFactory('factories.books_publisher.LimitedPublisherFactory') publication_date = Faker('date') price = Faker('pydecimal', left_digits=2, right_digits=2, positive=True) isbn = Faker('isbn13') state = FuzzyChoice(dict(BOOK_PUBLISHING_STATUS_CHOICES).keys()) pages = LazyAttribute( lambda __x: random.randint(10, 200) ) class Meta(object): """Meta class.""" model = Book abstract = True @post_generation def tags(obj, created, extracted, **kwargs): """Create Tag objects for the created Book instance.""" if created: # Create from 1 to 7 ``Tag`` objects. amount = random.randint(1, 7) tags = TagGenreFactory.create_batch(amount, **kwargs) obj.tags.add(*tags) @post_generation def authors(obj, created, extracted, **kwargs): """Create `Author` objects for the created `Book` instance.""" if created: # Create random amount of `Author` objects. amount = random.randint(3, 7) authors = LimitedAuthorFactory.create_batch(amount, **kwargs) obj.authors.add(*authors) @post_generation def orders(obj, created, extracted, **kwargs): """Create `Order` objects for the created `Book` instance.""" if created: # Create 3 `Order` objects. amount = random.randint(2, 7) orders = OrderFactory.create_batch(amount, **kwargs) order_line_kwargs = dict(kwargs) order_line_kwargs['book'] = obj for order in orders: # Create 1 `OrderLine` object. amount = random.randint(1, 5) order_lines = OrderLineFactory.create_batch( amount, **order_line_kwargs ) order.lines.add(*order_lines)
class ComputerFactory(WuFactory): class Meta: model = Computer nutzer = SubFactory(NutzerFactory) nutzer_id = LazyAttribute(lambda self: self.nutzer.nutzer_id) c_etheraddr = Faker('mac_address') c_ip = Faker('ipv4') c_hname = FuzzyText() c_alias = FuzzyText()
class ParkingSpotFactory(DjangoModelFactory): class Meta: model = ParkingSpot django_get_or_create = ( 'label', 'point' ) label = LazyAttribute(lambda x: faker.address()) point = SamplePoint().fuzz()
class LimitedAuthorFactory(BaseAuthorFactory): """Author factory, but limited to 20 authors.""" id = LazyAttribute( lambda __x: random.randint(1, 20) ) class Meta(object): """Meta class.""" django_get_or_create = ('id',)
class IndividualPlanFactory(Factory): class Meta: model = IndividualPlan id = LazyAttribute(lambda _: uuid1()) name = Faker('name', locale='pl_PL') status = FuzzyChoice(Status) fee_amount = FuzzyDecimal(low=10) fee_currency = FuzzyChoice(['PLN', 'USD', 'EUR', 'GBP']) max_no_of_pauses = plan.cmd.MAX_NUMBER_OF_PAUSES renewal = FuzzyChoice(Renewal)
class OrganizationFactory(DjangoModelFactory): name = factory.Sequence(lambda n: f"{faker.word()} #{n}") picture = LazyAttribute( lambda _: ContentFile( ImageField()._make_data({"width": 1024, "height": 768}), "example.jpg", ) ) class Meta: model = Organization
class ProductFactory(DjangoModelFactory): class Meta: model = Product exclude = ('product_words') product_words = Faker('words', nb=2) name = LazyAttribute(lambda o: ' '.join(o.product_words)) @post_generation def product_category(self, create, extracted, **kwargs): """ After model generation, Relate this product to one or more product categories. Do this in a way that will assign some products 2 or more categories. """ ceiling = 1.0 while True: odds = random.random() if odds < ceiling: category = get_random_category() self.product_category.add(category) ceiling = ceiling / 5 else: return company = Faker('company') blurb = Faker('sentence') url = Faker('url') price = random.randint(49, 1500) camera_app = Faker('boolean') meets_minimum_security_standards = Faker('boolean') camera_device = Faker('boolean') microphone_app = Faker('boolean') microphone_device = Faker('boolean') location_app = Faker('boolean') location_device = Faker('boolean') uses_encryption = Faker('boolean') privacy_policy_reading_level_url = Faker('url') privacy_policy_reading_level = str(random.randint(7, 19)) share_data = Faker('boolean') must_change_default_password = Faker('boolean') security_updates = Faker('boolean') need_account = Faker('boolean') delete_data = Faker('boolean') child_rules = Faker('boolean') manage_security = Faker('boolean') phone_number = Faker('phone_number') live_chat = Faker('url') email = Faker('email') worst_case = Faker('sentence') @post_generation def set_image(self, create, extracted, **kwargs): self.image.name = Faker('generic_image').generate({})
class UserFactory(DjangoModelFactory): class Meta: model = get_user_model() strategy = CREATE_STRATEGY is_active = True is_staff = False display_name = LazyAttribute(lambda _: faker.name()) email = Sequence(lambda n: str(n) + faker.email()) description = LazyAttribute(lambda _: faker.text()) # Use display_name as password, as it is readable password = PostGeneration( lambda obj, *args, **kwargs: obj.set_password(obj.display_name)) @classmethod def _create(cls, model_class, *args, **kwargs): manager = cls._get_manager(model_class) user = manager.create_user(*args, **kwargs) return user
class ClientFactory(DjangoModelFactory): name = Faker("company") client_id = LazyFunction(lambda: hex_string(64)) client_secret = LazyFunction(lambda: hex_string(64)) scopes = ["openid", "profile", "email", "address"] scope = LazyAttribute(lambda o: " ".join(o.scopes)) class Meta: model = Client exclude = ["scopes"]
class AddressFactory(Factory): """Create a new address for OnDemand testing. This is a factory which can be configured by passing in optional parameters for address customization via the nested class method. Multiple addresses may be created using the factory by calling a batch method. Optional parameters must match fields defined in the Address data class. :example usage: API: AddressFactory.create(name='Lake Park Plaza') API Web Address: AddressFactory.create(name='Lake Park Plaza', rider_address=True) Non-API: AddressFactory.build(name='Lake Park Plaza') """ class Meta: model = Address class Params: """Optional params which change factory output when True. :param rider_address: Generate an address for the OnDemand Web application. :example usage: AddressFactory.create(rider_address=True) """ rider_address = Trait(url=API.build_api_url('/me/rider/addresses')) _api: AddressesAPI = AddressesAPI() url: str = API.build_api_url(f'/ondemand/{AGENCY}/addresses') name: str = LazyAttribute( lambda _: f'{fake.sentence(nb_words=3)}-{process_time()}') @classmethod def _build(cls, model_class: Callable, **kwargs: Any) -> dict: """Override the default _build method to build a new Address. :param model_class: The factory model used for generation. :param kwargs: Additional arguments being passed for generation. """ return model_class(**kwargs).__dict__ @classmethod def _create(cls, model_class: Callable, **kwargs: Any) -> dict: """Override the default _create method to post against the Addresses API. :param app: The application under test. :param model_class: The factory model used for generation. :param kwargs: Additional arguments being passed for generation. """ _address_dict: dict = model_class(**kwargs).__dict__ return cls._api.create_address(address_data=_address_dict, url=_address_dict['url'])