xtest

Software Testing

Test Data Management

This course teaches the discipline of planning, creating, protecting, and cleaning up the data that powers software tests. It covers the core concepts of test data management, practical techniques for generating realistic data, methods for masking and anonymizing sensitive information, and patterns for seeding and resetting data in automated test pipelines. Learners work through concrete examples using widely available tools such as Faker, SQL scripts, and shell scripts calling REST APIs, so the techniques transfer directly to real projects. The course also addresses the lifecycle of test data across environments, from local development through staging and production-like test environments, and the governance practices that keep data compliant with privacy expectations. By the end, learners will be able to design a test data strategy for a project of any size, choose the right kind of data for each kind of test, and build repeatable, isolated data setups that make automated tests reliable rather than flaky.

Intermediate · By the Xtest team · About 39 minutes to read

Introduction

Every test, whether run by a person or an automated script, needs data to act on: a user to log in as, an order to cancel, a record to search for. When that data is missing, stale, duplicated, or leaked from production, tests become unreliable, slow to prepare, or risky to run at all. Test Data Management (TDM) is the set of practices that make sure the right data is available, in the right shape, at the right time, for every test, without exposing anything that shouldn't leave production. This course starts from the basics: what test data is, the different categories it falls into, and the problems teams run into when they manage it carelessly. It then moves into practical generation techniques, covering how to create realistic but fake data at scale rather than copying real records. A full section is devoted to protecting sensitive data, since many teams still test against real customer information without masking it first, which is one of the most common and most serious mistakes in this field. The course also looks at how data gets seeded and cleaned up automatically as part of a test run, so that tests don't interfere with each other or leave debris behind. Finally, it covers the lifecycle and governance side: deciding who owns test data, how long it lives, and how it moves between environments. The course is hands-on throughout, with real tool examples in Python, SQL and shell scripts, plus exercises and a quiz to check understanding.

Foundations of Test Data Management

What This Section Covers

Before writing a single generator script or masking rule, a tester needs a clear mental model of what test data actually is and why managing it deliberately matters. This section lays that foundation.

Why Test Data Management Is Its Own Discipline

It's tempting to treat test data as an afterthought: just point the tests at a copy of the production database and move on. That approach works for a small project for a short while, and then starts causing real damage. A copy of production may contain real names, emails, and payment details, which creates privacy and compliance exposure the moment anyone outside the production team can see it. Production data also changes shape over time in ways tests don't expect, so a test that passed last month fails today not because the code broke but because the data underneath it moved. And when many tests share one pool of data, one test's changes become another test's unexpected starting condition, producing failures that have nothing to do with the feature under test.

Treating test data management as a deliberate practice means making conscious decisions: what data does this test actually need, where does it come from, who else is going to use it at the same time, and what happens to it when the test ends. Those four questions recur throughout this entire course.

The Shape of Good Test Data

Good test data has a few consistent properties regardless of the tool or project. It is realistic enough to exercise the code paths that matter, meaning it respects the formats, ranges and relationships the application expects, such as valid postal codes, correctly structured phone numbers, and foreign keys that point at records that really exist. It is isolated, so that one test run does not corrupt the data another run depends on. It is disposable, so that a test can be run a hundred times without manually resetting anything by hand. And it is minimal, meaning a test carries only the data it needs to prove its point rather than relying on a sprawling, shared dataset where nobody remembers which parts matter.

A Mental Model: Four Kinds of Test Data

Throughout this course, test data is grouped into four practical categories: static reference data that rarely changes (country lists, product categories), dynamic data created fresh for a single test run (a new user, a new order), synthetic data generated to resemble real data without being real, and masked data taken from a real source but altered so it can no longer identify a real person. Each kind has its own place, and mixing them up is one of the most common sources of fragile test suites, which later sections address directly.

What Is Test Data Management

Test Data Management is the ongoing practice of identifying what data a test suite needs, creating or sourcing that data, keeping it available and correct across every environment a test might run in, and disposing of it cleanly afterward. It sits alongside test case design and test automation as a core testing discipline, but it is frequently under-invested in because it doesn't produce a visible artifact like a test script does.

In practice, TDM touches several concerns at once. There's the functional concern: does this record have the fields and relationships the feature under test actually reads? There's the volume concern: does a performance-style check need thousands of rows while a login test needs exactly one user? There's the privacy concern: can this data leave the production system at all, and if so, in what altered form? And there's the operational concern: who refreshes this data, how often, and what breaks if it goes stale?

A team that handles TDM well usually has answers to all four written down somewhere, even informally: a short document or a convention that says new features get a seed script, sensitive fields always get masked before leaving production, and every automated suite cleans up what it created. A team that handles it poorly usually discovers the gaps only when a test fails for a reason nobody can explain, traces it back hours later to a data problem, and repeats the same investigation a few weeks after that.

Types of Test Data

Static reference data is the data that defines the rules of the application rather than its day-to-day activity: currency codes, tax rates, shipping zones, role permissions. It changes rarely, so it is usually loaded once per environment and left alone, with tests treating it as a known constant rather than something they create or destroy.

Dynamic data is created specifically for a test run and is expected to disappear afterward: a freshly registered account, a cart with three items added to it, a support ticket opened and then closed. This is the data category most test automation actually touches, and it benefits the most from being generated programmatically rather than typed in by hand, so that every run starts from a known, isolated state.

Synthetic data is data invented to resemble real-world data in shape and distribution without being copied from anywhere real: names that look like names, addresses that look like addresses, order histories that look plausible. It is the safest category from a privacy standpoint because it never touched a real person, and tools like Faker (covered later in this course) exist specifically to produce it at scale.

Masked data starts life as real production data and is then deliberately altered, such as replacing real names with random ones and real emails with disposable ones, while keeping the overall structure and volume intact. It is useful when a bug can only be reproduced against data with production's real messiness and scale, but it requires discipline: masking has to happen before the data reaches anyone who shouldn't see the original, not after.

Common Challenges in Test Data Management

The most frequent challenge is data drift: tests are written against one shape of data, and the application or database schema changes underneath them without the test data being updated to match, so tests fail for reasons unrelated to the feature being tested. The fix is treating test data setup as part of the codebase, versioned and reviewed the same way application code is, so a schema change and its corresponding data fixture change land in the same commit.

A second challenge is shared mutable state: multiple tests, or multiple people, reading and writing the same rows at the same time. A test that expects exactly one pending order will fail intermittently if another test or another person just created a second one. The fix is isolation, giving each test run its own data, often by generating unique identifiers (a timestamp or random suffix in an email address, for example) so no two runs can collide.

A third challenge is privacy exposure: real customer data ending up in a staging environment that far more people can access than production, often with weaker controls. This is addressed by masking or by using synthetic data instead of a raw copy, and by treating any environment that holds real data, however old, with the same access controls as production.

A fourth challenge is cleanup debt: data created by a test run accumulating indefinitely because nothing removes it, until the environment is cluttered with thousands of abandoned orders and accounts and nobody wants to touch it for fear of breaking something. The fix is to pair every piece of setup with a corresponding teardown, run automatically whether the test passed or failed.

from faker import Faker
import json

fake = Faker()

def generate_test_user():
    return {
        "first_name": fake.first_name(),
        "last_name": fake.last_name(),
        "email": fake.unique.email(),
        "phone": fake.phone_number(),
        "address": {
            "street": fake.street_address(),
            "city": fake.city(),
            "postal_code": fake.postcode(),
            "country": fake.country_code()
        },
        "signup_date": fake.date_between(start_date="-2y", end_date="today").isoformat()
    }

# Generate a batch of 10 synthetic users for a test run
users = [generate_test_user() for _ in range(10)]
print(json.dumps(users, indent=2))

Uses the Python Faker library to generate a batch of realistic but entirely synthetic user records, suitable for seeding a test environment without any risk of exposing real personal data.

#!/bin/bash
# Seed a test account before running a suite, and remove it afterward
API_BASE="https://staging.example.com/api/v1"
TOKEN="test-service-token"

# Create a uniquely-named test user so parallel runs never collide
SUFFIX=$(date +%s)
EMAIL="qa-user-${SUFFIX}@example.test"

USER_ID=$(curl -s -X POST "$API_BASE/users" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"email\": \"$EMAIL\", \"plan\": \"trial\"}" | jq -r '.id')

echo "Created test user $USER_ID with email $EMAIL"

# ... run the actual test suite here, pointing it at $USER_ID ...

# Clean up afterward regardless of pass or fail
curl -s -X DELETE "$API_BASE/users/$USER_ID" \
  -H "Authorization: Bearer $TOKEN"

echo "Deleted test user $USER_ID"

A shell script pattern using curl and jq that creates a uniquely identified test user through a REST API before a suite runs, and deletes it afterward, demonstrating isolation and cleanup in a single, repeatable script.

Tips

  • Give every piece of dynamic test data a unique marker, such as a timestamp or random suffix in an email or username, so parallel test runs never collide with each other.
  • Keep test data setup scripts in version control alongside the application code, so a schema change and its matching fixture update are reviewed and merged together.
  • Default to synthetic data for anything that doesn't specifically require production's real messiness; reach for masked production data only when a bug genuinely cannot be reproduced otherwise.
  • Write the cleanup step before the setup step is even finished, and make sure it runs whether the test passed or failed, not just on success.

Common pitfalls

  • Pointing a whole test suite at one shared database without any isolation between runs; the fix is generating unique identifiers per run and scoping tests to the records they created themselves.
  • Copying a production database into staging as-is for convenience; the fix is masking identifying fields before the copy is usable, or replacing the copy with synthetic data generated to the same shape.
  • Letting test data accumulate indefinitely because nobody owns cleanup; the fix is pairing every setup step with a teardown step in the same script or test lifecycle hook.

Generating and Sourcing Test Data

Good test data rarely falls out of a simple faker.name() call. Real applications enforce business rules: tax IDs follow a checksum algorithm, ages must fall within an eligibility window, inventory counts must reconcile with order lines. Generating data that satisfies these constraints, while still being varied enough to catch edge cases, is a distinct skill from basic fixture writing.

This section covers three escalating techniques. Rule-based generation builds domain-aware generators that respect validation logic instead of producing data a form would reject outright. Bulk generation produces hundreds or thousands of records to exercise pagination, performance boundaries, and rare combinations that only emerge at volume. Finally, we compare hand-written fixtures, programmatic generators, and database seed scripts as three points on a spectrum of control versus effort, so you can choose the right one for a given test rather than defaulting to whichever is fastest to write.

A recurring challenge across all three is referential consistency: a generated customer needs orders that reference a real customer id, and those orders need line items that reference real product ids with stock actually available. Breaking that chain produces tests that pass for the wrong reason, or fail with confusing foreign-key errors unrelated to the behavior under test. The examples below show generating a customer and its orders together, in Python and in SQL, so the relationship is built at creation time instead of patched together afterward.

Rule-Based Generation for Business Constraints

Random data generators are built for shape, not for meaning. A library will happily hand you a string that looks like a tax ID but fails a checksum, or a birthdate that makes a customer three years old when the business rule requires 18+. Rule-based generation wraps a random source with the validation logic the application itself enforces, so every record it produces is guaranteed to pass the same checks a real user's input would face.

In practice this means writing small generator functions per constraint rather than one generic 'make a person' function: one that produces a checksum-valid tax ID by generating the digits and then computing the check digit the same way the backend does; one that produces a birthdate within a configurable age range by working backward from today; one that produces an order whose quantity never exceeds the stock figure on the product record it references.

These generators pay for themselves on any field with a server-side validator, because invalid-looking test data either gets silently rejected (producing false test failures that have nothing to do with the feature being tested) or, worse, gets accepted by a buggy validator and masks a real defect. Treat the generator function as the single place that encodes 'what a valid value looks like' so that every test, fixture, and seed script that needs one calls the same function instead of re-deriving the rule and inevitably drifting out of sync with the real validation.

Bulk Generation and the Fixtures-vs-Generators-vs-Seeds Tradeoff

Some tests need one carefully hand-crafted record; others need a thousand. Boundary and performance scenarios, such as confirming a list view paginates correctly at exactly 100 rows or that a report still renders with 10,000 line items, require bulk generation: looping a generator function with varied-but-valid inputs rather than writing each record by hand.

Three approaches typically coexist in a test suite, each suited to a different situation. Hand-written fixtures (a literal JSON or object literal with two or three records) are the clearest to read and the easiest to reason about, and are the right choice for a small number of tests where the exact values matter to the assertion. Programmatic generators (functions called at test setup, as in the example below) scale to hundreds of records, support randomized or bulk generation, and keep the generation logic in one reviewable place, at the cost of being a layer removed from the literal data a test exercises. Database seed scripts (SQL run directly against a test database before a suite starts) are fastest for large volumes and for setting up data that several tests or several services share, but they live outside the test code itself and can quietly drift out of date with the schema.

A practical rule of thumb: use fixtures for small, assertion-critical data; generators for anything needing volume, randomization, or constraint-satisfying values; and seed scripts when the data needs to exist before the application or several test runs even start.

from faker import Faker
import random

fake = Faker()

def make_customer():
    return {
        "id": fake.uuid4(),
        "name": fake.name(),
        "email": fake.email(),
    }

def make_orders(customer, count=3):
    orders = []
    for _ in range(count):
        orders.append({
            "id": fake.uuid4(),
            "customer_id": customer["id"],  # keeps the foreign key consistent
            "total": round(random.uniform(10, 500), 2),
            "status": random.choice(["pending", "shipped", "delivered"]),
        })
    return orders

customer = make_customer()
orders = make_orders(customer, count=3)

print(customer)
for o in orders:
    print(o)

Generates a customer record first, then generates a batch of orders that each carry that customer's real id as a foreign key, so the records stay referentially consistent instead of being generated independently and mismatched.

-- Seed one customer and three related orders in a single consistent batch
INSERT INTO customers (id, name, email)
VALUES ('c-1001', 'Jordan Blake', 'jordan.blake@example.com');

INSERT INTO orders (id, customer_id, total, status)
VALUES
  ('o-2001', 'c-1001', 149.99, 'pending'),
  ('o-2002', 'c-1001', 29.50,  'shipped'),
  ('o-2003', 'c-1001', 310.00, 'delivered');

A seed script that inserts a customer and its orders in one transaction-friendly batch, useful for setting up a known baseline before a test suite runs against a shared test database.

Tips

  • Write one generator function per business rule (tax ID, age range, stock limit) so the rule lives in exactly one place and every test calls the same logic.
  • When generating related records, always derive the foreign key from the parent record you just created rather than generating it independently, to avoid silent referential mismatches.
  • Use bulk generation specifically for boundary counts (exactly at a page size limit, one over it, one under it) rather than an arbitrary large number, so the volume test is actually testing the boundary.

Common pitfalls

  • Generating child records (orders, line items) with a fresh random id instead of the parent's real id, which produces data that looks plausible but silently fails to exercise the relationship the test is supposed to cover.
  • Letting a database seed script drift out of sync with schema changes because it lives outside the test code and isn't reviewed alongside migrations; treat seed scripts as code that needs the same review and upkeep as the tests that depend on them.

Protecting Sensitive Data: Masking, Anonymization and Synthetic Data

Production data is convenient for testing because it is realistic, but copying it into a test environment as-is is one of the fastest ways to create a compliance incident. Names, addresses, payment details, national ID numbers and health records carried over from production expose your organization to the same breach risk in a lower-security environment, often with weaker access controls and more people looking at it. This section covers the practical techniques for neutralizing that risk: masking (replacing real values with realistic-looking fakes while keeping the data's shape), anonymization (removing the link back to a real person so thoroughly that it cannot be reversed), and synthetic data generation (never touching production data at all, and building test records from scratch).

The three techniques are not interchangeable. Masking is reversible in principle if the mapping is kept, and is usually enough for internal functional testing. True anonymization is a stronger, often irreversible transformation required when regulation (such as data protection law covering personal data) or internal policy says production data must never be reconstructable, even by the team that masked it. Synthetic data sidesteps the question entirely by never deriving from real records, which is why it should be your default whenever a test's goal does not specifically require production-shaped edge cases.

This section also works through a masking script applied to an exported dataset, showing field substitution (swapping a real value for a fake one from a matching category), shuffling (reassigning real values between rows so the distribution survives but the linkage does not), and tokenization (replacing a value with an opaque token kept in a separate, access-controlled vault). You will see where each is appropriate, and where a test environment's seed and clean-up endpoints fit so that masked or synthetic data is created and torn down automatically rather than hand-maintained.

Masking Techniques: Substitution, Shuffling and Tokenization

Field substitution replaces a sensitive value with a plausible fake drawn from the same category: a real name becomes a different but equally real-looking name, a real email becomes a fake one at a test domain. This keeps format validation, length checks and display logic working exactly as they would against production data, while removing any link to a real person. The main risk is doing it inconsistently: if the same customer's name is substituted differently in two tables, referential tests that join across tables will break or, worse, silently pass against mismatched data. Always substitute deterministically, keyed off a stable identifier, so the same source value always maps to the same fake value within a given masking run.

Shuffling keeps the real values but reassigns them across rows, so 'Jane's salary' becomes attached to a different row entirely. This preserves the overall statistical distribution (useful for performance or reporting tests that depend on realistic value spread) but breaks the link between a specific record and a specific person. Shuffling is weaker than substitution for compliance purposes, because the real values are still present in the dataset, just rearranged; it should not be used alone when regulation requires that no real personal values remain.

Tokenization replaces a value with an opaque token (a random string with no inherent meaning) and stores the real value, if it is kept at all, in a separate vault with its own access controls. This is the strongest option for values you must be able to recover in rare cases, such as a support investigation, because the token itself carries no information and a breach of the test dataset alone exposes nothing.

Masking vs. True Anonymization, and When Synthetic Data Wins

Masking and anonymization are often used loosely as synonyms, but they answer different questions. Masking asks: does this value still look real, so my tests still exercise real validation and display logic? Anonymization asks: can this record ever be traced back to a real person, by anyone, under any combination of other data they might hold? A masked dataset can still fail anonymization if enough quasi-identifiers survive together (a birth date, a postcode and a job title can uniquely identify someone even with the name removed). True anonymization typically requires generalizing or removing those quasi-identifiers as a group, not just the obviously sensitive fields.

When regulation or internal policy demands true anonymization, or when a test does not need any particular production-shaped value at all, synthetic data generation is the simpler and safer path: build records entirely from a generator rather than starting from a real export. A library such as Faker can produce names, addresses, phone numbers and dates that are realistic in shape and distribution without any connection to a real person, which sidesteps the masking-versus-anonymization question entirely because there was never a real record to protect.

A practical rule: use synthetic data as the default for new test suites, reserve masking for cases where you specifically need to reproduce a production bug or a production-shaped edge case, and treat full anonymization as the bar for any dataset that leaves your control, such as one shared with a vendor or a contractor.

import csv
import hashlib
from faker import Faker

fake = Faker()
Faker.seed(0)

def deterministic_fake_name(real_value: str) -> str:
    # Hash the real value to a stable seed so the same input
    # always maps to the same fake output within this run.
    seed = int(hashlib.sha256(real_value.encode()).hexdigest(), 16) % (10 ** 8)
    local_fake = Faker()
    local_fake.seed_instance(seed)
    return local_fake.name()

with open('production_export.csv') as src, open('masked_export.csv', 'w', newline='') as dst:
    reader = csv.DictReader(src)
    writer = csv.DictWriter(dst, fieldnames=reader.fieldnames)
    writer.writeheader()
    for row in reader:
        row['customer_name'] = deterministic_fake_name(row['customer_name'])
        row['email'] = f"user{hash(row['email']) % 100000}@example.test"
        writer.writerow(row)

Masks an exported CSV by substituting each real name with a deterministic fake name (same input always produces the same fake output, so joins across tables still work) and rewriting emails to a test domain, leaving all other columns and the dataset's shape intact.

from faker import Faker

fake = Faker()

def generate_synthetic_customer():
    return {
        'name': fake.name(),
        'email': fake.email(),
        'address': fake.address(),
        'phone': fake.phone_number(),
        'signup_date': fake.date_between(start_date='-2y', end_date='today'),
    }

customers = [generate_synthetic_customer() for _ in range(50)]

Generates 50 fully synthetic customer records with no connection to any real person, suitable as seed data for a test environment that does not need production-shaped edge cases.

Tips

  • Mask or anonymize as close to the export as possible, ideally in the pipeline that creates the test dataset, so an unmasked file never lands on a shared drive even temporarily.
  • Keep a written mapping of which fields are masked, shuffled, tokenized or left as-is, and review it whenever a new column is added to the source data.
  • Default new test suites to synthetic data and only fall back to masked production data when a test specifically needs a production-shaped edge case; a test environment's seed endpoint is a natural place to create that data and its clean-up endpoint to remove it afterward.

Common pitfalls

  • Masking only the obviously sensitive fields (name, email) while leaving quasi-identifiers like birth date, postcode and job title intact together, which can still uniquely identify a person even though no single field looks sensitive on its own.
  • Substituting values non-deterministically, so the same customer gets a different fake name in two different tables; this silently breaks join-based tests or, worse, makes them pass against data that no longer corresponds row to row.

Test Data in Automated Pipelines: Seeding, Cleanup and Environments

A pipeline that runs tests unattended, at night or on every pull request, cannot rely on a person clicking through a database tool to set up records by hand. It needs the data creation and removal built into the test run itself, as explicit steps rather than tribal knowledge. The common pattern is three kinds of calls around the actual test: a seed call that creates the records a test needs, the test itself, and a clean-up call that removes what the seed created, win or lose. A third kind, a read-only check, lets a test or a pipeline step ask the system what state it is actually in without changing anything, which is useful for asserting that a background job really ran.

Keeping these as endpoints of your own, rather than direct database writes from the test runner, has two benefits. First, the test runner never needs a database driver, a connection string or a service account with write access to production-shaped data; it only needs an HTTP client and a token. Second, the endpoint can enforce the same validation and business rules a real user's request would, so seeded data looks like data the application itself would have created, not a shortcut that happens to satisfy a query.

As one example of this pattern, xtest lets a test define a test environment with a seed and a clean-up endpoint of your own that it calls with POST before and after a run, and read-only checks it calls with GET, each sent with your own token; the data itself is still generated by your endpoint, not by xtest, and xtest never connects to your database directly. This section covers how to design those endpoints so they are safe to call repeatedly, how to scope the data they create so parallel runs do not collide, and what to log so a failed seed call is easy to debug from a pipeline's console output alone.

Designing Seed and Clean-up Endpoints

A seed endpoint should do one job: take a small, explicit payload describing what a test needs, and return identifiers the test can use, such as a user id, an order number or an authentication token. Keep the payload intentional rather than a dump of every field a record could have; a test that only needs "a customer with an overdue invoice" should not have to specify forty unrelated fields. Where sensible, give the endpoint sensible defaults and let the caller override only what matters for that test.

The clean-up endpoint is the harder half to get right, because it has to run even when the test itself failed partway through, left the UI in an unexpected state, or timed out. Design clean-up to work from the identifiers the seed call returned, not from assumptions about what the test did in between: delete the order by its id, not by "the most recent order for this customer," because a failed test may have created more than one. Make clean-up idempotent, so calling it twice, or calling it on data already removed, returns a clean success rather than an error that breaks the pipeline.

Read-only check endpoints round the pattern out: they let a test, or the pipeline around it, confirm a side effect actually happened, such as an email being queued or a webhook being recorded, without the test having to poll the UI for something that may never render. Because these calls only read, they are safe to call from more places than seed and clean-up, including a monitoring script that runs independently of any single test.

Isolation, Parallelism and Common Pitfalls

Once a pipeline runs more than one test at a time, seed and clean-up endpoints need to produce data that cannot collide. The classic mistake is seeding a record with a fixed email address or fixed username; two tests running in parallel will fight over the same record, and one of them fails for a reason that has nothing to do with the feature under test. Generate unique identifiers per run, for example by appending a timestamp or a random suffix to any field that must be unique, and prefer returning a fresh id from the seed call over hardcoding one in the test.

A second pitfall is a seed endpoint that silently succeeds even when it created nothing, because it swallowed an error internally. A pipeline that cannot tell "the seed worked" from "the seed quietly did nothing" will spend hours debugging a test failure that was really a setup failure. Have the seed endpoint return a clear error status and a message when it cannot create what was asked, so the pipeline fails fast at the right step with a useful log line.

A third pitfall is skipping clean-up on failure. If clean-up only runs after a passing test, every failed run leaves orphaned records behind, and a database used for testing slowly fills with stale data until some unrelated test starts failing because a count or a search result is no longer what it expects. Always wrap the test step so clean-up runs regardless of the outcome, and treat a clean-up endpoint's own failure as worth logging, even if the pipeline does not fail the build because of it.

# Seed data before the suite, capture the id, run tests, clean up after
RESPONSE=$(curl -s -X POST https://api.example.com/test-data/seed \
  -H "Authorization: Bearer $TEST_DATA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"type": "customer", "state": "overdue_invoice", "suffix": "'"$RUN_ID"'"}')

CUSTOMER_ID=$(echo "$RESPONSE" | jq -r '.id')
if [ -z "$CUSTOMER_ID" ] || [ "$CUSTOMER_ID" = "null" ]; then
  echo "Seed call failed, aborting before running tests"
  exit 1
fi

export CUSTOMER_ID
npx playwright test tests/billing.spec.js
TEST_EXIT=$?

# Clean up regardless of whether the test passed
curl -s -X POST https://api.example.com/test-data/cleanup \
  -H "Authorization: Bearer $TEST_DATA_TOKEN" \
  -d '{"id": "'"$CUSTOMER_ID"'"}' > /dev/null

exit $TEST_EXIT

A pipeline script that seeds a uniquely suffixed customer record, checks the seed actually returned an id before running tests, runs a Playwright test against that record, and always calls the clean-up endpoint afterward regardless of the test's result.

const { test, expect } = require('@playwright/test');

let customerId;

test.beforeAll(async ({ request }) => {
  const res = await request.post('https://api.example.com/test-data/seed', {
    data: { type: 'customer', state: 'overdue_invoice' },
    headers: { Authorization: `Bearer ${process.env.TEST_DATA_TOKEN}` }
  });
  const body = await res.json();
  customerId = body.id;
  expect(customerId, 'seed endpoint must return a customer id').toBeTruthy();
});

test.afterAll(async ({ request }) => {
  if (customerId) {
    await request.post('https://api.example.com/test-data/cleanup', {
      data: { id: customerId },
      headers: { Authorization: `Bearer ${process.env.TEST_DATA_TOKEN}` }
    });
  }
});

test('overdue invoice shows a reminder banner', async ({ page }) => {
  await page.goto(`https://app.example.com/customers/${customerId}`);
  await expect(page.getByText('Payment overdue')).toBeVisible();
});

A Playwright test file that seeds its own data in beforeAll, asserts the seed actually worked before any test runs, and always cleans up in afterAll so the record does not outlive the test.

Tips

  • Make every seeded record identifiable to a single run, for example with a run id in its name or email, so parallel pipelines never collide over the same data.
  • Have the seed endpoint fail loudly with a clear error rather than silently returning nothing, so a broken setup step is never mistaken for a failing test.
  • Use read-only check endpoints to confirm background effects, like a queued email, instead of waiting on a UI element that may never appear.

Common pitfalls

  • Skipping clean-up when a test fails: wrap the test step so clean-up always runs on both pass and failure, otherwise failed runs leave orphaned data behind.
  • Seeding with fixed, non-unique values such as a hardcoded email: two parallel runs then fight over the same record, producing failures unrelated to the feature under test.

Test Data Governance and Lifecycle Management

Test data does not manage itself, and once a project has more than one environment and more than one contributor, the lack of a governance plan turns into either stale fixtures nobody trusts or a leak of real customer data into a bug report. This section looks at the policy layer that sits above the mechanics of generating or masking data: who is allowed to decide what counts as safe test data, how long any given batch of it should live before it is purged, and how it is allowed (or forbidden) to move between production, staging and a developer's laptop.

Governance starts with ownership. A team that treats test data as 'whatever is left over from the last person's run' will eventually ship a test that depends on a row someone meant to delete. Assigning a named owner for each dataset, along with a written policy for who can request new data, who approves exceptions, and who audits the result, turns test data from an accident into an asset.

Retention is the second pillar. Data kept too long becomes a liability (expired accounts, stale foreign keys, accumulating disk usage); data purged too aggressively breaks reproducibility, since a failing test is far easier to debug when the exact dataset that triggered it still exists. A retention policy should state, in writing, how long raw datasets, masked snapshots and generated fixtures are kept, and what triggers early deletion.

The third pillar is movement: the rules for copying data from production into lower environments. Any such copy must pass through masking or synthetic replacement before it reaches staging or a local machine, and the policy should say explicitly which fields are sensitive, which pipeline step strips them, and who is accountable if that step is skipped. Documenting all of this somewhere a new hire can read, rather than letting it live only in the heads of two senior engineers, is what makes the practice survive staff turnover.

xtest, for instance, lets a test have a test environment: a seed and a clean-up endpoint of yours that it calls with POST before and after a run, plus read-only checks called with GET, each using your token, so even an AI-driven run still depends on whoever owns and governs the data behind those endpoints.

Ownership, Roles and Access Policy

A test data governance policy should name three kinds of responsibility explicitly: who can create new test data, who can approve a request to copy or refresh it from a higher environment, and who audits that the rules were actually followed. Without named owners, test data tends to be created ad hoc by whoever hits a blocker first, and six months later no one remembers why a particular account has admin rights or why a particular record has a negative balance.

A practical starting point is a short RACI-style table per dataset: one owner responsible for its content and schema, one approver for any request to pull fresh data from production, and a list of consumers who are allowed to read it but not change its shape without telling the owner. This matters most at the boundary between teams: a payments team's fixtures should not be silently edited by a shipping team's test suite, even though both suites touch the same staging database.

Access policy also needs to state who can see unmasked data at all. In most organizations, only a small group with a documented need should ever have production-shaped data with real values; everyone else should work from masked or synthetic copies. Writing this down, and reviewing it on a fixed schedule such as every quarter, keeps the list of people with elevated access from growing quietly over time. Pair the written policy with a lightweight enforcement mechanism, such as a config file that only owners can merge, so the policy is not just a document nobody checks against reality.

Retention, Movement and Documentation

Retention policy should answer three concrete questions for every category of test data: how long does it live, what deletes it, and what happens if a test still depends on it when it expires. A common pattern is a tiered retention schedule: ephemeral data created and torn down within a single test run, short-lived data kept for a sprint to help debug flaky failures, and long-lived reference data (like a stable set of country codes or product categories) that is versioned rather than deleted.

Movement between environments deserves its own written rule, separate from retention. Production to staging copies should never happen unmasked, and the policy should name the exact tool or script responsible for masking, so there is no ambiguity about whether a given copy already passed through it. Staging to local copies carry the same risk at smaller scale: a developer who pulls a 'quick copy' of staging onto a laptop should still be pulling already-masked data, not a shortcut around the pipeline.

Finally, all of this needs to be documented somewhere durable: a README in the test data repository, a wiki page linked from the onboarding checklist, or a short runbook that a new engineer can follow without asking a teammate to walk them through it verbally. The document should include the owner list, the retention schedule, the masking tool used for each environment boundary, and the escalation path when something looks wrong, such as unmasked emails showing up in a staging database.

import csv
import hashlib

SENSITIVE_FIELDS = {"email", "full_name", "phone"}

def mask_value(field, value):
    if field in SENSITIVE_FIELDS:
        digest = hashlib.sha256(value.encode()).hexdigest()[:10]
        return f"{field}_{digest}@example.test" if field == "email" else digest
    return value

def mask_csv(source_path, dest_path):
    with open(source_path, newline="") as src, open(dest_path, "w", newline="") as dst:
        reader = csv.DictReader(src)
        writer = csv.DictWriter(dst, fieldnames=reader.fieldnames)
        writer.writeheader()
        for row in reader:
            masked_row = {field: mask_value(field, value) for field, value in row.items()}
            writer.writerow(masked_row)

mask_csv("production_export.csv", "staging_dataset.csv")

A minimal masking step that any production-to-staging pipeline can call before a dataset crosses that boundary: it hashes sensitive fields instead of copying them verbatim, giving the governance policy a concrete script to point to rather than a vague instruction to 'anonymize the data'.

#!/usr/bin/env bash
set -euo pipefail

DATASET_OWNER_FILE="test-data/owners.yml"
REQUESTED_DATASET="$1"

owner=$(grep -A1 "^${REQUESTED_DATASET}:" "$DATASET_OWNER_FILE" | grep owner | awk '{print $2}')

if [ -z "$owner" ]; then
  echo "No registered owner for dataset '$REQUESTED_DATASET'. Refresh request blocked."
  exit 1
fi

echo "Dataset '$REQUESTED_DATASET' is owned by $owner. Notifying for approval before refresh."
# e.g. post a message to the owner's channel here, then proceed only after approval

A small guard script that checks a dataset against a registered owners file before allowing a refresh request to proceed, turning the 'who approves this' policy into something a CI job can actually enforce.

Tips

  • Keep a single owners file or table for all test datasets, reviewed on a fixed schedule, so ownership does not quietly drift to 'whoever touched it last'.
  • Separate the retention clock from the masking step: data can be short-lived and still require masking before it ever reaches a lower environment.
  • Write the governance policy down somewhere a new hire finds during onboarding, not only in a senior engineer's memory or an old Slack thread.

Common pitfalls

  • Treating 'we masked it once' as permanent: a pipeline change can reintroduce unmasked fields silently, so the masking step should be checked on every copy, not assumed from past behavior.
  • Letting retention policy exist only on paper: without an automated job that actually deletes expired data, 'data expires after 30 days' quietly becomes 'data never expires', and disk usage and stale state accumulate unnoticed.

Exercises

Exercise 1: Build a Synthetic Data Generator

In this exercise you will write a small script that generates synthetic test data for a fictional e-commerce application, producing realistic customer and order records without touching any real data. This exercise reinforces the foundational idea that good test data is realistic, isolated and disposable, and gives you hands-on practice with a generation tool before moving on to masking and pipeline integration in later sections. You will work with Python and the Faker library, though the same exercise can be redone with any equivalent library in another language if you prefer.

  1. Install the Faker library in a Python environment (pip install faker).
  2. Write a function that generates a single customer record with a first name, last name, unique email, and a shipping address.
  3. Write a second function that generates between 1 and 5 order records for a given customer, each with a unique order id, a random item list, and an order date within the last year.
  4. Combine both functions to generate 20 customers, each with their own set of orders, and write the result to a JSON file.
  5. Add a uniqueness check that fails loudly if any two generated emails or order ids collide, and re-run the generator a few times to confirm it never collides.

Expected outcome: A JSON file containing 20 synthetic customers, each with one to five orders, all referentially consistent (every order belongs to a customer that exists in the file) and with no duplicate emails or order ids across multiple runs.

Exercise 2: Seed and Clean Up a Test Environment

In this exercise you will practice the seed-then-cleanup pattern that keeps automated tests isolated and free of leftover data. You will simulate calling a REST API to create a test user before a test and delete it afterward, using a mock or a simple local API if you don't have a real one available. This exercise is meant to make the setup and teardown pattern a reflex, since it is one of the most common sources of flaky automated tests when skipped.

  1. Set up a minimal local API (or use a public mock API service) that supports creating and deleting a user resource.
  2. Write a shell script using curl and jq that creates a user with a uniquely generated email, prints the returned user id, and stores it in a variable.
  3. Insert a placeholder step in the script representing 'run the test suite here', and confirm the script continues correctly even if that placeholder step is made to fail.
  4. Add a cleanup step at the end of the script that deletes the user by id, and make sure it runs regardless of whether the placeholder test step passed or failed.
  5. Run the script five times in a row and confirm no leftover users remain in the API's user list after each run.

Expected outcome: A working shell script that creates an isolated test user, leaves no residue after either a passing or a failing test step, and can be run repeatedly without any manual cleanup.

Quiz

1. Which of the following best describes why copying a full production database into a staging environment is considered a poor test data practice?

  1. It usually exposes sensitive real data to a wider audience than production allows, and the data's shape can drift out of sync with what tests expect
  2. It is too slow to copy a database compared to generating data fresh
  3. Staging environments cannot technically store the same amount of data as production
  4. Production databases do not contain enough data to be useful for testing
Show answer

A. It usually exposes sensitive real data to a wider audience than production allows, and the data's shape can drift out of sync with what tests expect

The core issues are privacy exposure, since a wider group of people typically can access staging than production, and data drift, since production data changes in ways tests don't control. Masking or using synthetic data addresses the privacy issue directly.

2. What is the key difference between synthetic data and masked data?

  1. Synthetic data is always larger in volume than masked data
  2. Synthetic data is generated from scratch and never derived from a real record, while masked data starts as real data that has been altered to remove identifying details
  3. Masked data is always faster to generate than synthetic data
  4. There is no meaningful difference; the terms are interchangeable
Show answer

B. Synthetic data is generated from scratch and never derived from a real record, while masked data starts as real data that has been altered to remove identifying details

Synthetic data never touches a real person's information at all, making it the safer default. Masked data begins as a real record and depends on the masking step being thorough and applied before the data reaches anyone who shouldn't see the original.

3. A test suite occasionally fails because a test expecting exactly one 'pending' order finds two, created by another test running at the same time. What is the most direct fix?

  1. Run all tests sequentially on a single shared machine forever
  2. Give each test run its own uniquely identified data so no two runs can collide
  3. Increase the number of pending orders the test expects to two
  4. Delete the entire database before every single test
Show answer

B. Give each test run its own uniquely identified data so no two runs can collide

The underlying problem is shared mutable state between parallel test runs. Generating unique identifiers per run (such as a timestamp-based email or order reference) isolates each run's data so it cannot be affected by another run happening at the same time.

4. In an automated pipeline, pairing every data setup step with a corresponding teardown step primarily solves which problem?

  1. Slow network requests during the test run
  2. Cleanup debt, where test-created data accumulates indefinitely and clutters the environment
  3. Incorrect test assertions
  4. Missing test case documentation
Show answer

B. Cleanup debt, where test-created data accumulates indefinitely and clutters the environment

Without a teardown step, every test run that creates data leaves it behind, and over time an environment fills with abandoned records that nobody wants to remove for fear of breaking something. Pairing setup with teardown keeps the environment clean run after run.

5. When a test environment is defined with a seed endpoint and a clean-up endpoint that a testing tool calls automatically around a run, what is still the responsibility of the team rather than the tool?

  1. Deciding what data the seed endpoint actually creates, since the tool calls the endpoint but does not generate the data itself
  2. Starting the browser used to run the test
  3. Recording whether the test passed or failed
  4. Choosing which device the test runs on
Show answer

A. Deciding what data the seed endpoint actually creates, since the tool calls the endpoint but does not generate the data itself

A test environment feature like this calls your own seed and clean-up endpoints with POST before and after a run, but it does not generate test data on its own. Writing the logic that actually creates and removes the right data remains the team's own responsibility, implemented in the seed and clean-up endpoints themselves.

Related docs

All courses