def generateData(request): fixture = AutoFixture( Auction, field_values={ 'auctionTitle': generators.StaticGenerator('autoGenerated_title'), 'description': generators.StaticGenerator('autoGenerated_description'), 'minimumPrice': randint(2, 200) }) entries = fixture.create(50) for e in entries: e.save() return HttpResponseRedirect(reverse('home'))
class RoleAutoFixture(AutoFixture): field_values = { 'name': RoleNameGenerator(), 'github_user': generators.FirstNameGenerator(), 'github_repo': generators.StringGenerator(min_length=6, max_length=10), 'description': generators.LoremGenerator(max_length=250), 'readme': generators.LoremHTMLGenerator(), 'min_ansible_version': generators.StaticGenerator('1.3'), 'issue_tracker_url': generators.URLGenerator(), 'license': generators.StaticGenerator(''), 'company': generators.StaticGenerator(''), 'is_valid': generators.StaticGenerator(True), }
class RegisterDevicesForPatientCompanyAutoFixture(AutoFixture): field_values = { 'Patient_ID': generators.IntegerGenerator(min_value=1, max_value=8000), 'SugarMonitoringDevice': generators.StaticGenerator('X'), 'WorkOutMachineDevice': generators.StaticGenerator('X'), 'PulseMonitor': generators.StaticGenerator('X'), 'TemperatureMonitor': generators.StaticGenerator('X'), 'SleepPatternsMonitor': generators.StaticGenerator('X'), 'GulcoseMonitoringDeviceID': generators.StaticGenerator('X'), 'WorkOutMachineDeviceID': generators.StaticGenerator('X'), 'PulseMonitorID': generators.StaticGenerator('X'), 'TemperatureMonitorID': generators.StaticGenerator('X'), 'SleepPatternsDeviceID': generators.StaticGenerator('X'), }
class UserAutoFixture(AutoFixture): field_values = { 'username': generators.ChoicesGenerator(choices=user_usernames), 'password': generators.StaticGenerator(make_password('demo')), 'first_name': generators.ChoicesGenerator(choices=user_first_names), 'last_name': generators.ChoicesGenerator(choices=user_last_names), }
class PedidoAutoFixture(AutoFixture): field_values = { 'referencia_pedido': generators.StaticGenerator(1), 'unidades': random.randint(100, 5000), 'talla': random.choice(('M', 'L', 'XL', 'XXL')), 'cliente': generators.InstanceSelector(User, limit_choices_to={'username':"******"}), }
class FairsharingRecordAutoFixture(AutoFixture): field_values = { 'name': generators.StringGenerator(max_length=10, min_length=8), 'abbreviation': generators.StringGenerator(max_length=3, min_length=2), 'homepage': generators.URLGenerator(), 'description': generators.LoremGenerator(), 'doi': generators.StaticGenerator(generate_doi(DATACITE_PREFIX)) }
def test_simple_weights(self): results = {"Red": 0, "Blue": 0} choices = [(generators.StaticGenerator("Red"), 50), (generators.StaticGenerator("Blue"), 50)] generate = generators.WeightedGenerator(choices) runs = 10000 for i in range(runs): results[generate()] += 1 MARGIN = 0.025 self.assertTrue( 0.5 - MARGIN < truediv(results["Red"], runs) < 0.5 + MARGIN) self.assertTrue( 0.5 - MARGIN < truediv(results["Blue"], runs) < 0.5 + MARGIN)
class RoleVersionAutoFixture(AutoFixture): choices = [] for major in range(0, 3): for minor in range(0, 9): choices.append("v%d.%d" % (major, minor)) field_values = { 'name': generators.ChoicesGenerator(values=choices), 'loose_version': generators.StaticGenerator("0.0"), }
class PatientHealthDataCompanyAutoFixture(AutoFixture): field_values = { 'Patient_ID': generators.StaticGenerator('X'), 'InsuranceCompanyID': generators.StaticGenerator('X'), 'DataOfReading': generators.StaticGenerator('X'), 'SugarMonitoringDeviceReading': generators.StaticGenerator('X'), 'WorkOutMachineDeviceReading': generators.StaticGenerator('X'), 'PulseMonitorReading': generators.StaticGenerator('X'), 'TemperatureMonitorReading': generators.StaticGenerator('X'), 'SleepPatternsMonitorReading': generators.StaticGenerator('X'), }
class UserRegistration(AutoFixture): field_values = { 'name': generators.StaticGenerator('user_registration'), 'datetime': generators.DateTimeGenerator(min_date=datetime(2018, 1, 1), max_date=datetime(2018, 1, 30)), 'increment': generators.ChoicesGenerator(values=(-1, 1, 1, 1, 1, 1, 1, 1, 1)) }
class UserAutoFixture(AutoFixture): field_values = { 'full_name': FullNameGenerator(), 'username': UserNameGenerator(), 'email': generators.EmailGenerator(), 'password': generators.StaticGenerator('password'), 'is_superuser': False, 'is_staff': WeightedRandomBoolGenerator(percent_chance=3), 'is_active': True, } follow_fk = False follow_m2m = False
def test_unique_together_constraint_one_field_null(self): fixture = AutoFixture(UniqueTogetherNullFieldModel, field_values={ 'field_one': generators.NoneGenerator(), 'field_two': generators.StaticGenerator('test_string') }) self.assertIn(constraints.unique_together_constraint, fixture.constraints) with self.assertRaises(CreateInstanceError): fixture.create_one() fixture.create_one()
def test_complex_weights(self): results = {"frosh": 0, "soph": 0, "jr": 0, "sr": 0} choices = [(generators.StaticGenerator("frosh"), 35), (generators.StaticGenerator("soph"), 20), (generators.StaticGenerator("jr"), 30), (generators.StaticGenerator("sr"), 15)] generate = generators.WeightedGenerator(choices) runs = 10000 for i in range(runs): results[generate()] += 1 MARGIN = 0.025 self.assertTrue( 0.35 - MARGIN < truediv(results["frosh"], runs) < 0.35 + MARGIN, results["frosh"] / 1.0 * runs) self.assertTrue( 0.20 - MARGIN < truediv(results["soph"], runs) < 0.20 + MARGIN) self.assertTrue( 0.30 - MARGIN < truediv(results["jr"], runs) < 0.30 + MARGIN) self.assertTrue( 0.15 - MARGIN < truediv(results["sr"], runs) < 0.15 + MARGIN)
def __init__(self, *args, **kwargs): ''' By default the password is set to an unusable value, this makes it impossible to login with the generated users. If you want to use for example ``autofixture.create_one('auth.User')`` in your unittests to have a user instance which you can use to login with the testing client you can provide a ``username`` and a ``password`` argument. Then you can do something like:: autofixture.create_one('auth.User', username='******', password='******'foo', password='******') ''' self.username = kwargs.pop('username', None) self.password = kwargs.pop('password', None) super(UserFixture, self).__init__(*args, **kwargs) if self.username: self.field_values['username'] = generators.StaticGenerator( self.username)
def handle(self, *args, **options): AutoFixture( Metric, field_values={ 'name': generators.StaticGenerator('user_registration'), 'datetime': generators.DateTimeGenerator(min_date=datetime(2018, 1, 1), max_date=datetime(2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), 'data': generators.StaticGenerator({'dummy': True}), }).create(160) AutoFixture(Metric, field_values={ 'name': generators.StaticGenerator('event_registration'), 'datetime': generators.DateGenerator(min_date=datetime(2018, 1, 1), max_date=datetime( 2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(2, )), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 1, 'event_id': 1 }), }).create(int(114 * 3)) AutoFixture(Metric, field_values={ 'name': generators.StaticGenerator('event_attendance'), 'datetime': generators.DateGenerator(min_date=datetime(2018, 1, 1), max_date=datetime( 2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(1, )), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 1, 'event_id': 1 }), }).create(int(114 * 3)) AutoFixture( Metric, field_values={ 'name': generators.StaticGenerator('group_join'), 'datetime': generators.DateTimeGenerator(min_date=datetime(2018, 1, 1), max_date=datetime(2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 1, 'event_id': 1 }), }).create(140) AutoFixture( Metric, field_values={ 'name': generators.StaticGenerator('create_event'), 'datetime': generators.DateTimeGenerator(min_date=datetime(2018, 1, 1), max_date=datetime(2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 1, 'event_id': 1 }), }).create(140) AutoFixture(Metric, field_values={ 'name': generators.StaticGenerator('event_registration'), 'datetime': generators.DateGenerator(min_date=datetime(2018, 1, 1), max_date=datetime( 2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(2, )), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 2 }), }).create(int(114 * 3)) AutoFixture(Metric, field_values={ 'name': generators.StaticGenerator('event_attendance'), 'datetime': generators.DateGenerator(min_date=datetime(2018, 1, 1), max_date=datetime( 2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(1, )), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 2 }), }).create(int(114 * 3)) AutoFixture( Metric, field_values={ 'name': generators.StaticGenerator('group_join'), 'datetime': generators.DateTimeGenerator(min_date=datetime(2018, 1, 1), max_date=datetime(2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 2 }), }).create(140) AutoFixture( Metric, field_values={ 'name': generators.StaticGenerator('create_event'), 'datetime': generators.DateTimeGenerator(min_date=datetime(2018, 1, 1), max_date=datetime(2018, 4, 24)), 'increment': generators.ChoicesGenerator(values=(-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), 'data': generators.StaticGenerator({ 'dummy': True, 'group_id': 2 }), }).create(140)
def get_generator(self, field): ''' Return a value generator based on the field instance that is passed to this method. This function may return ``None`` which means that the specified field will be ignored (e.g. if no matching generator was found). ''' if isinstance(field, fields.AutoField): return None if self.is_inheritance_parent(field): return None if ( field.default is not fields.NOT_PROVIDED and not self.overwrite_defaults and field.name not in self.field_values): return None kwargs = {} if field.name in self.field_values: value = self.field_values[field.name] if isinstance(value, generators.Generator): return value elif isinstance(value, AutoFixture): return generators.InstanceGenerator(autofixture=value) elif callable(value): return generators.CallableGenerator(value=value) return generators.StaticGenerator(value=value) if field.null: kwargs['empty_p'] = self.none_p if field.choices: return generators.ChoicesGenerator(choices=field.choices, **kwargs) if isinstance(field, related.ForeignKey): # if generate_fk is set, follow_fk is ignored. is_self_fk = (get_remote_field_to(field)().__class__ == self.model) if field.name in self.generate_fk and not is_self_fk: return generators.InstanceGenerator( autofixture.get( get_remote_field_to(field), follow_fk=self.follow_fk.get_deep_links(field.name), generate_fk=self.generate_fk.get_deep_links(field.name)), limit_choices_to=get_remote_field(field).limit_choices_to) if field.name in self.follow_fk: selected = generators.InstanceSelector( get_remote_field_to(field), limit_choices_to=get_remote_field(field).limit_choices_to) if selected.get_value() is not None: return selected if field.blank or field.null: return generators.NoneGenerator() if is_self_fk and not field.null: raise CreateInstanceError( u'Cannot resolve self referencing field "%s" to "%s" without null=True' % ( field.name, '%s.%s' % ( get_remote_field_to(field)._meta.app_label, get_remote_field_to(field)._meta.object_name, ) )) raise CreateInstanceError( u'Cannot resolve ForeignKey "%s" to "%s". Provide either ' u'"follow_fk" or "generate_fk" parameters.' % ( field.name, '%s.%s' % ( get_remote_field_to(field)._meta.app_label, get_remote_field_to(field)._meta.object_name, ) )) if isinstance(field, related.ManyToManyField): if field.name in self.generate_m2m: min_count, max_count = self.generate_m2m[field.name] return generators.MultipleInstanceGenerator( autofixture.get(get_remote_field_to(field)), limit_choices_to=get_remote_field(field).limit_choices_to, min_count=min_count, max_count=max_count, **kwargs) if field.name in self.follow_m2m: min_count, max_count = self.follow_m2m[field.name] return generators.InstanceSelector( get_remote_field_to(field), limit_choices_to=get_remote_field(field).limit_choices_to, min_count=min_count, max_count=max_count, **kwargs) if field.blank or field.null: return generators.StaticGenerator([]) raise CreateInstanceError( u'Cannot assign instances of "%s" to ManyToManyField "%s". ' u'Provide either "follow_m2m" or "generate_m2m" argument.' % ( '%s.%s' % ( get_remote_field_to(field)._meta.app_label, get_remote_field_to(field)._meta.object_name, ), field.name, )) if isinstance(field, fields.FilePathField): return generators.FilePathGenerator( path=field.path, match=field.match, recursive=field.recursive, max_length=field.max_length, **kwargs) if isinstance(field, fields.CharField): if isinstance(field, fields.SlugField): generator = generators.SlugGenerator elif isinstance(field, fields.EmailField): return generators.EmailGenerator( max_length=min(field.max_length, 30)) elif isinstance(field, fields.URLField): return generators.URLGenerator( max_length=min(field.max_length, 25)) elif field.max_length > 15: return generators.LoremSentenceGenerator( common=False, max_length=field.max_length) else: generator = generators.StringGenerator return generator(max_length=field.max_length) if isinstance(field, fields.DecimalField): return generators.DecimalGenerator( decimal_places=field.decimal_places, max_digits=field.max_digits) if hasattr(fields, 'BigIntegerField'): if isinstance(field, fields.BigIntegerField): return generators.IntegerGenerator( min_value=-field.MAX_BIGINT - 1, max_value=field.MAX_BIGINT, **kwargs) if isinstance(field, ImageField): return generators.ImageGenerator(storage=field.storage, **kwargs) for field_class, generator in self.field_to_generator.items(): if isinstance(field, field_class): return generator(**kwargs) return None
class SimpleAutoFixture(AutoFixture): field_values = { 'name': generators.StaticGenerator('foo'), }
class InsuranceCompanyAutoFixture(AutoFixture): field_values = { 'InsuranceCompanyName': generators.StaticGenerator('X'), }
class RoleAutoFixture(AutoFixture): field_values = { 'name': generators.StaticGenerator('role_name'), 'github_user': generators.StaticGenerator('github_user'), 'github_repo': generators.StaticGenerator('github_repo'), }