#263: Generate Realistic Test Data With Faker
If you have ever worked on a project that needed realistic test data, you know how tedious it can be to create it manually. Hardcoding names, addresses, or even phone numbers into your test suite not only clutters your code but also makes it inflexible. Thankfully, the Python Faker library comes to the rescue.
What Is Faker?
Faker is a Python package that generates fake data for you. It is highly configurable, simple to use, and perfect for creating a variety of placeholder data for testing or development environments. It can generate names, addresses, dates, phone numbers, emails, and even paragraphs of lorem ipsum text. Best of all, it supports multiple locales, making it easy to simulate data from different countries.
Let us get practical and take our first steps with Faker.
Installing Faker
We can install Faker with this command:
Once installed, we are ready to generate as much fake data as we need.
Creating Fake Data
We can create a Faker object and call its various methods to explore its data generator:
This will output something like this:
|
Each time we run this code it will generate new random data.
Localisation
We can pass a locale to Faker to get a localised flavour of our generated data:
Supported locales are listed in the Faker documentation. Should you use a locale that has no matching provider, Faker will fall back to en_US.
Seeding for consistency
Sometimes, especially in testing, we want our fake data to be consistent. We can achieve this by seeding the random generator:
Advanced Use Cases
Faker can generate more than just names and addresses. Here are some advanced use cases:
-
random text:
-
credit card numbers:
-
Email:
print(fake.ascii_company_email()) # [email protected] print(fake.ascii_free_email()) # [email protected] print(fake.ascii_safe_email()) # [email protected] -
ISBN:
-
Coordinates:
We can generate these values with the standard providers. Read the documentation to see what else comes with Faker.
Next
The Faker library is a powerful tool for generating dummy data fast and without much effort. Whether we need fake user profiles for testing our web app or placeholders for populating our database during development, Faker has us covered. But what happens if we need more specific values? Next week we create our own custom provider to get the exact values we need.