class MonthlyGoalFactory(DjangoModelFactory): class Meta: model = MonthlyGoal custom_user = factory.SubFactory(CustomUserFactory) year = FuzzyInteger(low=0, high=9999) month = FuzzyInteger(low=1, high=12) category = FuzzyInteger(low=1, high=6) score = FuzzyInteger(low=1, high=5) goal = Faker('text', max_nb_chars=255, locale=FAKER_LOCALE) why_need_goal = Faker('text', max_nb_chars=500, locale=FAKER_LOCALE) revised_goal = Faker('text', max_nb_chars=255, locale=FAKER_LOCALE) why_revise = Faker('text', max_nb_chars=500, locale=FAKER_LOCALE) after_memo = Faker('text', max_nb_chars=500, locale=FAKER_LOCALE)
def test_star_range_validation(self): '''Star point attributes are restricted to 1 - 5''' for point in [ 'spirit', 'exercise', 'work', 'play', 'friends', 'adventure' ]: low = {point: FuzzyInteger(-10, 0)} high = {point: FuzzyInteger(6, 10)} star = StarFactory(**low) self.assertRaises(ValidationError, star.clean_fields) star = StarFactory(**high) self.assertRaises(ValidationError, star.clean_fields)
class CreditFactory(ProductFactory): residue = FuzzyInteger(1000, 100000) current_penalty = FuzzyInteger(100, 1000) next_payment_term = factory.sequence(lambda n: fake.date()) duration = factory.sequence(lambda n: fake.pyint()) start_date = factory.sequence(lambda n: fake.date()) status = FuzzyChoice(dict(Credit.STATUS_CHOICES)) fine_percentage = FuzzyFloat(100) method_of_ensuring = FuzzyChoice(dict(CreditTemplate.ENSURING_CHOICES)) money_destination = FuzzyChoice(dict(Credit.MONEY_DESTINATION)) template = factory.SubFactory('finance.factories.CreditTemplateFactory') class Meta: model = Credit
class VideoThumbnailFactory(DjangoModelFactory): """ Factory for a VideoThumbnail """ video = SubFactory(VideoFactory) s3_object_key = LazyAttribute( lambda obj: "{}/{}".format(obj.video.hexkey, FAKE.file_name("image"))) bucket_name = settings.VIDEO_S3_BUCKET max_width = FuzzyInteger(low=1) max_height = FuzzyInteger(low=1) class Meta: model = models.VideoThumbnail
class OrderModelFactory(factory.Factory): # type: ignore class Meta: model = OrderModel id = factory.Sequence(lambda n: n + 1) code = FuzzyInteger(10000, 99999) value = FuzzyDecimal(100.00, 100000.00) retailer_document = str(FuzzyInteger(10000000000, 99999999999)) status = FuzzyChoice(["Em Validação", "Aprovado"]) created_at = FuzzyDateTime(datetime(2012, 1, 1, tzinfo=UTC)) @factory.lazy_attribute # type: ignore def cashback(self) -> Decimal: return cast(Decimal, self.value) * Decimal(0.10)
class MemberFactory(DjangoModelFactory): class Meta: model = Member birth_year = FuzzyInteger(year - 90, year - 12) # Contact information gender = FuzzyInteger(0, 1) phone = Sequence(lambda n: "720%07d" % n) city = "Broomfield" state = "CO" zip_code = "80020" # Still in the ward active = True
class CreditTemplateFactory(factory.DjangoModelFactory): name = factory.sequence(lambda n: fake.sentence(nb_words=1)) description = factory.sequence(lambda n: fake.sentence(nb_words=15)) annual_percentage_rate = factory.fuzzy.FuzzyInteger(1, 100) max_amount = factory.sequence(lambda n: '{}') min_amount = factory.sequence(lambda n: '{}') max_duration = FuzzyInteger(3, 60) fine_percentage = FuzzyInteger(1, 100) issue_online = factory.sequence(lambda n: fake.pybool()) allowed_ensuring = [ FuzzyChoice(dict(CreditTemplate.ENSURING_CHOICES)).fuzz() ] class Meta: model = CreditTemplate
class BookFactory(factory.DjangoModelFactory): title = factory.Faker("catch_phrase") author = factory.SubFactory(AuthorFactory) pages = FuzzyInteger(100, 500, 10) class Meta: model = "foo.Book"
class DocumentFactory(factory.django.DjangoModelFactory): name = factory.Faker("name") size = FuzzyInteger(10) file_type = FuzzyChoice(["doc", "txt", "py", "png", "pdf"]) class Meta: model = "foo.Document"
class TrafficVolumeFactory(TrafficDataFactory): class Meta: model = TrafficVolume ip = factory.SubFactory(IPFactory) type = FuzzyChoice(['Ingress', 'Egress']) packets = FuzzyInteger(0, 5000)
class SafeContractFactory(factory.DjangoModelFactory): class Meta: model = SafeContract address = factory.LazyFunction(lambda: Account.create().address) ethereum_tx = factory.SubFactory(EthereumTxFactory) erc20_block_number = FuzzyInteger(low=0, high=2)
class IndOpiFactory(factory.DjangoModelFactory): FACTORY_FOR = IndOpi cod_ind_opi = factory.Sequence(lambda n: n) cod_ind = factory.Sequence(lambda n: n) lib_nom_pat_ind_opi = factory.Sequence(lambda n: "stefan%d" % n) lib_pr1_ind_opi = factory.Sequence(lambda n: "George%d" % n) cod_opi_int_epo = FuzzyInteger(11111111, 29999999)
class TrafficDataFactory(BaseFactory): class Meta: abstract = True amount = FuzzyInteger(0, 60 * 1024 ** 3) timestamp = factory.Faker('date_time') user = factory.SubFactory(UserFactory)
def test_web_profile_with_invalid_locale(self, mock_web_profile, mock_payment, mock_logger): """ Verify that the payment creation payload does not reference a web profile when an invalid locale is chosen. This should occur when the create_and_set_webprofile waffle is enabled. """ toggle_switch('create_and_set_webprofile', True) mock_payment_instance = mock.Mock() # NOTE: This is necessary to avoid the issue in https://code.djangoproject.com/ticket/25493. mock_payment_instance.id = FuzzyInteger(low=1).fuzz() mock_payment_instance.to_dict.return_value = {} mock_payment_instance.links = [mock.Mock(rel='approval_url', href='dummy')] mock_payment.return_value = mock_payment_instance Paypal.resolve_paypal_locale = mock.Mock(return_value='invalid_locale') mock_web_profile_instance = mock.Mock() mock_web_profile_instance.create = mock.Mock(return_value=False) mock_web_profile_instance.error = 'invalid_config' mock_web_profile.return_value = mock_web_profile_instance self.processor.get_transaction_parameters(self.basket, request=self.request) payment_creation_payload = mock_payment.call_args[0][0] self.assertNotIn('experience_profile_id', payment_creation_payload) msg = 'Web profile creation encountered error [%s]. Will continue without one' % ( mock_web_profile_instance.error ) mock_logger.warning.assert_any_call(msg)
def setUp(self): super(MarketingSiteAPIClientTestMixin, self).setUp() self.username = FuzzyText().fuzz() self.password = FuzzyText().fuzz() self.api_root = FuzzyUrlRoot().fuzz() self.csrf_token = FuzzyText().fuzz() self.user_id = FuzzyInteger(1).fuzz()
class VulnerabilityCodeFactory(VulnerabilityGenericFactory): start_line = FuzzyInteger(1, 5000) source_code = factory.SubFactory(SourceCodeFactory) class Meta: model = VulnerabilityCode sqlalchemy_session = db.session
class PersonFactory(factory.django.DjangoModelFactory): class Meta: model = Person age = FuzzyInteger(21, 99) eye_color = FuzzyChoice([Person.EYE_BLUE, Person.EYE_BROWN]) name = factory.Sequence(lambda n: f"Person{n}") gender = FuzzyChoice([Person.GENDER_MALE, Person.GENDER_FEMALE]) phone = factory.Sequence(lambda n: "0486-992-%03d" % n) email = factory.LazyAttribute(lambda obj: f"{obj.name}@test.com".lower()) address = factory.Faker("address") registered = FuzzyDateTime(datetime.datetime(2020, 1, 1, tzinfo=UTC)) company = factory.SubFactory(CompanyFactory) about = FuzzyText() greeting = FuzzyText() balance = FuzzyDecimal(low=0) @factory.post_generation def favourite_foods(self, create, extracted, **kwargs): if not create: return if extracted: for food in extracted: self.favourite_foods.add(food) @factory.post_generation def friends(self, create, extracted, **kwargs): if not create: return if extracted: for friend in extracted: self.friends.add(friend)
class CatalogObjectFactory(factory.django.DjangoModelFactory): class Meta: model = CatalogObject astro_object = factory.SubFactory(AstroObjectFactory) catalog = FuzzyChoice(choices=settings.CATALOGS.keys()) designation = FuzzyInteger(0, 10000)
class PostCodeFactory(BaseFactory): name = 'Test PostCode Area Name' code = FuzzyInteger(10000, 97000) municipality = factory.SubFactory(MunicipalityFactory) class Meta: model = models.PostCode
class DenunciableFactory(factory.DjangoModelFactory): class Meta: model = models.Denunciable denunciable_id = FuzzyInteger(0, 1000) denunciable_type = FuzzyChoice(['comment', 'image', 'document'])
def handle(self, *args, **options): upper_bound = options['upper_bound'] substance_type = options['substance_type'] substance_unit = options['substance_unit'] username = options['username'] try: user = User.objects.get(name=username.lower()) except ObjectDoesNotExist: user = User.objects.create(name=username.lower()) try: category = Category.objects.get(name=substance_type.lower()) except ObjectDoesNotExist: category = Category.objects.create(name=substance_type.lower()) try: unit = Unit.objects.get(name=substance_unit.lower()) except ObjectDoesNotExist: unit = Unit.objects.create(name=substance_unit.lower(), category=category) end_date = date.today() start_date = end_date - timedelta(days=7) for i in self.get_date_list(start_date, end_date): for _ in range(3): SubstanceFactory( user=user, unit=unit, category=category, record_date=i, record_time=FuzzyNaiveDateTime(datetime.datetime.now() - timedelta(hours=24)), value=FuzzyInteger(0, int(upper_bound)))
class CommentFactory(WorkspaceObjectFactory): """ A command without command objects. """ text = FuzzyText() object_id = FuzzyInteger(1, 10000) object_type = FuzzyChoice(['host', 'service', 'comment', 'vulnerability']) @classmethod def build_dict(cls, **kwargs): # The host, service or comment must be created ret = super().build_dict(**kwargs) workspace = kwargs['workspace'] if ret['object_type'] == 'host': HostFactory.create(workspace=workspace, id=ret['object_id']) elif ret['object_type'] == 'service': ServiceFactory.create(workspace=workspace, id=ret['object_id']) elif ret['object_type'] == 'vulnerability': VulnerabilityFactory.create(workspace=workspace, id=ret['object_id']) elif ret['object_type'] == 'comment': cls.create(workspace=workspace, id=ret['object_id']) return ret class Meta: model = Comment sqlalchemy_session = db.session
class PopSnapFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = models.PopulationSnapshot sqlalchemy_session = db.session id = factory.Sequence(int) popcount = FuzzyInteger(0, 150) time = FuzzyNaiveDateTime(datetime.datetime.now())
class FavoriteFactory(factory.DjangoModelFactory): title = factory.Faker("word") ranking = FuzzyInteger(low=1, high=10) category = factory.SubFactory(CategoryFactory) class Meta: model = Favorite
def test_web_profile_with_valid_locale(self, mock_web_profile, mock_payment, mock_logger): """ Verify that the payment creation payload references a web profile when a valid locale is chosen This should occur when the create_and_set_webprofile waffle is enabled. """ toggle_switch('create_and_set_webprofile', True) mock_payment_instance = mock.Mock() # NOTE: This is necessary to avoid the issue in https://code.djangoproject.com/ticket/25493. mock_payment_instance.id = FuzzyInteger(low=1).fuzz() mock_payment_instance.to_dict.return_value = {} mock_payment_instance.links = [mock.Mock(rel='approval_url', href='dummy')] mock_payment.return_value = mock_payment_instance Paypal.resolve_paypal_locale = mock.Mock(return_value='valid_locale') mock_web_profile_instance = mock.Mock() mock_web_profile_instance.id = 'test-profile-id' mock_web_profile_instance.presentation.locale_code = 'valid_locale' mock_web_profile.create = mock.Mock(return_value=True) mock_web_profile.return_value = mock_web_profile_instance self.processor.get_transaction_parameters(self.basket, request=self.request) payment_creation_payload = mock_payment.call_args[0][0] self.assertEqual(payment_creation_payload['experience_profile_id'], 'test-profile-id') msg = 'Web Profile[%s] for locale %s created successfully' % ( mock_web_profile_instance.id, mock_web_profile_instance.presentation.locale_code ) mock_logger.info.assert_any_call(msg)
def test_dummy_web_profiles(self, enabled_profile_name, mock_payment): """ Verify that the payment creation payload references a web profile when one is enabled with the expected name. This should occur when the create_and_set_webprofile waffle is disabled. """ toggle_switch('create_and_set_webprofile', False) mock_payment_instance = mock.Mock() # NOTE: This is necessary to avoid the issue in https://code.djangoproject.com/ticket/25493. mock_payment_instance.id = FuzzyInteger(low=1).fuzz() mock_payment_instance.to_dict.return_value = {} mock_payment_instance.links = [ mock.Mock(rel='approval_url', href='dummy') ] mock_payment.return_value = mock_payment_instance if enabled_profile_name is not None: PaypalWebProfile.objects.create(name=enabled_profile_name, id='test-profile-id') self.processor.get_transaction_parameters(self.basket, request=self.request) payment_creation_payload = mock_payment.call_args[0][0] if enabled_profile_name == Paypal.DEFAULT_PROFILE_NAME: self.assertEqual(payment_creation_payload['experience_profile_id'], 'test-profile-id') else: self.assertNotIn('experience_profile_id', payment_creation_payload)
def setUp(self): super().setUp() self.username = FuzzyText().fuzz() self.password = FuzzyText().fuzz() self.api_root = FuzzyUrlRoot().fuzz() self.csrf_token = FuzzyText().fuzz() self.user_id = FuzzyInteger(1).fuzz()
def test_web_profile_with_exception(self, mock_web_profile_init, mock_payment, mock_logger): """ Verify that the payment creation payload does not reference a web profile if its creation results in exception. This should occur when the create_and_set_webprofile waffle is enabled. """ toggle_switch('create_and_set_webprofile', True) mock_payment_instance = mock.Mock() # NOTE: This is necessary to avoid the issue in https://code.djangoproject.com/ticket/25493. mock_payment_instance.id = FuzzyInteger(low=1).fuzz() mock_payment_instance.to_dict.return_value = {} mock_payment_instance.links = [ mock.Mock(rel='approval_url', href='dummy') ] mock_payment.return_value = mock_payment_instance Paypal.resolve_paypal_locale = mock.Mock(return_value="valid_locale") mock_web_profile_init.side_effect = Exception( 'MissingConfig Exception') self.processor.get_transaction_parameters(self.basket, request=self.request) payment_creation_payload = mock_payment.call_args[0][0] self.assertNotIn('experience_profile_id', payment_creation_payload) self.assertRaises(Exception('MissingConfig Exception')) msg = 'Creating PayPal WebProfile resulted in exception. Will continue without one.' mock_logger.warning.assert_any_call(msg)
class SuperUserFactory(factory.DjangoModelFactory): id = FuzzyInteger(1000, 9999) is_superuser = True lms_user_id = 56765 class Meta(object): model = get_model('core', 'User')
class PersonFactory(factory.django.DjangoModelFactory): class Meta: model = Person guid = FuzzyText(length=10, chars=string.ascii_lowercase + string.digits) age = FuzzyInteger(21, 99) eye_color = 'brown' name = factory.Sequence(lambda n: "User{}".format(n)) gender = 'Male' phone = factory.Sequence(lambda n: '0486-992-%03d' % n) email = factory.LazyAttribute( lambda obj: u'{}@test.com'.format(obj.name).lower()) address = factory.Faker('address') registered = FuzzyDateTime(datetime.datetime(2020, 1, 1, tzinfo=UTC)) company = factory.SubFactory(CompanyFactory) @factory.post_generation def favourite_food(self, create, extracted, **kwargs): if not create: # simple build, do nothing return if extracted: for food in extracted: self.favourite_food.add(food) @factory.post_generation def friends(self, create, extracted, **kwargs): if not create: # simple build, do nothing return if extracted: for friend in extracted: self.friends.add(friend)