AI-POWERED TESTING

Generating Test Data With AI Agents Without Leaking Real Data

Test data is one of the first jobs people hand to an AI tool, and for good reason. Describe a nested API payload in plain English and you get a usable fixture back in seconds. The trouble is the shortcut that comes with it: pasting a real production record into the chat as a "template". I've seen teams who would never commit a customer email to a repo drop a full production payload into a chat window without thinking twice.

Coding agents raise the stakes. GitHub Copilot in agent mode, Claude Code, Cursor and similar tools don't just read what you paste. They read files in your workspace, run commands and look at command output. A CSV export sitting in your project folder, or a failure log full of staging responses, can become part of the prompt without you ever typing it. So the question is no longer just "what did I paste?" It's "what can the agent see?"

The good news is that AI generates better test data from a schema than from a real example. In this article I'll cover how I prompt from contracts, how I keep generated data deterministic, how I set rules for agents, and the test I add so leaks get caught automatically instead of by luck.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Prompt from the schema, never from a real record

The rule I start with: a prompt describes the shape of the data, it never contains an instance of real data. If I need synthetic users, the prompt looks like this:

Generate 10 JSON user objects matching this schema:
{
  "id": "UUID v4",
  "email": "address at example.com only",
  "full_name": "fictional name",
  "date_of_birth": "ISO 8601 date, age between 18 and 90",
  "account_balance": "number, range -500 to 100000",
  "status": "one of: active | suspended | pending"
}
Include one record with a negative balance, one name with non-ASCII
characters, and one record at exactly the minimum age.

That prompt produces more useful test data than a copied record would, because it asks for the edge cases production rarely shows you. Negative balances, unicode names and boundary ages are exactly what breaks APIs, and the model is building them from a contract rather than interpolating from something sensitive.

I keep a fixtures/schemas/ folder that holds only field names, types, constraints and allowed values. No sample values from any live system. That folder is the only input I point an AI tool at when I want data, and it doubles as documentation of what the API accepts.

Let the agent write factories, not fixture dumps

A pile of generated JSON goes stale the moment the schema changes. A factory function doesn't. When I ask Copilot or an agent for test data, I ask for a typed factory and review that, instead of reviewing hundreds of records:

import random
import uuid
from datetime import date, timedelta

from faker import Faker

fake = Faker()


def make_user(status="active", balance=0.0, name=None, age=30):
    n = random.randint(1000, 9999)
    return {
        "id": str(uuid.UUID(int=random.getrandbits(128), version=4)),
        "email": f"user{n}@example.com",
        "full_name": name or fake.name(),
        "date_of_birth": (date.today() - timedelta(days=age * 365 + 10)).isoformat(),
        "account_balance": balance,
        "status": status,
    }

Two details matter. Emails go to example.com, a domain reserved for documentation, so a generated address can never belong to a real person or send a real message. And the IDs come from random rather than uuid.uuid4(), so seeding makes them repeatable. With the factory in place, the agent can write make_user(status="suspended", balance=-200.0) in tests without ever needing to know what a real user looks like.

Keep generated data deterministic

Random data that changes on every run turns one failure into a guessing game. I seed both Faker and random once per test session in conftest.py:

import random

import pytest
from faker import Faker

SEED = 1234


@pytest.fixture(scope="session", autouse=True)
def seeded_data():
    Faker.seed(SEED)
    random.seed(SEED)

In a Behave suite the same two lines go in before_all in environment.py. The data is now repeatable without being a static file that drifts from the schema. When a test fails, I can regenerate exactly what it saw from the seed alone. One caution: order matters, so a test that runs in a different position under parallel execution may get different values. If that bites, seed inside the factory from a stable key such as the test name.

Control what the agent can see

This is where coding agents change the picture. Copilot uses open editor tabs and nearby files as context, and agent modes can open any file in the workspace, run your test suite and read the output. That means the leak path is often not a prompt you wrote. It's a file you left lying around. The habits I use:

  • No real exports in the repo folder, ignored or not. A .gitignore entry keeps a file out of Git, not out of an agent's reach. If you must inspect a production export, do it outside the workspace and delete it.
  • Close files with real data before starting an AI-assisted session. Open tabs are context.
  • Redact failure output. If staging holds snapshot data, an assertion message that prints the full response body puts that data in front of every agent that runs the tests. Print status, field names and IDs, not whole bodies.
  • Write the rule down for the agent. Copilot reads .github/copilot-instructions.md, and most agents have an equivalent instruction file.
## Test data rules
- Never read, copy or summarise files under data/exports/ or any *.csv outside tests/.
- Generate test data only from fixtures/schemas/ and the factories in tests/factories.py.
- Emails must use example.com. No real names of customers, staff or partners.
- If a test needs data that looks real, stop and ask instead of searching for it.

An instruction file is guidance, not enforcement. Treat it as the first line, and the next section as the one that actually holds.

Add a test that fails when real data sneaks in

Review catches most leaks. A test catches the rest, and it runs on every agent-written pull request without anyone remembering to look:

import json
import re
from pathlib import Path

ALLOWED_EMAIL = re.compile(r"@example\.(com|org|net)$")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")
CARD = re.compile(r"\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}\b")


def test_fixtures_contain_no_real_looking_pii():
    for path in Path("tests/fixtures").rglob("*.json"):
        text = path.read_text()
        for match in EMAIL.finditer(text):
            email = match.group()
            assert ALLOWED_EMAIL.search(email), f"{path}: {email}"
        assert not CARD.search(text), f"{path}: looks like a card number"

It's crude on purpose. It won't catch everything, but it turns the most common leaks (a real email, a card-shaped number) into a red build instead of a quiet commit. Extend the patterns with whatever counts as sensitive in your domain.

Where the remaining risk hides

Even with all of this, two gaps stay open. Chat history: browser tools may keep conversations, so use the tool your organisation has approved under its data agreements, and treat it like any external service. And staging itself: if staging is loaded from a production snapshot, every test run against it handles real data. The best fix is to populate staging from the same factories the tests use. Then the whole pipeline, agents included, only ever touches data you invented.

Done this way, synthetic data isn't a privacy compromise. It's better test data: boundary values, malformed inputs and deliberate violations that real records would never give you. If you want to see this kind of factory-plus-Copilot setup inside a full API test project, my API testing courses build one step by step. For the broader picture of where AI fits in testing, see how AI is changing software testing, and for safely sharing generated data across scenarios, sharing test data across a Behave suite.