Faker 4.1.2

Example Usage

First define your settings for keys and the number and type of objects to create.


If you are using the unsplash photo provider you will have to pass in a few additional settings. If you want to use a different image provider, pass in the class to that provider.

All other settings have defaults, so feel free to modify what you want and leave blank the rest.

$settings = [
    // required for photo providers
    'unsplash_app_id' => 'your_unsplash_app_id', // unsplash specific
    'interior_collection' => collection_id, // unsplash collection or filesystem path if using local photo provider
    'exterior_collection' => collection_id, // unsplash collection or filesystem path if using local photo provider
    'portrait_collection' => collection_id, // unsplash collection or filesystem path if using local photo provider
        
    // Optional photo provider, if not using unsplash (you can ignore the above, too).
    'photo_provider' => \FeedFaker\Helper\UnsplashPhotoProvider::class,

    // Basic settings, all with defaults.
    'mls_id' => 'my-awesome-mls',
    
    // the number of objects you want to create for each resource type.
    'office_count' => 50,
    'member_count' => 150,
    'property_count' => 500,
    'openhouse_count' => 1000,
    'history_count' => 1000,
    'media_count' => 5000,
];

You may provide a valid full path to a php settings file that returns an array, if you prefer. An example is in .

Now that you’re all setup, instantiate it and fire away:

$settings = [
    'unsplash_app_id' => 'my-app-id-from-unsplash'
    'interior_collection' => 10
    'exterior_collection' => 1010
    'portrait_collection' => 101010
    
    // optional
    'mls_id' => 'best-mls-in-the-universe',
    'history_count' => 500
];

$feedfake = new FeedFaker\FakeFeed();
$data = $feedfake->go($settings);

$properties = $data;
$offices = $data;
$members = $data;
$media = $data;
$history = $data;
$openhouses = $data;

foreach ($properties as $property) {
    echo $property->getListingKey() . PHP_EOL;

    var_dump($property->toArray());
}

Yep, that’s it. You’re welcome.

JavaFaker’s Faker Class

The Faker class allows us to use JavaFaker’s fake data classes.

In this section, we’ll see how to instantiate a Faker object and use it to call some fake data:

Above, we use the Faker Address object to generate a random address.

When we run this code, we’ll get an example of the output:

We can see that the data has no single geographical location since we didn’t specify a locale. To change this, we’ll learn to make the data more relevant to our location in the next section.

We could also use this faker object in a similar way to create data relating to many more objects such as:

  • Business
  • Beer
  • Food
  • PhoneNumber

You can find the full list here.

Localization

As of version faker.js has support for multiple localities.

The default language locale is set to English.

Setting a new locale is simple:

faker.setLocale("de");faker.locale="de";
  • az
  • cz
  • de
  • de_AT
  • de_CH
  • en
  • en_AU
  • en_BORK
  • en_CA
  • en_GB
  • en_IE
  • en_IND
  • en_US
  • en_ZA
  • en_au_ocker
  • es
  • es_MX
  • fa
  • fr
  • fr_CA
  • ge
  • id_ID
  • it
  • ja
  • ko
  • nb_NO
  • nep
  • nl
  • pl
  • pt_BR
  • ru
  • sk
  • sv
  • tr
  • uk
  • vi
  • zh_CN
  • zh_TW

As of vesion faker.js supports incremental loading of locales.

By default, requiring will include all locale data.

In a production environment, you may only want to include the locale data for a specific set of locales.

var faker =require('faker/locale/de');

Third-Party Libraries Extending/Based On Faker

  • BazingaFakerBundle: Put the awesome Faker library into the Symfony2 DIC and populate your database with fake data.
  • FakerServiceProvider: Faker Service Provider for Silex
  • faker-cli: Command Line Tool for the Faker PHP library
  • AliceFixturesBundle: A Symfony2 bundle for using Alice and Faker with data fixtures. Abled to use Doctrine ORM as well as Doctrine MongoDB ODM.
  • Factory Muffin: enable the rapid creation of objects (PHP port of factory-girl)
  • CompanyNameGenerator: Generate names for English tech companies with class
  • datalea A highly customizable random test data generator web app
  • xml-faker: Create fake XML with Faker

Maintainer

Marak Squires

faker.js — Copyright (c) 2017 Marak Squires http://github.com/marak/faker.js/


faker.js was inspired by and has used data definitions from:

  • https://github.com/stympy/faker/ — Copyright (c) 2007-2010 Benjamin Curtis
  • http://search.cpan.org/~jasonk/Data-Faker-0.07/ — Copyright 2004-2005 by Jason Kohles

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Localization

As of version faker.js has support for multiple localities.

The default language locale is set to English.

Setting a new locale is simple:

faker.setLocale("de");faker.locale="de";
  • az
  • cz
  • de
  • de_AT
  • de_CH
  • en
  • en_AU
  • en_BORK
  • en_CA
  • en_GB
  • en_IE
  • en_IND
  • en_US
  • en_au_ocker
  • es
  • es_MX
  • fa
  • fr
  • fr_CA
  • ge
  • id_ID
  • it
  • ja
  • ko
  • nb_NO
  • nep
  • nl
  • pl
  • pt_BR
  • ru
  • sk
  • sv
  • tr
  • uk
  • vi
  • zh_CN
  • zh_TW

As of vesion faker.js supports incremental loading of locales.

By default, requiring will include all locale data.

In a production environment, you may only want to include the locale data for a specific set of locales.

var faker =require('faker/locale/de');

Seeding the Generator

When using Faker for unit testing, you will often want to generate the same data set. For convenience, the generator also provide a seed() method, which seeds the shared random number generator. Calling the same methods with the same version of faker and seed produces the same results.

from faker import Faker
fake = Faker()
Faker.seed(4321)

print(fake.name())
# 'Margaret Boehm'

Each generator can also be switched to its own instance of random.Random, separate to the shared one, by using the seed_instance() method, which acts the same way. For example:

from faker import Faker
fake = Faker()
fake.seed_instance(4321)

print(fake.name())
# 'Margaret Boehm'

Please note that as we keep updating datasets, results are not guaranteed to be consistent across patch versions. If you hardcode results in your test, make sure you pinned the version of Faker down to the patch number.

Localization

As of version faker.js has support for multiple localities.

The default language locale is set to English.

Setting a new locale is simple:

faker.setLocale("de");faker.locale="de";
  • az
  • cz
  • de
  • de_AT
  • de_CH
  • en
  • en_AU
  • en_BORK
  • en_CA
  • en_GB
  • en_IE
  • en_IND
  • en_US
  • en_au_ocker
  • es
  • es_MX
  • fa
  • fr
  • fr_CA
  • ge
  • id_ID
  • it
  • ja
  • ko
  • nb_NO
  • nep
  • nl
  • pl
  • pt_BR
  • ru
  • sk
  • sv
  • tr
  • uk
  • vi
  • zh_CN
  • zh_TW

As of vesion faker.js supports incremental loading of locales.

By default, requiring will include all locale data.

In a production environment, you may only want to include the locale data for a specific set of locales.

var faker =require('faker/locale/de');

Basic Usage

Use to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.

<?php
// require the Faker autoloader
require_once '/path/to/Faker/src/autoload.php';
// alternatively, use another PSR-0 compliant autoloader (like the Symfony2 ClassLoader for instance)

// use the factory to create a Faker\Generator instance
$faker = Faker\Factory::create();

// generate data by accessing properties
echo $faker->name;
  // 'Lucy Cechtelar';
echo $faker->address;
  // "426 Jordy Lodge
  // Cartwrightshire, SC 88120-6700"
echo $faker->text;
  // Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
  // beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
  // amet quidem. Iusto deleniti cum autem ad quia aperiam.
  // A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui
  // quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur
  // voluptatem sit aliquam. Dolores voluptatum est.
  // Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est.
  // Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati.
  // Et sint et. Ut ducimus quod nemo ab voluptatum.

Even if this example shows a property access, each call to yields a different (random) result. This is because Faker uses magic, and forwards calls to .

<?php
for ($i=; $i < 10; $i++) {
  echo $faker->name, "\n";
}
  // Adaline Reichel
  // Dr. Santa Prosacco DVM
  // Noemy Vandervort V
  // Lexi O'Conner
  // Gracie Weber
  // Roscoe Johns
  // Emmett Lebsack
  // Keegan Thiel
  // Wellington Koelpin II
  // Ms. Karley Kiehn V

Localization

can take a locale as an argument, to return localized data. If no localized provider is found, the factory falls back to the default en_US locale.

from faker import Faker
fake = Faker('it_IT')
for _ in range(10):
    print(fake.name())

# 'Elda Palumbo'
# 'Pacifico Giordano'
# 'Sig. Avide Guerra'
# 'Yago Amato'
# 'Eustachio Messina'
# 'Dott. Violante Lombardo'
# 'Sig. Alighieri Monti'
# 'Costanzo Costa'
# 'Nazzareno Barbieri'
# 'Max Coppola'

You can check available Faker locales in the source code, under the providers package. The localization of Faker is an ongoing process, for which we need your help. Please don’t hesitate to create a localized provider for your own locale and submit a Pull Request (PR).

Included localized providers:

Basic Usage

Use to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.

<?php
// require the Faker autoloader
require_once '/path/to/Faker/src/autoload.php';
// alternatively, use another PSR-0 compliant autoloader (like the Symfony2 ClassLoader for instance)

// use the factory to create a Faker\Generator instance
$faker = Faker\Factory::create();

// generate data by accessing properties
echo $faker->name;
  // 'Lucy Cechtelar';
echo $faker->address;
  // "426 Jordy Lodge
  // Cartwrightshire, SC 88120-6700"
echo $faker->text;
  // Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
  // beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
  // amet quidem. Iusto deleniti cum autem ad quia aperiam.
  // A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui
  // quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur
  // voluptatem sit aliquam. Dolores voluptatum est.
  // Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est.
  // Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati.
  // Et sint et. Ut ducimus quod nemo ab voluptatum.

Even if this example shows a property access, each call to yields a different (random) result. This is because Faker uses magic, and forwards calls to .

<?php
for ($i=; $i < 10; $i++) {
  echo $faker->name, "\n";
}
  // Adaline Reichel
  // Dr. Santa Prosacco DVM
  // Noemy Vandervort V
  // Lexi O'Conner
  // Gracie Weber
  // Roscoe Johns
  // Emmett Lebsack
  // Keegan Thiel
  // Wellington Koelpin II
  // Ms. Karley Kiehn V

Tip: For a quick generation of fake data, you can also use Faker as a command line tool thanks to faker-cli.

API

faker.js contains a super useful generator method for combining faker API methods using a mustache string format.

Example:

console.log(faker.fake("{{name.lastName}}, {{name.firstName}} {{name.suffix}}"));

This will interpolate the format string with the value of methods , , and

  • address
    • zipCode
    • city
    • cityPrefix
    • citySuffix
    • streetName
    • streetAddress
    • streetSuffix
    • streetPrefix
    • secondaryAddress
    • county
    • country
    • countryCode
    • state
    • stateAbbr
    • latitude
    • longitude
  • commerce
    • color
    • department
    • productName
    • price
    • productAdjective
    • productMaterial
    • product
  • company
    • suffixes
    • companyName
    • companySuffix
    • catchPhrase
    • bs
    • catchPhraseAdjective
    • catchPhraseDescriptor
    • catchPhraseNoun
    • bsAdjective
    • bsBuzz
    • bsNoun
  • database
    • column
    • type
    • collation
    • engine
  • date
    • past
    • future
    • between
    • recent
    • month
    • weekday
  • fake
  • finance
    • account
    • accountName
    • mask
    • amount
    • transactionType
    • currencyCode
    • currencyName
    • currencySymbol
    • bitcoinAddress
    • iban
    • bic
  • hacker
    • abbreviation
    • adjective
    • noun
    • verb
    • ingverb
    • phrase
  • helpers
    • randomize
    • slugify
    • replaceSymbolWithNumber
    • replaceSymbols
    • shuffle
    • mustache
    • createCard
    • contextualCard
    • userCard
    • createTransaction
  • image
    • image
    • avatar
    • imageUrl
    • abstract
    • animals
    • business
    • cats
    • city
    • food
    • nightlife
    • fashion
    • people
    • nature
    • sports
    • technics
    • transport
    • dataUri
  • internet
    • avatar
    • email
    • exampleEmail
    • userName
    • protocol
    • url
    • domainName
    • domainSuffix
    • domainWord
    • ip
    • ipv6
    • userAgent
    • color
    • mac
    • password
  • lorem
    • word
    • words
    • sentence
    • slug
    • sentences
    • paragraph
    • paragraphs
    • text
    • lines
  • name
    • firstName
    • lastName
    • findName
    • jobTitle
    • prefix
    • suffix
    • title
    • jobDescriptor
    • jobArea
    • jobType
  • phone
    • phoneNumber
    • phoneNumberFormat
    • phoneFormats
  • random
    • number
    • arrayElement
    • objectElement
    • uuid
    • boolean
    • word
    • words
    • image
    • locale
    • alphaNumeric
  • system
    • fileName
    • commonFileName
    • mimeType
    • commonFileType
    • commonFileExt
    • fileType
    • fileExt
    • directoryPath
    • filePath
    • semver

Localization

can take a locale as an argument, to return localized data. If no localized provider is found, the factory falls back to the default en_US locale.

from faker import Faker
fake = Faker('it_IT')
for _ in range(10):
    print(fake.name())

# 'Elda Palumbo'
# 'Pacifico Giordano'
# 'Sig. Avide Guerra'
# 'Yago Amato'
# 'Eustachio Messina'
# 'Dott. Violante Lombardo'
# 'Sig. Alighieri Monti'
# 'Costanzo Costa'
# 'Nazzareno Barbieri'
# 'Max Coppola'

You can check available Faker locales in the source code, under the providers package. The localization of Faker is an ongoing process, for which we need your help. Please don’t hesitate to create a localized provider for your own locale and submit a Pull Request (PR).

Included localized providers:

Faker Internals: Understanding Providers

A alone can’t do much generation. It needs objects to delegate the data generation to them. actually creates a bundled with the default providers. Here is what happens under the hood:

<?php
$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Person($faker));
$faker->addProvider(new Faker\Provider\en_US\Address($faker));
$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker));
$faker->addProvider(new Faker\Provider\en_US\Company($faker));
$faker->addProvider(new Faker\Provider\Lorem($faker));
$faker->addProvider(new Faker\Provider\Internet($faker));

Whenever you try to access a property on the object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling triggers a call to . And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override.

That means that you can easily add your own providers to a instance. A provider is usually a class extending . This parent class allows you to use methods like or ; it also gives you access to formatters of other providers, through the protected property. The new formatters are the public methods of the provider class.

Here is an example provider for populating Book data:

<?php

namespace Faker\Provider;

class Book extends \Faker\Provider\Base
{
  public function title($nbWords = 5)
  {
    $sentence = $this->generator->sentence($nbWords);
    return substr($sentence, , strlen($sentence) - 1);
  }

  public function ISBN()
  {
    return $this->generator->ean13();
  }
}

To register this provider, just add a new instance of to an existing generator:

<?php
$faker->addProvider(new \Faker\Provider\Book($faker));

Now you can use the two new formatters like any other Faker formatter:

<?php
$book = new Book();
$book->setTitle($faker->title);
$book->setISBN($faker->ISBN);
$book->setSummary($faker->text);
$book->setPrice($faker->randomNumber(2));

Tip: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator.

Maintainer

faker.js was inspired by and has used data definitions from:

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Populating Entities Using an ORM or an ODM

To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the method.

Here is an example showing how to populate 5 and 10 objects:

<?php
$generator = \Faker\Factory::create();
$populator = new Faker\ORM\Propel\Populator($generator);
$populator->addEntity('Author', 5);
$populator->addEntity('Book', 10);
$insertedPKs = $populator->execute();

The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named using the formatter, and a column with a type using the formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to :

<?php
$populator->addEntity('Book', 5, array(
  'ISBN' => function() use ($generator) { return $generator->ean13(); }
));

In this example, Faker will guess a formatter for all columns except , for which the given anonymous function will be used.


Tip: To ignore some columns, specify for the column names in the third argument of . This is usually necessary for columns added by a behavior:

<?php
$populator->addEntity('Book', 5, array(
  'CreatedAt' => null,
  'UpdatedAt' => null,
));

Of course, Faker does not populate autoincremented primary keys. In addition, returns the list of inserted PKs, indexed by class:

<?php
print_r($insertedPKs);
// array(
//   'Author' => (34, 35, 36, 37, 38),
//   'Book'   => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475)
// )

In the previous example, the and models share a relationship. Since entities are populated first, Faker is smart enough to relate the populated entities to one of the populated entities.

Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the method:

<?php
$populator->addEntity('Book', 5, array(), array(
  function($book) { $book->publish(); },
));

Basic Usage

Install with pip:

pip install Faker

Use faker.Faker() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.

from faker import Faker
fake = Faker()

fake.name()
# 'Lucy Cechtelar'

fake.address()
# '426 Jordy Lodge
#  Cartwrightshire, SC 88120-6700'

fake.text()
# 'Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
#  beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
#  amet quidem. Iusto deleniti cum autem ad quia aperiam.
#  A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui
#  quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur
#  voluptatem sit aliquam. Dolores voluptatum est.
#  Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est.
#  Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati.
#  Et sint et. Ut ducimus quod nemo ab voluptatum.'

Each call to method fake.name() yields a different (random) result. This is because faker forwards faker.Generator.method_name() calls to faker.Generator.format(method_name).

Language specific formatters

<?php

// Generates a random SIREN number
echo $faker->siren; // 082 250 104

// Generates a random SIRET number
echo $faker->siret; // 347 355 708 00224

// Generates a random SIRET number (controlling the number of sequential digits)
echo $faker->siret(3); // 438 472 611 01513
<?php

// Generates a random department name
echo $faker->departmentName; // "Haut-Rhin"

// Generates a random department number
echo $faker->departmentNumber; // "2B"

// Generates a random department info (department number => department name)
$faker->department; // array('18' => 'Cher');

// Generates a random region
echo $faker->region; // "Saint-Pierre-et-Miquelon"
<?php

// Generates a random CPR number
echo $faker->cpr; // "051280-2387"
<?php

// Generates a random 'kommune' name
echo $faker->kommune; // "Frederiksberg"

// Generates a random region name
echo $faker->region; // "Region Sjælland"
<?php

// Generates a random CVR number
echo $faker->cvr; // "32458723"

// Generates a random P number
echo $faker->p; // "5398237590"

API

faker.js contains a super useful generator method for combining faker API methods using a mustache string format.

Example:

console.log(faker.fake("{{name.lastName}}, {{name.firstName}} {{name.suffix}}"));

This will interpolate the format string with the value of methods , , and

  • address
    • zipCode
    • city
    • cityPrefix
    • citySuffix
    • streetName
    • streetAddress
    • streetSuffix
    • streetPrefix
    • secondaryAddress
    • county
    • country
    • countryCode
    • state
    • stateAbbr
    • latitude
    • longitude
  • commerce
    • color
    • department
    • productName
    • price
    • productAdjective
    • productMaterial
    • product
  • company
    • suffixes
    • companyName
    • companySuffix
    • catchPhrase
    • bs
    • catchPhraseAdjective
    • catchPhraseDescriptor
    • catchPhraseNoun
    • bsAdjective
    • bsBuzz
    • bsNoun
  • database
    • column
    • type
    • collation
    • engine
  • date
    • past
    • future
    • between
    • recent
    • soon
    • month
    • weekday
  • fake
  • finance
    • account
    • accountName
    • mask
    • amount
    • transactionType
    • currencyCode
    • currencyName
    • currencySymbol
    • bitcoinAddress
    • ethereumAddress
    • iban
    • bic
  • hacker
    • abbreviation
    • adjective
    • noun
    • verb
    • ingverb
    • phrase
  • helpers
    • randomize
    • slugify
    • replaceSymbolWithNumber
    • replaceSymbols
    • shuffle
    • mustache
    • createCard
    • contextualCard
    • userCard
    • createTransaction
  • image
    • image
    • avatar
    • imageUrl
    • abstract
    • animals
    • business
    • cats
    • city
    • food
    • nightlife
    • fashion
    • people
    • nature
    • sports
    • technics
    • transport
    • dataUri
  • internet
    • avatar
    • email
    • exampleEmail
    • userName
    • protocol
    • url
    • domainName
    • domainSuffix
    • domainWord
    • ip
    • ipv6
    • userAgent
    • color
    • mac
    • password
  • lorem
    • word
    • words
    • sentence
    • slug
    • sentences
    • paragraph
    • paragraphs
    • text
    • lines
  • name
    • firstName
    • lastName
    • findName
    • jobTitle
    • prefix
    • suffix
    • title
    • jobDescriptor
    • jobArea
    • jobType
  • phone
    • phoneNumber
    • phoneNumberFormat
    • phoneFormats
  • random
    • number
    • float
    • arrayElement
    • objectElement
    • uuid
    • boolean
    • word
    • words
    • image
    • locale
    • alphaNumeric
    • hexaDecimal
  • system
    • fileName
    • commonFileName
    • mimeType
    • commonFileType
    • commonFileExt
    • fileType
    • fileExt
    • directoryPath
    • filePath
    • semver

Maintainer

faker.js was inspired by and has used data definitions from:

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Populating Entities Using an ORM or an ODM

To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the method.

Here is an example showing how to populate 5 and 10 objects:

<?php
$generator = \Faker\Factory::create();
$populator = new Faker\ORM\Propel\Populator($generator);
$populator->addEntity('Author', 5);
$populator->addEntity('Book', 10);
$insertedPKs = $populator->execute();

The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named using the formatter, and a column with a type using the formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom clusure to be used for populating a particular column, using the third argument to :

<?php
$populator->addEntity('Book', 5, array(
  'ISBN' => function() use ($generator) { return $generator->randomNumber(13); }
));

In this example, Faker will guess a formatter for all columns except , for which the given anonymous function will be used.

Tip: To ignore some columns, specify for the column names in the third argument of . This is usually necessary for columns added by a behavior:

<?php
$populator->addEntity('Book', 5, array(
  'CreatedAt' => null,
  'UpdatedAt' => null,
));

Of course, Faker does not populate autoincremented primary keys. In addition, returns the list of inserted PKs, indexed by class:

<?php
print_r($insertedPKs);
// array(
//   'Author' => (34, 35, 36, 37, 38),
//   'Book'   => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475)
// )

In the previous example, the and models share a relationship. Since entities are populated first, Faker is smart enough to relate the populated entities to one of the populated entities.

Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the method:

<?php
$populator->addEntity('Book', 5, array(), array(
  function($book) { $book->publish(); },
));

Seeding the Generator

When using Faker for unit testing, you will often want to generate the same data set. For convenience, the generator also provide a method, which seeds the shared random number generator. Calling the same methods with the same version of faker and seed produces the same results.

from faker import Faker
fake = Faker()
fake.seed(4321)

print(fake.name())
# 'Margaret Boehm'

Each generator can also be switched to its own instance of , separate to the shared one, by using the method, which acts the same way. For example:

from faker import Faker
fake = Faker()
fake.seed_instance(4321)

print(fake.name())
# 'Margaret Boehm'

Please note that as we keep updating datasets, results are not guaranteed to be consistent across patch versions. If you hardcode results in your test, make sure you pinned the version of down to the patch number.


С этим читают