我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用faker.Faker()。
def users(count=100): fake = Faker() i = 0 while i < count: u = User(email=fake.email(), username=fake.user_name(), password='password', confirmed=True, name=fake.name(), location=fake.city(), about_me=fake.text(), member_since=fake.past_date()) db.session.add(u) try: db.session.commit() i += 1 except IntegrityError: db.session.rollback()
def proxy_server(request, salt_root, docker_client): fake = Faker() name = u'proxy_server_{0}_{1}'.format(fake.word(), fake.word()) command = 'python -m tests.scripts.proxy_server {0}'.format(PROXY_PORT) obj = ContainerFactory( config__image=request.config.getini('IMAGE'), config__command=command, config__name=name, config__salt_config=None, config__host_config=docker_client.create_host_config( binds={ os.getcwd(): { 'bind': "/salt-toaster/", 'mode': 'rw' } } ), config__volumes=[os.getcwd()] ) request.addfinalizer(obj.remove) return obj
def create_demo_fixtures(): fake = Faker() name = fake.name() # have username be demo-username, so demos-users are easy to tell username = 'demo-{name}'.format(name=name) username = slugify(username) # since these are demo accounts, just set the username/pass the same # so this is a really weird bug since you'd wonder why this would be a get_or_create # but faker doesn't always generate fake names in celery instances ... user, _ = User.objects.get_or_create(username=username) # create a log of this person as a demo user, otherwise we would never be able to tell if someone is a demo or not! _, created = DemoUserLog.objects.get_or_create(user=user) if not created: return fixtures_builder = DemoHistoricalDataBuilder(user, periods_back=180) fixtures_builder.create_historical_fixtures()
def create_posts_for_user(to_populate=None, count=100): """ Create a number of StreetArtPost objects and associate them with the given user. :param to_populate: The user to populate. :param count: The number of posts to add to the user. :return: The newly-created posts. """ new_posts = [] faker = Faker() for i in range(count): new_posts.append(StreetArtPost.objects.create( latitude=float(faker.random_number()) * 0.01, longitude=float(faker.random_number()) * 0.01, title=faker.word(), description=faker.paragraph(), s3_bucket=faker.word(), s3_key=str(uuid4()), user=to_populate, )) return new_posts
def test_get_Fernet_returns_a_key(): fake = Faker() appname= '_'.join(['test_a_netcrawl_', fake.word(), fake.word()]) username= '_'.join(['test_u_netcrawl_', fake.word(), fake.word()]) key= manage._get_fernet_key(appname, username) assert isinstance(key, fernet.Fernet), 'Key [{}] is wrong type'.format( type(key)) assert keyring.get_password(appname, username) is not None keyring.delete_password(appname, username) assert keyring.get_password(appname, username) is None #=============================================================================== # def test_check_credentials_no_error(): # config.cc.check_credentials() #===============================================================================
def populated_cisco_network_device(): fake= Faker() fake.add_provider(Cisco) nd = CiscoDevice() nd.device_name= '_'.join(['fakedevice', fake.word(), fake.word(), fake.word(), ]) for i in range(1, fake.random_int(1, 10)): nd.serial_numbers.append(fake.ios_serial()) nd.config= fake.text(max_nb_chars=fake.random_int(min=5)) return nd
def generate_fake(count=100, **kwargs): """Generate a number of fake users for testing.""" from sqlalchemy.exc import IntegrityError from random import seed, choice from faker import Faker fake = Faker() roles = Role.query.all() seed() for i in range(count): u = User( first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email(), password=fake.password(), confirmed=True, role=choice(roles), **kwargs) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback()
def test_safe_e164(self): """Test returning all `safe_numbers` Set the `LOGLEVEL` environment variable to 'DEBUG' to see the phone number info for `safe_numbers`""" fake = Faker() # type: Union[E164Provider, Faker] fake.add_provider(self.provider_class) phone_number = fake.safe_e164() self.assertIsInstance(phone_number, str) for region_code in providers.safe_numbers.keys(): with mock.patch('faker_e164.providers.E164Provider.random_element') as random_element: random_element.side_effect = providers.safe_numbers[region_code] for _ in range(len(providers.safe_numbers[region_code])): phone_number = fake.safe_e164(region_code=region_code) self.assertIsInstance(phone_number, str) if os.environ.get('LOGLEVEL', None) == 'DEBUG': phone_number = phonenumbers.parse(phone_number) logger.debug('Phone Number info: {}\nis_valid: {is_valid}\nis_possible: {is_possible}'.format( phone_number, is_valid=phonenumbers.is_valid_number(phone_number), is_possible=phonenumbers.is_possible_number(phone_number) ))
def test_faker(ourtestdir): ourtestdir.makepyfile( test_one=""" from faker import Faker fake = Faker() def test_one(): assert fake.name() == 'Ryan Gallagher' def test_two(): assert fake.name() == 'Ryan Gallagher' """ ) out = ourtestdir.runpytest('--randomly-seed=1') out.assert_outcomes(passed=2)
def minion_container(request, salt_root, minion_container_extras, salt_minion_config, docker_client): fake = Faker() image = request.config.getini('MINION_IMAGE') or request.config.getini('IMAGE') obj = ContainerFactory( config__name='minion_{0}_{1}'.format(fake.word(), fake.word()), config__docker_client=docker_client, config__image=image, config__salt_config__tmpdir=salt_root, config__salt_config__conf_type='minion', config__salt_config__config={ 'base_config': salt_minion_config }, **minion_container_extras ) request.addfinalizer(obj.remove) return obj
def populate_persons(n=50): from faker import Faker from pony.orm import db_session from fbcm.models import Player fake = Faker() with db_session: for _ in range(n): try: Player( id=fake.numerify('#' * 10), name=fake.first_name(), lastname=fake.last_name(), ) except Exception: continue
def create_mock_gigya_user(self): """Create a simple mocked Gigya user""" fake = Faker() profile = Profile() profile.first_name = fake.first_name_female() profile.last_name = fake.last_name() profile.street = 'Medialaan' profile.house_number = '1' profile.box_number = '' profile.postal_code = '1800' profile.city = 'Vilvoorde' profile.birth_date = datetime(1990, 5, 20) profile.place_of_birth = 'Vilvoorde' email = '{}.{}@veryrealemail.com'.format(profile.first_name, profile.last_name) password = 'stievie' return { 'profile': profile, 'username': email, 'password': password }
def setUp(self): self.faker = faker.Faker()
def setUp(self): self.faker = faker.Faker() self.semaphore = mock.Mock() self.original_semaphore = threading.Semaphore threading.Semaphore = mock.MagicMock(return_value=self.semaphore) self.semaphore.reset_mock()
def setUp(self): self.images = mock.Mock() self.client = mock.Mock() self.faker = faker.Faker() self.dockerErrorsNotFound = docker.errors.NotFound
def django_file(cls, extension=None): """Generates a random file. Example: >>> from factory import DjangoModelFactory >>> >>> class ProductFactory(DjangoModelFactory): >>> "Product factory." >>> >>> # ... >>> >>> image_file = Faker('django_file', extension='image') >>> video_file = Faker('django_file', extension='video') >>> text_file = Faker('django_file', extension='text') >>> >>> # ... :param extension: File extension. :type extension: str :return: File object. """ fake = FakerFaker() django_file = get_temporary_file(fake.file_name(extension=extension)) return File(django_file)
def minion_id(): fake = Faker() return u'{0}_{1}'.format(fake.word(), fake.word())
def __init__(self): self._master, self._slave = pty.openpty() self._s_name = os.ttyname(self._slave) self._fake = Faker() self._fake_device = threading.Thread(target=self.__run)
def test_pings_on_avatar_save_current(fake_send_update_ping, settings): settings.DISCOURSE_SERVER = 'http://discourse.example.com' settings.DISCOURSE_API_KEY = 'discourse-api-key' user = UserFactory.create() avatar = AvatarFactory.create(user=user) user.current_avatar = avatar user.save() fake_send_update_ping.reset_mock() avatar.remote_url = faker.Faker().image_url() avatar.save() fake_send_update_ping.assert_called_once_with(user)
def fake(): return faker.Faker()
def user_factory(troubleshooter=False, superuser=False, backoffice=False, password=None): fake = Faker('en-US') u = User(username=fake.user_name(), firstname=fake.first_name(), lastname=fake.last_name(), is_active=True, is_superuser=superuser, is_backoffice_user=backoffice, is_troubleshooter=troubleshooter) u.set_password(password or fake.password()) if troubleshooter: u.auth_token = get_random_string(32) u.save() return u
def item_factory(): fake = Faker('en-US') return Item.objects.create(name=fake.state(), description=fake.bs(), initial_stock=random.randint(50, 1000))
def cashdesk_factory(ip=None, active=None): fake = Faker('en-US') return Cashdesk.objects.create(name='Cashdesk {}'.format(random.randint(0, 10)), ip_address=ip or fake.ipv4(), is_active=active if active is not None else True)
def time_constraint_factory(active=True): fake = Faker('en-US') if active: start = fake.date_time_between(start_date='-23h', end_date='-1h') end = fake.date_time_between(start_date='+1h', end_date='+23h') else: start = fake.date_time_between(start_date='-23h', end_date='-10h') end = fake.date_time_between(start_date='-9h', end_date='-2h') return TimeConstraint.objects.create(name='Time Constraint', start=start, end=end)
def product_factory(items=False): fake = Faker('en-US') p = Product.objects.create(name=fake.catch_phrase(), price=random.choice([50 * i for i in range(5)]), tax_rate=19) if items: ProductItem.objects.create(item=item_factory(), product=p, amount=1) return p
def setUp(self): super().setUp(DeviceServer) self.faker = Faker()
def fake_binary(self): """ Return random binary format. Faker Factory also provide about this binary. Example: b"\x00\x01\x02\x03\x04\x05\x06\x07" b"\x0b\x0c\x0e\x0f" 1. from Djipsum faker.fake_binary() 2. from Faker Factory faker.fake.binary(length=10) """ return self.djipsum_fields().randomBinaryField()
def fake_null_boolean(self): """ Faker Factory also provide about this null boolean. Example: None, True, False 1. from Djipsum faker.fake_null_boolean() 2. from Faker Factory faker.fake.null_boolean() """ return self.djipsum_fields().randomize([None, True, False])
def fake_file(self): """ Return string name of file. Faker Factory also provide about this file. Example: file.zip, awesomefile.tar.gz, samplefile.docx, djipsum.pdf 1. from Djipsum faker.fake_file() 2. from Faker Factory faker.fake.file_name() """ return self.djipsum_fields().randomFileField()
def fake_ipaddress(self): """ Faker Factory also provide about this ipaddress, such as ipv4, ipv6, ...etc Example: 192.168.1.1, 66.249.65.54, 255.255.255.0, 2001:db8:a0b:12f0::1 1. from Djipsum faker.fake_ipaddress() 2. from Faker Factory faker.fake.ipv4(), faker.fake.ipv6() """ return self.djipsum_fields().randomGenericIPAddressField()
def fake_paragraphs(self): """ Generate the paragraphs for `TextField`. Faker Factory also provide about this paragraphs. Example: 1. from Djipsum faker.fake_paragraphs() 2. from Faker Factory ' '.join(faker.fake.paragraphs()) """ return self.djipsum_fields().randomTextField()
def fake_url(self): """ Generate the url for `URLField`. Faker Factory also provide about this url. Example: `https://python.web.id`, `http://dracos-linux.org` 1. from Djipsum faker.fake_url() 2. from Faker Factory faker.fake.url() """ return self.djipsum_fields().randomURLField()
def generate_contacts(context): contacts_list = ctx.web.lists.get_by_title("Contacts") fake = Faker() for idx in range(0, 1): name = fake.name() contact_properties = {'__metadata': {'type': 'SP.Data.ContactsListItem'}, 'Title': name} contact_item = contacts_list.add_item(contact_properties) context.execute_query() print("Contact '{0}' has been created".format(contact_item.properties["Title"]))
def posts(count=100): fake = Faker() user_count = User.query.count() for i in range(count): u = User.query.offset(randint(0, user_count - 1)).first() p = Post(body=fake.text(), timestamp=fake.past_date(), author=u) db.session.add(p) db.session.commit()
def get_create_post_kwargs(): """ Get a dictionary of values to submit to the post creation endpoint. :return: A dictionary of values to submit to the post creation endpoint. """ faker = Faker() f = open("streetart/tests/files/puppy.jpg", "r") return { "title": faker.word(), "description": faker.paragraph(), "image": f, }
def get_create_user_kwargs(): """ Get a dictionary of values to submit to the user registration endpoint. :return: A dictionary of values to submit to the user registration endpoint. """ faker = Faker() return { "email": faker.email(), "first_name": faker.first_name(), "last_name": faker.last_name(), "password": faker.password(), }
def get_edit_post_kwargs(): """ Get a dictionary of values to submit to the edit post endpoint. :return: A dictionary of values to submit to the edit post endpoint. """ faker = Faker() return { "title": faker.word(), "description": faker.paragraph(), "latitude": float(faker.pydecimal()), "longitude": float(faker.pydecimal()), }
def fake(): _fake = Faker() _fake.add_provider(human.HumanProvider) _fake.add_provider(alien.AlienProvider) _fake.add_provider(binary.BinaryProvider) _fake.add_provider(chemistry.ChemistryProvider) _fake.add_provider(biology.GeneticProvider) return _fake
def test_locate_mac_runs_without_error(): fake = Faker() for i in range(10): locate(fake.mac_address())
def inventory_db(): """Sets up a test inventory database and returns the database name""" config.parse_config() fake = Faker() dbname= '_'.join(['fakedb', fake.word(), fake.word(), fake.word(), ]) config.cc.inventory.name = dbname # Create the database db= io_sql.sql_database() db.create_database(dbname) assert db.database_exists(dbname) del(db) print('Inventroy_db: ', dbname) # Pass the database to the test functions yield print('Done with inventory_db: ', dbname) # Delete the database after use db= io_sql.sql_database() db.delete_database(dbname) assert not db.database_exists(dbname)
def waitinglistentries(event, items): fake = faker.Faker() for i in range(42): event.waitinglistentries.create( item=random.choice(items), created=fake.date_time_between(start_date="-14d", end_date="now", tzinfo=None), email=fake.email() )
def setUpTestData(cls): """Set up class.""" # Create user cls.user = factories.TestUsernameSuperAdminUserFactory() # Fake data cls.faker = Faker()