class UserWithTimetableFactory(DjangoModelFactory): """ Factory specifying many-to-many through relationship. The 'admin' field in Timetable model is a many-to-many relationship to User model through Admin model. """ admins = factory.RelatedFactory(TimetableManagementFactory, 'user')
class PostFactory(factory.django.DjangoModelFactory): class Meta: model = Post django_get_or_create = ("ynr_id", ) ynr_id = "WMC:E14000647" label = "copeland" elections = factory.RelatedFactory(ElectionFactory) organization_type = "local-authority"
class SessionTypeFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = SessionType sqlalchemy_session = db.session event = factory.RelatedFactory(EventFactoryBasic) name = common.string_ length = '00:30' event_id = 1
class PersonPostFactory(factory.django.DjangoModelFactory): class Meta: model = PersonPost person = factory.SubFactory(PersonFactory) post = factory.SubFactory(PostFactory) party = None elections = factory.RelatedFactory(ElectionFactory) list_position = None
class NotificationFactory(BaseFactory): class Meta: model = Notification user = factory.RelatedFactory(UserFactory) title = common.string_ message = common.string_ is_read = False user_id = 2
class PageFactory(factory.django.DjangoModelFactory): """Create random CMS pages.""" changed_by = factory.LazyAttribute(lambda o: slugify(o.user.username)) created_by = factory.LazyAttribute(lambda o: slugify(o.user.username)) title = factory.RelatedFactory(TitleFactory, "page") # Utility fields in_navigation = True login_required = False parent = None user = factory.SubFactory(UserFactory) class Meta: model = cms_models.Page exclude = ["parent", "user"] @factory.lazy_attribute def node(self): """Create a node for the page (under its parent if applicable).""" site = get_current_site() new_node = cms_models.TreeNode(site=site) if self.parent: return self.parent.node.add_child(instance=new_node) return cms_models.TreeNode.add_root(instance=new_node) @classmethod def _after_postgeneration(cls, instance, create, results=None): """ This hook method is called last when generating an instance from a factory. The super method saves the instance one last time after all the "post_generation" hooks have played. This is the moment to finally publish the pages. If we published the pages before this final "save", they would be set back to a pending state and would not be in a clean published state. """ super()._after_postgeneration(instance, create, results=results) instance.rescan_placeholders() if results.get("should_publish", False): for language in instance.get_languages(): instance.publish(language) instance.get_public_object().rescan_placeholders() instance.refresh_from_db() @factory.post_generation # pylint: disable=no-self-use,unused-argument def should_publish(self, create, extracted, **kwargs): """ Mark the pages for publishing. The actual publishing is done by the "_after_post_generation" hook method above. """ if create and extracted: return True return False
class IPv4SubnetFactory(SubnetFactory): ipversion = 4 cidr = factory.Sequence(lambda n: '192.168.{0}.0/24'.format(n)) gateway = factory.LazyAttribute(lambda a: a.cidr[:-4] + '1') pool = factory.RelatedFactory(IPPoolTableFactory, 'subnet', base=cidr, offset=2, size=253)
class AuthorBioFactory(factory.django.DjangoModelFactory): class Meta: model = AuthorBio author = factory.SubFactory(AuthorFactory) body = factory.LazyAttribute(lambda x: faker.text()) metadata = factory.RelatedFactory( "example.factories.AuthorBioMetadataFactory", "bio")
class UserFactory(DjangoModelFactory): class Meta: model = models.User username = factory.Sequence(lambda n: 'user {0}'.format(n)) email = '*****@*****.**' password = factory.PostGenerationMethodCall('set_password', 'password') address = factory.RelatedFactory(AddressFactory) is_public_member = False
class SubscriptionPlanFactory(factory.django.DjangoModelFactory): """Factory to create SubscriptionPlan and PlanCost models.""" plan_name = factory.Sequence(lambda n: 'Plan {}'.format(n)) plan_description = factory.Sequence(lambda n: 'Description {}'.format(n)) grace_period = factory.sequence(lambda n: int(n)) cost = factory.RelatedFactory(PlanCostFactory, 'plan') class Meta: model = models.SubscriptionPlan
class UserFactory(DjangoModelFactory): first_name = 'Vardenis' last_name = 'Pavardenis' email = factory.LazyAttribute(lambda x: '*****@*****.**' % x.username) is_active = True emailaddress = factory.RelatedFactory(EmailAddressFactory, 'user') class Meta: model = settings.AUTH_USER_MODEL django_get_or_create = ('username',)
class PartHandlerFactoryWithTwoParts(factory.DjangoModelFactory): class Meta: model = PartHandler django_get_or_create = ("_project", ) # The project factory automatically creates a parthandler when # instanciating, so none is passed to avoid creating two instances of the # parthandler. If 'none' was not passed two additional parts would created # and there would be 2+2=4 parts instead of 2 _project = factory.SubFactory(ProjectFactory, _part_handler=None) part1 = factory.RelatedFactory( 'tests.factories.part_library_factories.PartFactory', '_handler', order=0) part2 = factory.RelatedFactory( 'tests.factories.part_library_factories.PartFactory', '_handler', order=1)
class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.fuzzy.FuzzyText(length=12, prefix='') email = factory.LazyAttribute(lambda a: u'{0}@example.com'.format(a.username).lower()) id = factory.fuzzy.FuzzyInteger(0, 256) story = factory.RelatedFactory(StoryFactory) User.objects.create_user(self.username, self.email, factory.fuzzy.FuzzyText(length=12, prefix='')) user = factory.SubFactory(StoryUserFactory)
class CoreUserFactory(BaseFactory): class Meta: model = CoreUser core_user_guid = GUID email = factory.Faker('email') phone_no = factory.Faker('numerify', text='###-###-####') last_logon = TODAY idir_user_detail = factory.RelatedFactory( 'tests.factories.IdirUserDetailFactory', 'core_user')
class ScheduleFactory(factory.DjangoModelFactory): class Meta(object): model = models.Schedule # TODO replace 'start' field with 'start_date' after data migration, # in removing writes from old field step in column renaming release start = factory.Faker('future_datetime', tzinfo=pytz.UTC) upgrade_deadline = factory.Faker('future_datetime', tzinfo=pytz.UTC) enrollment = factory.SubFactory(CourseEnrollmentFactory) experience = factory.RelatedFactory(ScheduleExperienceFactory, 'schedule')
class GatewayFactory(factory.django.DjangoModelFactory): class Meta: model = Gateway # min = 123456789, max = 99999999 external_id = factory.LazyAttribute(lambda o: faker.random_int()) # is created first node = factory.RelatedFactory(NodeFactory, 'gateway', vendor=factory.SelfAttribute('gateway.vendor')) vendor = factory.SubFactory(VendorFactory)
class ApprovedWorkBasketFactory(WorkBasketFactory): class Meta: model = "workbaskets.WorkBasket" approver = factory.SubFactory(UserFactory) status = WorkflowStatus.READY_FOR_EXPORT transaction = factory.RelatedFactory( "common.tests.factories.TransactionFactory", factory_related_name="workbasket", )
class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name = factory.LazyAttribute(lambda x: faker.name()) email = factory.LazyAttribute(lambda x: faker.email()) bio = factory.RelatedFactory('example.factories.AuthorBioFactory', 'author') type = factory.SubFactory(AuthorTypeFactory)
class CityRecordFactory(BaseRecordFactory): city = factory.SubFactory(CityFactory) update_dtm = factory.Sequence( lambda n: datetime(2016, 5, 10, tzinfo=pytz.utc) + timedelta(hours=n)) primary_pollutant = factory.RelatedFactory( 'aqhi.airquality.tests.factories.CityPrimaryPollutantItemFactory', 'city_record') class Meta: model = models.CityRecord
class PrescriberOrganizationWithMembershipFactory(PrescriberOrganizationFactory ): """ Returns a PrescriberOrganization() object with a related PrescriberMembership() object. https://factoryboy.readthedocs.io/en/latest/recipes.html#many-to-many-relation-with-a-through """ membership = factory.RelatedFactory(PrescriberMembershipFactory, "organization")
class TrackFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = Track sqlalchemy_session = db.session event = factory.RelatedFactory(EventFactoryBasic) event_id = 1 name = common.string_ description = common.string_ color = "#0f0f0f"
class FOIACommunicationFactory(factory.django.DjangoModelFactory): """A factory for creating FOIARequest test objects.""" class Meta: model = FOIACommunication foia = factory.SubFactory(FOIARequestFactory) from_who = factory.Sequence(lambda n: "From: %d" % n) priv_from_who = 'Test Sender <*****@*****.**>' date = factory.LazyAttribute(lambda obj: datetime.datetime.now()) rawemail = factory.RelatedFactory('muckrock.factories.RawEmailFactory', 'communication')
class SiteFactory(factory.django.DjangoModelFactory): """ A factory that creates a new device with 10 measuremnts """ class Meta: model = Site name = factory.LazyAttribute(lambda o: faker.street_name()) gateway = factory.RelatedFactory(GatewayFactory, 'site')
class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda num: f"user_{num}") password = Faker("text", max_nb_chars=10) address = factory.RelatedFactory(AddressFactory, factory_related_name="user") class Meta: model = User
class InformatieObjectTypeFactory(factory.django.DjangoModelFactory): omschrijving = factory.Sequence( lambda n: "Informatie object type {}".format(n)) catalogus = factory.SubFactory(CatalogusFactory) zaaktypen = factory.RelatedFactory(ZaakTypeInformatieObjectTypeFactory, "informatieobjecttype") datum_begin_geldigheid = date(2018, 1, 1) class Meta: model = InformatieObjectType
def test_user_with_non_matching_moderator_languages(self): user = BypassStaffModerationUserFactory( profile=factory.RelatedFactory( "mresponse.users.tests.factories.UserProfileFactory", factory_related_name="user", permissions_in_locales=["de", "fr"], ) ) review = ReviewFactory(review_language="es") self.assertFalse(user_can_bypass_staff_approval_for_review(user, review))
class BookFactory(factory.Factory): """Test factory with all the features.""" class Meta: model = Book name = "Alice in Wonderland" price = factory.LazyAttribute(lambda f: 3.99) author = factory.SubFactory(AuthorFactory) book_edition = factory.RelatedFactory( "tests.test_factory_fixtures.EditionFactory", "book")
def test_user_non_moderator(self): user = UserFactory( profile=factory.RelatedFactory( "mresponse.users.tests.factories.UserProfileFactory", factory_related_name="user", permissions_in_locales=["en"], ) ) review = ReviewFactory(review_language="en") self.assertFalse(user_can_bypass_staff_approval_for_review(user, review))
class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ("username", ) username = "******" profile = factory.RelatedFactory( "mresponse.users.tests.factories.UserProfileFactory", factory_related_name="user", )
class BaseUserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() django_get_or_create = ("email", ) username = factory.LazyFunction(generate_username) first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') email = factory.Faker('email') profile = factory.RelatedFactory(ProfileFactory, 'user')