Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data
Good tests need good data: realistic enough to find bugs, repeatable enough to debug, and never copied from real customers. We used the Python Faker library to generate, seed, localise and measure test data, and found where it falls short.
- Test data generation creates realistic fake data, so tests do not depend on copies of real customer records.
- Seed the generator so the same test produces the same data every time.
- Faker produces plausible, typical values; you must add edge cases such as empty strings, apostrophes and very long text yourself.
- Faker is not cryptographically random: never use it for passwords, tokens or anything security-related.
A tester needs 500 customers with orders to check a reporting screen. Copying them from production is quick, but it puts real names, emails and phone numbers into test environments, logs and screenshots, which is a privacy and legal risk. Typing them by hand is slow and produces “Test User 1” to “Test User 500”, which hides bugs. Test data generation with a library like Faker sits in between: realistic, fast and fake.
We ran every example with Faker 40.52 on Python 3.13. The values below are from our seeded run, so they are reproducible with the same version.
Why test data matters
- Realism finds bugs: long names, accented characters and varied formats break code that “Test User” never touches.
- Repeatability enables debugging: a failure you cannot reproduce is a failure you cannot fix.
- Isolation keeps tests reliable: tests that share and change the same records become flaky.
- Privacy is non-negotiable: real personal data in test systems is often a breach of law and policy.
Ways to get test data
| Approach | Pros | Cons |
|---|---|---|
| Hand-written fixtures | Exact, readable, great for edge cases | Slow to create in volume |
| Generated (Faker and similar) | Fast, realistic, no personal data | Misses business rules and rare edge cases |
| Masked production copy | Real distributions and relationships | Masking must be thorough; still sensitive |
| Synthetic data platforms | Preserve statistics and relationships at scale | Cost and setup |
Most teams combine them: small hand-written fixtures for exact checks, generated data for volume, and carefully masked data only where realistic distributions are essential.
Getting started with Faker
pip install faker
from faker import Faker
fake = Faker("en_IN")
fake.name(), fake.email(), fake.city(), fake.phone_number()
Faker has providers for names, addresses, companies, internet data, dates, numbers, text, finance and more, plus the ability to add your own. It is pure Python with no system dependencies.
Seeding for repeatable data
Faker.seed(42)
# Aryan Maharaj | udantdewan@example.net | Bongaigaon | +9196001xxxxx
# Oni Kannan | zmall@example.org | Bhusawal | 042351xxxxx
# Caleb Sharaf | radhakrishnanfarhan@example.net | Tadipatri | 093103xxxxx
# (phone numbers shortened here: generated numbers can match real ones)
Faker.seed(42); fake2 = Faker("en_IN")
fake2.name() # Aryan Maharaj
With the same seed, a new generator produced the same first name. Seed every test or test session, and log the seed, so a failure can be replayed exactly. Note that values can change between Faker versions, so pin the version in your requirements if tests compare exact generated values. Better still, write tests that do not depend on specific fake values at all.
Notice too that Faker used example.net and example.org email domains, which are reserved for documentation and testing, so a test can never email a real person by accident.
Locales
en_US: Ryan Gallagher | Davidmouth
de_DE: Karsten Wieloch-Bolnbach | Cloppenburg
ja_JP: 木村 陽一 | 八丈島八丈町
hi_IN: मोहना रोद्रिगुएस | अनन्तपुर
Locales change names, addresses and formats, and some switch scripts entirely. A German double-barrelled surname, Japanese characters and Devanagari text are exactly the inputs that expose bugs in field lengths, sorting, search, PDFs and fonts. If your product serves several regions, generate data for each.
Unique values
emails = [f.unique.email() for _ in range(1000)]
len(set(emails)) # 1000
small.unique.random_int(1, 5) # called 6 times
# UniquenessException
Plain Faker calls can repeat values, which breaks tests on columns with UNIQUE constraints. The .unique proxy guarantees no repeats; in our run, 1,000 emails were all distinct. When the pool of possible values runs out, as when asking for six unique numbers between 1 and 5, it raises UniquenessException instead of looping forever. Call fake.unique.clear() between tests.
Building domain records
Faker generates fields; your code must respect business rules. A small factory function combines them:
def make_order(f):
qty = f.random_int(1, 5)
price = f.pyint(10, 2000)
return {"order_id": f.uuid4(), "customer": f.name(), "qty": qty,
"unit_price": price, "total": qty * price,
"status": f.random_element(["paid", "pending", "refunded"]),
"placed_at": f.date_time_between("-30d", "now").isoformat(timespec="seconds")}
# {"order_id": "0c5c7fd0-...", "customer": "Girindra Pau", "qty": 3,
# "unit_price": 1951, "total": 5853, "status": "refunded", "placed_at": "2026-10-14T18:01:02"}
Note that total is calculated, not random, so the record is internally consistent. Random independent fields produce impossible data, such as a refund date before the order date, which wastes time chasing bugs that cannot happen. Libraries like factory_boy, and model-based tools such as Hypothesis strategies built from dataclasses, help keep these rules in one place.
Edge cases Faker will not give you
Faker produces typical values. Bugs live in atypical ones, so keep a hand-written list and mix it in:
edge_names = ["", " ", "O'Brien", "Zoë", "李小龙", "a" * 255,
"Robert'); DROP TABLE students;--", " padded "]
Empty and whitespace-only values, apostrophes, accents, non-Latin scripts, maximum lengths and strings that look like code catch validation, escaping and display bugs. Boundary value analysis tells you which numeric limits to add, and property-based testing generates awkward inputs automatically.
Tip: Faker uses Python’s standard random module, which is predictable by design, especially when seeded. Never use it to generate real passwords, API keys, tokens or one-time codes. Use the secrets module for anything security-related.
Masking production data
def mask_email(e):
h = hashlib.sha256(e.encode()).hexdigest()[:8]
return f"user_{h}@example.test"
mask_email("asha.rao@gmail.com") # user_fbb1af74@example.test (same input, same output)
Sometimes realistic distributions matter, for example for performance tests or analytics. Then teams copy production and mask it. Consistent masking, where the same input always maps to the same fake value, keeps joins between tables working. But masking is harder than it looks: free-text notes, addresses in comments, and combinations of harmless fields can still identify people. A simple hash of an email can also be reversed by guessing common addresses unless a secret key is added. Involve your security or privacy team, and prefer generated data whenever it is good enough.
Speed and volume
10,000 name + email rows: 1.79s
Faker is fine for thousands of records but slows down at millions. For large performance datasets, generate once and reuse the file, use faster libraries such as Mimesis, generate inside the database with SQL, or bulk-load with the database’s import tools. Load testing guidance is in our load vs stress testing guide.
Using it in tests
# conftest.py (illustration, not run for this article)
import pytest
from faker import Faker
@pytest.fixture
def fake():
f = Faker("en_IN")
f.seed_instance(1234)
return f
def test_signup(fake):
user = {"name": fake.name(), "email": fake.unique.email()}
...
A seeded fixture gives every test predictable data, and seed_instance keeps tests from affecting each other through a shared global seed. pytest also ships a Faker plugin with Faker itself, providing a faker fixture. See our pytest fixtures guide for fixture scopes and cleanup.
Best practices
- Never use real personal data in test environments without approved masking.
- Seed generators and log the seed for every run.
- Generate the minimum data each test needs, created by the test itself.
- Keep business rules in factories so records are always valid.
- Mix in a maintained list of edge cases.
- Clean up generated data, or run each test in a rolled-back transaction.
Test data for each test level
| Test level | Good data source | Why |
|---|---|---|
| Unit tests | Hand-written values plus a few edge cases | Exact, readable, fast |
| Integration and API tests | Seeded factories using Faker | Realistic and repeatable, created per test |
| End-to-end tests | A small, known baseline dataset plus data each test creates | Stable starting point for user journeys |
| Performance tests | Large generated or masked datasets | Realistic volume and distribution |
| Exploratory testing | Varied, messy generated data across locales | Surfaces unexpected behaviour |
Matching the data source to the test level keeps fast tests simple and slow tests realistic. Lower levels need precision; higher levels need variety and volume. The test pyramid explains how these levels fit together.
Whatever the level, make each test responsible for the data it depends on. A test that quietly relies on a record created by another test, or left over from last week, will eventually fail for reasons that have nothing to do with the code under test.
Final thoughts
Faker turns test data from a chore into a few lines of code: realistic names, emails and addresses in many languages, repeatable with a seed and safe because nothing is real. It produces typical data, though, so add your own edge cases and business rules on top, keep it away from security values, and prefer generated data over copies of production wherever you can.
Frequently asked questions
What is test data generation?
Creating artificial but realistic data for testing, so tests have the variety and volume they need without using real customer information.
How do I get the same Faker data every run?
Seed it with Faker.seed(n) or fake.seed_instance(n). With the same seed and version, it produces the same values.
How do I avoid duplicate values with Faker?
Use the unique proxy, as in fake.unique.email(). It raises UniquenessException when no new values remain, and you can reset it with fake.unique.clear().
Is Faker safe for passwords or tokens?
No. Faker uses predictable pseudo-random numbers. Use Python’s secrets module for any security-sensitive value.
Should I use production data for testing?
Avoid it where possible. If realistic distributions are essential, use properly masked copies approved by your privacy or security team.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.