class GeneralProductFactory(ProductFactory): class Meta: model = GeneralProduct camera_app = LazyFunction(get_extended_yes_no_value) camera_device = LazyFunction(get_extended_yes_no_value) microphone_app = LazyFunction(get_extended_yes_no_value) microphone_device = LazyFunction(get_extended_yes_no_value) location_app = LazyFunction(get_extended_yes_no_value) location_device = LazyFunction(get_extended_yes_no_value) personal_data_collected = Faker('sentence') biometric_data_collected = Faker('sentence') social_data_collected = Faker('sentence') how_can_you_control_your_data = Faker('sentence') data_control_policy_is_bad = Faker('boolean') company_track_record = get_random_option( ['Great', 'Average', 'Needs Improvement', 'Bad']) track_record_is_bad = Faker('boolean') track_record_details = Faker('sentence') offline_capable = LazyFunction(get_extended_yes_no_value) offline_use_description = Faker('sentence') @post_generation def set_privacy_policy_link(self, create, extracted, **kwargs): ProductPrivacyPolicyLinkFactory.create(product=self) uses_ai = LazyFunction(get_extended_yes_no_value) ai_uses_personal_data = LazyFunction(get_extended_yes_no_value) ai_is_transparent = LazyFunction(get_extended_yes_no_value) ai_helptext = Faker('sentence')
class UserFactory(DjangoModelFactory): """ Factory for default Django User model. Calls full_clean before saving to ensure that generated User instance is valid. """ class Meta: model = get_user_model() email = LazyFunction(faker.safe_email) first_name = LazyFunction(faker.first_name) last_name = LazyFunction(faker.last_name) password = PostGenerationMethodCall('set_password', 'password') @lazy_attribute def username(self): """ Create a username from faker's profile generator, but ensure that it's not in the database before using it. This is a pre-full_clean check. Uses a simple single uniqueness check, cached against a set of already tried names. 200 max tries is on the username generation, not the round trip to the database - although that could be changed if required. Raises: RuntimeError: If a unique username can not be found after 200 retries. """ unique_usernames = unique_username() non_uniques = set() for _ in range(max_retries): username = next(unique_usernames) username_unique = (username not in non_uniques and get_user_model().objects.filter( username=username).count() == 0) if username_unique: return username non_uniques.add(username) else: non_uniques_str = ', '.join( ['"{}"'.format(name) for name in non_uniques]) message = ( 'Unique username not found after 200 tries. Unique values tried: {}' ).format(non_uniques_str) raise RuntimeError(message) @post_generation def z_full_clean(self, create, extracted, **kwargs): """ Assert that created User is "clean" in Django's opinion if build strategy is happening. NOTE: function name is prefixed with 'z_' so that it runs after the 'password' post generation function. Raises: ValidationError: If there are any invalid fields in the final User object. """ if create: self.full_clean()
class GeneralProductPageFactory(ProductPageFactory): class Meta: model = GeneralProductPage camera_app = LazyFunction(get_extended_yes_no_value) camera_device = LazyFunction(get_extended_yes_no_value) microphone_app = LazyFunction(get_extended_yes_no_value) microphone_device = LazyFunction(get_extended_yes_no_value) location_app = LazyFunction(get_extended_yes_no_value) location_device = LazyFunction(get_extended_yes_no_value) personal_data_collected = Faker('sentence') biometric_data_collected = Faker('sentence') social_data_collected = Faker('sentence') how_can_you_control_your_data = Faker('sentence') data_control_policy_is_bad = Faker('boolean') company_track_record = get_random_option(['Great', 'Average', 'Needs Improvement', 'Bad']) track_record_is_bad = Faker('boolean') track_record_details = Faker('sentence') offline_capable = LazyFunction(get_extended_yes_no_value) offline_use_description = Faker('sentence') uses_ai = LazyFunction(get_extended_yes_no_value) ai_uses_personal_data = LazyFunction(get_extended_yes_no_value) ai_is_transparent = LazyFunction(get_extended_yes_no_value) ai_helptext = Faker('sentence') email = Faker('email') live_chat = Faker('url') phone_number = Faker('phone_number') twitter = '@TwitterHandle'
class DnsRecordFactory(BaseFactory): class Meta: model = DnsRecord record = LazyFunction(random_record) sort = LazyFunction(random_sort) zone = SubFactory(ZoneFactory)
class CommentFactory(DjangoModelFactory): class Meta: model = Comment author = SubFactory(UserFactory) post = SubFactory(PostFactory) text = LazyFunction(lambda: fake.text(randint(20, 1500))) created_at = LazyFunction(lambda: now() - delta(days=365))
class UserFactory(DjangoModelFactory): class Meta: model = AUTH_USER_MODEL email = LazyAttribute(lambda o: '{username}@123.com'.format(username=o.username)) first_name = LazyFunction(fake.first_name) last_name = LazyFunction(fake.last_name) username = Sequence(lambda n: '{}{}'.format(fake.user_name(), n))
class SongFactory(MongoEngineFactory): class Meta: model = Song artist = Sequence(lambda n: 'Good musician %d' % n) title = Sequence(lambda n: 'Good song %d' % n) difficulty = LazyFunction(lambda: round(random.uniform(1.0, 20.0), 2)) level = LazyFunction(lambda: random.randint(1, 20)) released = datetime.datetime.now() ratings = []
class ShopFactory(DjangoModelFactory): class Meta: model = Shop user = SubFactory(UserFactory) name = 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 TodoFactory(DjangoModelFactory): class Meta: model = Todo assignee = factory.SubFactory('todoapp.tests.factories.PersonFactory') id = LazyAttribute(lambda o: randint(0, 10000)) title = LazyAttribute(lambda o: faker.text(max_nb_chars=255)) description = LazyAttribute(lambda o: faker.text(max_nb_chars=1024)) due_date = LazyFunction(faker.date) done = LazyFunction(faker.boolean)
class CarpoolFactory(BaseFactory): """Carpool factory.""" leave_time = LazyFunction(datetime.now) return_time = LazyFunction(lambda: datetime.now() + timedelta(hours=2)) destination = SubFactory(DestinationFactory) driver = SubFactory(PersonFactory) max_riders = 4 class Meta: """Factory configuration.""" model = Carpool
class DnsRequestFactory(BaseFactory): class Meta: model = DnsRequest name = Faker("domain_name") source_address = LazyFunction(fake.ipv4_private) source_port = LazyFunction(random_port) type = "A" protocol = "udp" dns_server = SubFactory(DnsServerFactory) zone = SubFactory(ZoneFactory)
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 NZQAStandardFactory(DjangoModelFactory): """Factory for generating NZQA standards.""" name = Faker('sentence') abbreviation = LazyFunction(lambda: 'AS{}'.format(random.randint(10000, 99999))) level = LazyFunction(lambda: random.randint(1, 3)) class Meta: """Metadata for class.""" model = NZQAStandard
class POETFormSubmissionFactory(DjangoModelFactory): """Factory for generating POET form submissions.""" resource = LazyFunction(lambda: random.choice(Resource.objects.all())) progress_outcome = LazyFunction(get_progress_outcome) feedback = Faker('sentence') class Meta: """Metadata for class.""" model = Submission
class PackageFactory(Factory): class Meta: model = Package package_type = Package.TYPE_BOX width = LazyFunction(lambda: random.randint(11, 30)) height = LazyFunction(lambda: random.randint(2, 30)) length = LazyFunction(lambda: random.randint(18, 30)) weight = LazyFunction(lambda: random.randint(1, 100) * 100) service = LazyFunction(lambda: random.choice(_services)) sequence = Sequence(lambda n: (n, n + 1))
class DnsRequestFactory(BaseFactory): class Meta: model = DnsRequest name = Faker("domain_name") zone_id = None source_address = LazyFunction(fake.ipv4_private) source_port = LazyFunction(random_port) type = "A" protocol = "udp" dns_server_name = LazyFunction(uuid.uuid4)
class QuestionnaireFactory(DjangoModelFactory): graph = SubFactory(QuestionGraphFactory) flow = Questionnaire.EXTRA_PROPERTIES name = LazyFunction(fake.sentence) description = LazyFunction(fake.paragraph) is_active = True class Meta: model = Questionnaire
class VerificationCodeFactory(alchemy.SQLAlchemyModelFactory): class Meta(object): model = VerificationCode sqlalchemy_session = db.session # the SQLAlchemy session object email = "*****@*****.**" phone = "5551231212" code = "98765" expires_at = LazyFunction(get_future_expiry) created_at = LazyFunction(utcnow) updated_at = LazyFunction(utcnow)
class RouteFactory(SQLAlchemyModelFactory): class Meta(metaclass=MetaWithSession): model = Route id = LazyFunction(lambda: str(uuid4())) created_at = LazyFunction(lambda: datetime.now()) protocol = 'http' source_endpoint = '*' destination_override_endpoint = '*' host_endpoint = r'httpbin\.org' port = 443 tags = {'source': 'vgs-satellite'}
class EpisodeFactory(DjangoModelFactory): guid = LazyFunction(lambda: uuid.uuid4().hex) podcast = SubFactory(PodcastFactory) title = Faker("text") description = Faker("text") media_url = Faker("url") media_type = "audio/mpeg" pub_date = LazyFunction(timezone.now) class Meta: model = Episode
class PostFactory(DjangoModelFactory): class Meta: model = Post author = SubFactory(UserFactory) title = LazyFunction(lambda: fake.text(randint(5, 20))) picture = ImageField(color=choice(['blue', 'yellow', 'green', 'orange']), height=randint(250, 1000), width=randint(250, 1000), ) text = LazyFunction(lambda: fake.text(randint(200, 3000))) created_at = LazyFunction(lambda: now() - delta(days=365))
class HttpRequestFactory(BaseFactory): class Meta: model = HttpRequest name = Faker("domain_name") path = "/some/fake/path" source_address = LazyFunction(fake.ipv4_private) source_port = LazyFunction(random_port) type = "GET" protocol = "http" http_server = SubFactory(HttpServerFactory) zone = SubFactory(ZoneFactory) raw_request = "some fake data"
class UserFactory(Factory): class Meta: model = settings.AUTH_USER_MODEL strategy = CREATE_STRATEGY first_name = LazyFunction(fake.first_name) last_name = LazyFunction(fake.last_name) email = LazyFunction(fake.email) username = LazyAttribute(lambda o: o.email) password = PostGeneration( lambda obj, *args, **kwargs: obj.set_password(DEFAULT_PASSWORD)) profile = RelatedFactory(ProfileFactory, "user") active_email = RelatedFactory(EmailAddressFactory, "user", email=email)
class ApiTokenFactory(BaseFactory): class Meta: model = ApiToken scopes = "profile dns-request zone:list zone:read" # TODO: better randomness is_active = True expires_at = LazyFunction(random_expires_at) dns_server_name = LazyFunction(uuid.uuid4) @lazy_attribute def token(self): return bearer_token(str(self.dns_server_name), str(self.scopes))
class PermissionFactory(BaseFactory): """Permission factory.""" user = LazyFunction(UserFactory) collection = LazyFunction(CollectionFactory) modified_by = LazyFunction(UserFactory) created_by = LazyFunction(UserFactory) class Meta: """Factory configuration.""" model = Permission
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 GrantFactory(BaseFactory): """Grant factory.""" user = LazyFunction(UserFactory) client = LazyFunction(ClientFactory) code = Sequence(lambda _: 'grantCode{0}'.format(_)) redirect_uri = 'http://example.com' scopes = 'read write' class Meta: """Factory configuration.""" model = Grant
class SignalFactory(DjangoModelFactory): class Meta: model = Signal signal_id = FuzzyAttribute(uuid.uuid4) text = LazyFunction(fake.paragraph) text_extra = LazyFunction(fake.paragraph) # Creating (reverse FK) related objects after this `Signal` is created. location = RelatedFactory( 'signals.apps.signals.factories.location.LocationFactory', '_signal') status = RelatedFactory( 'signals.apps.signals.factories.status.StatusFactory', '_signal') category_assignment = RelatedFactory( 'signals.apps.signals.factories.category_assignment.CategoryAssignmentFactory', '_signal', ) reporter = RelatedFactory( 'signals.apps.signals.factories.reporter.ReporterFactory', '_signal') priority = RelatedFactory( 'signals.apps.signals.factories.priority.PriorityFactory', '_signal') incident_date_start = FuzzyDateTime(timezone.now() - timedelta(days=100), timezone.now()) incident_date_end = LazyAttribute( lambda o: _incident_date_end(o.incident_date_start)) extra_properties = {} # SIG-884 parent = None @post_generation def set_one_to_one_relations(self, create, extracted, **kwargs): """Set o2o relations on given `Signal` object.""" self.location = self.locations.last() self.status = self.statuses.last() self.category_assignment = self.category_assignments.last() self.reporter = self.reporters.last() self.priority = self.priorities.last() @post_generation def set_default_type(self, create, extracted, **kwargs): """ This will add the default Type to the signal for a factory created signal """ if create: from . import TypeFactory TypeFactory( _signal=self) # By default the type is set to "SIG (SIGNAL)"
class UserFactory(DjangoModelFactory): """ Factory for user """ class Meta: model = User first_name = LazyFunction(faker.first_name) last_name = LazyFunction(faker.last_name) username = LazyAttribute( lambda o: slugify(o.first_name) + "." + slugify(o.last_name)) email = LazyAttribute(lambda o: o.username + "@eledus.cz") password = PostGenerationMethodCall('set_password', 'password') is_staff = False is_superuser = False
class SoftwareProductPageFactory(ProductPageFactory): class Meta: model = SoftwareProductPage price = 0 handles_recordings_how = Faker('sentence') recording_alert = LazyFunction(get_extended_yes_no_value) recording_alert_helptext = Faker('sentence') medical_privacy_compliant = LazyFunction(get_extended_boolean_value) medical_privacy_compliant_helptext = Faker('sentence') host_controls = Faker('sentence') easy_to_learn_and_use = LazyFunction(get_extended_boolean_value) easy_to_learn_and_use_helptext = Faker('sentence')