我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用faker.Factory.create()。
def create_payment(delivery_group): order = delivery_group.order status = random.choice( [PaymentStatus.WAITING, PaymentStatus.PREAUTH, PaymentStatus.CONFIRMED]) payment = Payment.objects.create( order=order, status=status, variant='default', transaction_id=str(fake.random_int(1, 100000)), currency=settings.DEFAULT_CURRENCY, total=order.get_total().gross, delivery=delivery_group.shipping_price.gross, customer_ip_address=fake.ipv4(), billing_first_name=order.billing_address.first_name, billing_last_name=order.billing_address.last_name, billing_address_1=order.billing_address.street_address_1, billing_city=order.billing_address.city, billing_postcode=order.billing_address.postal_code, billing_country_code=order.billing_address.country) if status == PaymentStatus.CONFIRMED: payment.captured_amount = payment.total payment.save() return payment
def user_creator(num_user): """Create users from an Italian-like context. Due to param in factory create 'it_iT'.""" for i in range(num_user): user_uuid = fake.uuid4() first_name = fake.first_name() last_name = fake.last_name() email_provider = fake.free_email_domain() email_user = '{}.{}@{}'.format( first_name.lower(), last_name.lower(), email_provider) password = fake.password(length=3, special_chars=False, digits=True, upper_case=True, lower_case=False) User.create( uuid=user_uuid, first_name=first_name, last_name=last_name, email=email_user, password=User.hash_password(password) )
def item_creator(num_item): LIST_CATEGORIES = ['scarpe', 'accessori', 'abbigliamento uomo', 'abbigliamento donna'] for i in range(num_item): item_id = fake.uuid4() item_name = fake.sentence(nb_words=3, variable_nb_words=True) item_price = fake.pyfloat(left_digits=2, right_digits=2, positive=True) item_category = random.choice(LIST_CATEGORIES) item = Item.create( uuid=item_id, name=item_name, price=item_price, description=fake.paragraph( nb_sentences=3, variable_nb_sentences=True), availability=random.randint(35, 60), category=item_category, ) picture_creator(num_item, i, item)
def make_mock_transfer_sub(from_org, to_org): sub = factories.FormSubmissionWithOrgsFactory.create( organizations=[from_org]) application = sub.applications.first() author = from_org.profiles.first().user # make a status_update prior to transfer factories.StatusUpdateWithNotificationFactory.create( application=application, author=author) transfer, *stuff = services.transfers_service.transfer_application( author=author, application=application, to_organization=to_org, reason="Transporter malfunction") message = 'Your case has been transferred to {}.\n{}'.format( to_org.name, to_org.short_confirmation_message) factories.StatusNotificationFactory.create( status_update=transfer.status_update, base_message=message, sent_message=message) return sub
def test_bad_mac_doesnt_evaluate(): fake= Factory().create() assert mac_audit.evaluate_mac( _strip_mac(fake.mac_address()), None ) == 0 assert mac_audit.evaluate_mac( None, None ) == 0 assert mac_audit.evaluate_mac( None, _strip_mac(fake.mac_address()), ) == 0
def c_table (Table, t_config): # create dynamo DB tables """ try to create table, if it errors tables exist, drop the tables, and then rerun the function to create again. """ try: print "INFO :: Creating %s Table....." % Table db_r.create_table( AttributeDefinitions = t_config[Table]['AttributeDefinitions'], TableName=Table, KeySchema = t_config[Table]['KeySchema'], ProvisionedThroughput=t_config[Table]['ProvisionedThroughput'] ) print "INFO :: Waiting for completion..." db_r.Table(Table).wait_until_exists() except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "ResourceInUseException": print "INFO :: Learning Online %s Table exists, deleting ...." % Table db_r.Table(Table).delete() print "INFO :: Waiting for delete.." db_r.Table(Table).wait_until_not_exists() c_table (Table, t_config) else: print "Unknown Error" #------------------------------------------------------------------------------
def setUp(self): from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") """Setup the test driver and create test users""" self.driver = webdriver.Chrome(chrome_options=chrome_options) self.driver.get(self.get_server_url()) email_admin = test_admin_email db.session.commit() db.drop_all() db.create_all() user_datastore.create_user(email=test_admin_email, username=test_admin_username, password=test_admin_password) user_datastore.create_user(email=test_user_final_email, username=test_user_final_username, password=test_user_final_password) user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') user_datastore.add_role_to_user(email_admin, 'admin') db.session.commit()
def create_challenge(title, start_date, end_date, host_team): """ Creates a challenge. """ evaluation_script = open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'string_matching.zip'), 'rb') Challenge.objects.create( title=title, short_description=fake.paragraph(), description=fake.paragraph(), terms_and_conditions=fake.paragraph(), submission_guidelines=fake.paragraph(), evaluation_details=fake.paragraph(), evaluation_script=SimpleUploadedFile(evaluation_script.name, evaluation_script.read()), approved_by_admin=True, creator=host_team, published=True, enable_forum=True, anonymous_leaderboard=False, start_date=start_date, end_date=end_date, ) print("Challenge created with title: {} creator: {} start_date: {} end_date: {}".format(title, host_team.team_name, start_date, end_date))
def create_challenge_phases(challenge, number_of_phases=1): """ Creates challenge phases for the created challenges and returns it. """ challenge_phases = [] for i in range(number_of_phases): name = "{} Phase".format(fake.first_name()) with open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'test_annotation.txt'), 'rb') as data_file: data = data_file.read() data = data or None challenge_phase = ChallengePhase.objects.create( name=name, description=fake.paragraph(), leaderboard_public=True, is_public=True, start_date=challenge.start_date, end_date=challenge.end_date, challenge=challenge, test_annotation=SimpleUploadedFile(fake.file_name(extension="txt"), data, content_type="text/plain"), codename="{}{}".format("phase", i + 1), ) challenge_phases.append(challenge_phase) print("Challenge Phase created with name: {} challenge: {}".format(name, challenge.title)) return challenge_phases
def setUp(self): """ Set up reusable fake data. """ self.user = UserFactory.create(is_staff=True, is_active=True) self.user.set_password("QWERTY") self.user.save() self.client = Client() self.demo_course_1 = FAKE_PROGRAM_RESPONSE3['courses'][0] self.demo_course_2 = FAKE_PROGRAM_RESPONSE3['courses'][1] self.demo_course_id1 = FAKE_PROGRAM_RESPONSE3['courses'][0]['key'] self.demo_course_id2 = FAKE_PROGRAM_RESPONSE3['courses'][1]['key'] self.demo_course_ids = [self.demo_course_id1, self.demo_course_id2] self.dummy_program_uuid = FAKE_PROGRAM_RESPONSE3['uuid'] self.dummy_program = FAKE_PROGRAM_RESPONSE3 super(TestProgramEnrollmentView, self).setUp()
def setUp(self): self.user = UserFactory.create(is_staff=True, is_active=True) self.user.set_password("QWERTY") self.user.save() self.client = Client() self.demo_course_id = 'course-v1:edX+DemoX+Demo_Course' self.dummy_demo_course_modes = [ { "slug": "professional", "name": "Professional Track", "min_price": 100, "sku": "sku-audit", }, { "slug": "audit", "name": "Audit Track", "min_price": 0, "sku": "sku-audit", }, ] super(TestHandleConsentEnrollmentView, self).setUp()
def setUp(self): self.user = UserFactory.create(is_staff=True, is_active=True) self.user.set_password("QWERTY") self.user.save() self.client = Client() self.demo_course_id = 'course-v1:edX+DemoX+Demo_Course' self.dummy_demo_course_modes = [ { "slug": "professional", "name": "Professional Track", "min_price": 100, "sku": "sku-professional", }, { "slug": "audit", "name": "Audit Track", "min_price": 0, "sku": "sku-audit", }, ] self.faker = FakerFactory.create() self.provider_id = self.faker.slug() # pylint: disable=no-member super(TestCourseEnrollmentView, self).setUp()
def test_string_conversion(self, method): """ Test ``EnterpriseCustomerCatalog`` conversion to string. """ faker = FakerFactory.create() uuid = faker.uuid4() # pylint: disable=no-member name = 'EnterpriseWithACatalog' enterprise_catalog = EnterpriseCustomerCatalog( uuid=uuid, enterprise_customer=factories.EnterpriseCustomerFactory(name=name) ) expected_str = "<EnterpriseCustomerCatalog with uuid '{uuid}' for EnterpriseCustomer {name}>".format( uuid=uuid, name=name ) self.assertEqual(method(enterprise_catalog), expected_str)
def test_project_estimate(self): project = Project.objects.create( client=self.client, name='Testing', estimate=5000.00 ) task = Task.objects.create( name='Testing', hourly_rate=100.00 ) Entry.objects.create( project=project, user=self.user, task=task, duration=timedelta(hours=10), note='Creating tests for the core app' ) self.assertEqual(project.get_percent_done(), 20)
def logIn(self): self.user = User.objects.create_user(self.profile['username'], self.profile['mail'], self.profile['password']) site_permission = SitePermission.objects.create(user=self.user) site_permission.sites.set(Site.objects.filter(id=1)) site_permission.save() self.driver.get('%s%s' % (self.live_server_url, '/login/')) username_input = self.find(By.NAME, 'username') self.clear(username_input) username_input.send_keys(self.profile['username']) password_input = self.find(By.NAME, 'password') self.clear(password_input) password_input.send_keys(self.profile['password']) self.find(By.NAME, 'login').click() self.waitForPresence((By.ID, 'nav-app'))
def init_api_test_data(): """ Generates fake data, starts an HttpClient session, creates a fake user and logs that user in. """ call_command('migrate', verbosity=0) call_command('fake', verbosity=0, iterations=1) c = HttpClient() fake_user = fake.simple_profile() fake_password = fake.password() user = User.objects.create_user(fake_user['username'], fake_user['mail'], fake_password) site_permission = SitePermission.objects.create(user=user) site_permission.sites.set(Site.objects.filter(id=1)) site_permission.save() user = User.objects.get(username=fake_user['username']) c.login(username=fake_user['username'], password=fake_password) return [c, user]
def populate_model(model, instances, create=True): model_fields = filter((lambda x: isinstance(x, models.Field)), model._meta.get_fields()) kwargs = {} # Outstanding instances in case of Many-to-Many relations. outstanding = {} for model_field in model_fields: if isinstance(model_field, models.AutoField): continue field_value, isoutstanding = generate_field_value( model_field, instances) if isoutstanding: outstanding[model_field.name] = field_value else: kwargs[model_field.name] = field_value if not create: return kwargs return create_instance(model, kwargs, outstanding)
def faker(): return Factory.create()
def create_product(**kwargs): defaults = { 'name': fake.company(), 'price': fake.price(), 'description': '\n\n'.join(fake.paragraphs(5))} defaults.update(kwargs) return Product.objects.create(**defaults)
def create_stock(variant, **kwargs): default_location = StockLocation.objects.get_or_create( name=STOCK_LOCATION)[0] defaults = { 'variant': variant, 'location': default_location, 'quantity': fake.random_int(1, 50)} defaults.update(kwargs) return Stock.objects.create(**defaults)
def create_variant(product, **kwargs): defaults = { 'product': product} defaults.update(kwargs) variant = ProductVariant.objects.create(**defaults) create_stock(variant) return variant
def create_address(): address = Address.objects.create( first_name=fake.first_name(), last_name=fake.last_name(), street_address_1=fake.street_address(), city=fake.city(), postal_code=fake.postcode(), country=fake.country_code()) return address
def create_order_line(delivery_group): product = Product.objects.all().order_by('?')[0] variant = product.variants.all()[0] return OrderedItem.objects.create( delivery_group=delivery_group, product=product, product_name=product.name, product_sku=variant.sku, quantity=random.randrange(1, 5), unit_price_net=product.price.net, unit_price_gross=product.price.gross)
def create_fake_order(): user = random.choice([None, User.objects.filter( is_superuser=False).order_by('?').first()]) if user: user_data = { 'user': user, 'billing_address': user.default_billing_address, 'shipping_address': user.default_shipping_address} else: address = create_address() user_data = { 'billing_address': address, 'shipping_address': address, 'user_email': get_email( address.first_name, address.last_name)} order = Order.objects.create(**user_data) order.change_status(OrderStatus.PAYMENT_PENDING) delivery_group = create_delivery_group(order) lines = create_order_lines(delivery_group, random.randrange(1, 5)) order.total = sum( [line.get_total() for line in lines], delivery_group.shipping_price) order.save() payment = create_payment(delivery_group) if payment.status == PaymentStatus.CONFIRMED: order.change_status(OrderStatus.FULLY_PAID) if random.choice([True, False]): order.change_status(OrderStatus.SHIPPED) return order
def create_fake_sale(): sale = Sale.objects.create( name='Happy %s day!' % fake.word(), type=Sale.PERCENTAGE, value=random.choice([10, 20, 30, 40, 50])) for product in Product.objects.all().order_by('?')[:4]: sale.products.add(product) return sale
def create_shipping_methods(): shipping_method = ShippingMethod.objects.create(name='UPC') shipping_method.price_per_country.create(price=fake.price()) yield 'Shipping method #%d' % shipping_method.id shipping_method = ShippingMethod.objects.create(name='DHL') shipping_method.price_per_country.create(price=fake.price()) yield 'Shipping method #%d' % shipping_method.id
def create_nickname(): faker = Factory.create(settings.LANGUAGE_CODE) return faker.first_name_female()
def fake_sort_key(): """Generate a fake sort-key in the form of user-email+account_id""" fake = Factory.create() account_id = "671642278147" email = fake.email() return "{account_id}+{email}".format(account_id=account_id, email=email)
def create(self): people = list(self.people.keys()) random.shuffle(people) return people
def get_databases(): """create a list with the name of each .db file from main folder.""" list_of_db = glob.glob('*.db') return list_of_db
def picture_creator(num_picture, index, item): ALLOWED_EXTENSION = ['jpg', 'jpeg', 'png', 'gif'] pictures_path = get_random_pictures(num_picture) picture_id = fake.uuid4() extension = random.choice(ALLOWED_EXTENSION) Picture.create( uuid=picture_id, extension=extension, item=item ) image_folder = utils.get_image_folder() if not os.path.exists(image_folder): os.makedirs(image_folder) shutil.copy2(pictures_path[index], '/{}/{}.{}'.format(image_folder, picture_id, extension))
def address_creator(num_addr): LIST_COUNTRIES = ['Belgium', 'France', 'Germany', 'Greece', 'Italy', 'Portugal', 'Spain'] for i in range(num_addr): country = random.choice(LIST_COUNTRIES) Address.create( uuid=fake.uuid4(), user=User.select().order_by(fn.Random()).get(), country=country, city=fake.city(), post_code=fake.postcode(), address=fake.street_name(), phone=fake.phone_number(), )
def favorite_creator(num_favorites): for i in range(num_favorites): Favorite.create( uuid=fake.uuid4(), item=Item.select().order_by(fn.Random()).get(), user=User.select().order_by(fn.Random()).get(), )
def fake_invitation(organization, inviter, **kwargs): data = dict( email=fake.free_email(), created=Pacific.localize( fake.date_time_between('-1w', 'now')) ) data.update(kwargs) return models.Invitation.create( organization=organization, inviter=inviter, **data)
def make_submission(): return factories.FormSubmissionWithOrgsFactory.create()
def fillable_pdf(**kwargs): attributes = dict( name="Sample PDF", pdf=File(open( 'tests/sample_pdfs/sample_form.pdf', 'rb')), translator="tests.sample_translator.translate", organization=Organization.objects.get(slug='sf_pubdef') ) attributes.update(kwargs) return FillablePDFFactory.create(**attributes)
def useable_pdf(org): path = getattr(settings, 'TEST_PDF_PATH', os.environ.get('TEST_PDF_PATH')) example_pdf = File(open(path, 'rb')) return FillablePDFFactory.create( name="Clean Slate", pdf=example_pdf, translator="intake.translators.clean_slate.translator", organization=org, )
def masking_gen(attribute_name, details): """ Apply masking to a RDD of rows. Rows are first grouped by key in order to have rows with same value for the column available at same time (if the value is the same, the mask will be the same). @FIXME: Define a good size for partitions / groups (for instance use part of string or range of numbers, but it depends on the data type). """ def masking(group): from faker import Factory faker_obj = Factory.create(details.get('lang', 'en_GB')) faker_obj.seed(random.randint(0, 100000)) if not hasattr(faker_obj, details.get('label_type', 'name')): raise ValueError(_('Invalid masking type: {}').format( details.get('label_type'))) action = getattr(faker_obj, details.get('label_type', 'name')) faker_ctx = {} result = [] for row in group[1]: as_dict = row.asDict() value = as_dict.get(attribute_name) if value in faker_ctx: new_value = faker_ctx.get(value) else: new_value = action(**details.get('label_args', {})) faker_ctx[value] = new_value as_dict[attribute_name] = new_value result.append(as_dict) return result return masking
def handle(self, *args, **options): number = options['count'][0] fake = Factory.create('pl_PL') for i in range(number): nauczyciel = Nauczyciel(None, fake.first_name().encode('ascii','ignore'), fake.last_name().encode('ascii','ignore')) nauczyciel.save() nazwaPrzedmiotu = fake.job().encode('ascii','ignore') przedmiot = Przedmiot(None, nazwaPrzedmiotu, nazwaPrzedmiotu[0:3]) przedmiot.save() test = Test(None, random.randint(1, Przedmiot.objects.all().count()), random.randint(5, 15), random.randint(20, 40),fake.sentence(nb_words=6, variable_nb_words=True) ,datetime.date.today(), datetime.date.today(), True) test.save()
def auto_create_sending_domain( self, create, extracted, create_sending_domain=True): if not create: return if create_sending_domain: SendingDomain.objects.create( name=self.name, organization=self.author.organization)
def groups(self, create, extracted, **kwargs): if not create: return if extracted: for group in extracted: if group in [ 'users', 'collaborators', 'managers', 'administrators']: self.groups.add(Group.objects.filter(name=group)[0])
def init(loop): print("Generating Fake Data") pg = await init_postgres(conf['postgres'], loop) fake = Factory.create() fake.seed(1234) await preapre_tables(pg) quiestion_num = 1000 choices_num = 5 question_ids = await generate_questions(pg, quiestion_num, fake) await generate_choices(pg, choices_num, fake, question_ids) pg.close() await pg.wait_closed()
def init(loop): print("Generating Fake Data") mongo = await init_mongo(conf['mongo'], loop) fake = Factory.create() fake.seed(1234) await prepare_coolections(mongo.user, mongo.message, mongo.follower) users = await generate_users(mongo.user, db.user, 100, fake) await generate_messages(mongo.message, db.message, 50, fake, users) user_ids = [v['_id'] for v in users] await generate_followers(mongo.follower, db.follower, 5, fake, user_ids)
def init(loop): print("Generating Fake Data") pg = await init_postgres(conf['postgres'], loop) fake = Factory.create() fake.seed(1234) await prepare_tables(pg) rows = 1000 tag_ids = await generate_tags(pg, 500, fake) post_ids = await generate_posts(pg, rows, fake, tag_ids) await generate_comments(pg, 25, fake, post_ids)