Seeding Test Databases in CI/CD with Synthetic JSON

Guest post by Nebustream · Published
This is a guest post written for JSONGenerator by Nebustream, a DevOps consultancy.
Unit tests can get by with mocks. Integration tests can't. The moment your tests touch a real database, you need data in it: enough rows to exercise pagination, a mix of statuses to hit every branch, and values that look like what your users actually enter.
Most teams solve this in one of three ways, and two of them cause problems later. This post walks through the approach that holds up: generate synthetic JSON fixtures once, commit them, and load them into a fresh database on every pipeline run.
The three common approaches
1. Copy production. It's realistic, and it's the easiest to set up. It's also the riskiest. A production dump puts real names, emails and payment details on CI runners, in build logs, in cached artifacts, and often with a third-party CI vendor. If you handle health records, financial data or government data, that copy pulls your whole pipeline into compliance scope. Dumps also get large and slow, and they go stale.
2. Hand-written fixtures. Safe, but someone has to write and maintain them. They tend to be tiny ("Test User 1", "Test User 2"), which means they miss the bugs real data finds: long names, odd characters, empty optional fields.
3. Generated synthetic data. Realistic in shape and variety, contains no real people, and costs nothing to regenerate when your schema changes. This is the one we'll build.
What good seed data looks like
Before writing any code, it helps to agree on the goals:
- Deterministic. Every pipeline run starts from the same data, so a failing test fails every time, not one run in five.
- Matches the schema. Every column a constraint requires is present and valid.
- Small but varied. Fifty to a few hundred rows per table is plenty for integration tests. Load testing is a separate job.
- Isolated. Each run gets its own throwaway database. Nothing carries over between runs.
- Versioned. Fixtures live in the repo next to the migrations they depend on, so a schema change and its data change land in the same pull request.
Step 1: Define the table
We'll use a simple Postgres users table as the running example:
CREATE TABLE users (
id uuid PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
email text NOT NULL UNIQUE,
status text NOT NULL CHECK (status IN ('active', 'disabled')),
city text,
state text,
credit_limit integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
Step 2: Generate the fixture
Open the JSON Generator and paste a template that mirrors the table. Each key is a column, and each value tells the generator what kind of data to produce:
[
"repeat(50)",
{
"id": "guid()",
"first_name": "firstName()",
"last_name": "lastName()",
"email": "email(example.com)",
"status": "enum(active, disabled)",
"city": "city()",
"state": "state()",
"credit_limit": "int(500,10000)"
}
]
repeat(50) produces 50 records. enum(...) picks one of the listed values (the template tag reference lists every tag and its options), so you get both active and disabled users and your tests can cover both. email(example.com) puts every address on example.com, a domain reserved for documentation and testing, so a test that accidentally triggers a real email can never reach a real inbox.
Generate, then save the output as test/fixtures/users.json:
[
{
"id": "3f6c1a2e-8b4d-4c1f-9e2a-7d5b0c9e1f42",
"first_name": "Marisol",
"last_name": "Okafor",
"email": "Dane_Kuhlman@example.com",
"status": "active",
"city": "North Lavonne",
"state": "Ohio",
"credit_limit": 7340
}
]
Because int(500,10000) is the whole value, credit_limit comes out as a number (7340), ready for the integer column. Used inside other text, such as "ID-int(1,9)", a tag is inserted as text instead.
Commit the generated file, not just the template. The generator produces different values each time, which is great for variety but bad for repeatable tests. Generate once, review it, commit it. When the schema changes, update the template, regenerate, and commit both in the same pull request.
Step 3: Write the seed script
The script resets the table and bulk-loads the fixture in one transaction. Postgres's json_populate_recordset turns the JSON array into rows that match the table's column types, so there's no need to build hundreds of INSERT statements:
import { readFile } from "node:fs/promises";
import pg from "pg";
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const users = JSON.parse(await readFile("test/fixtures/users.json", "utf8"));
try {
await client.query("BEGIN");
await client.query("TRUNCATE users CASCADE");
await client.query(
`INSERT INTO users (id, first_name, last_name, email, status, city, state, credit_limit)
SELECT id, first_name, last_name, email, status, city, state, credit_limit
FROM json_populate_recordset(NULL::users, $1::json)`,
[JSON.stringify(users)]
);
await client.query("COMMIT");
console.log(`Seeded ${users.length} users`);
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
await client.end();
}
The column list matters. If you write INSERT INTO users SELECT *, any column missing from the JSON (like created_at) comes through as NULL instead of falling back to its default, and the NOT NULL constraint rejects the row.
Step 4: Run it in the pipeline
GitHub Actions can start a Postgres container alongside the job as a service. It's created fresh for every run and destroyed afterward, which gives you isolation for free:
name: test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: app
POSTGRES_PASSWORD: app
POSTGRES_DB: app_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U app"
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
DATABASE_URL: postgres://app:app@localhost:5432/app_test
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run db:migrate
- run: node scripts/seed.mjs
- run: npm test
The order is the important part: migrate, then seed, then test. If the seed step fails, the job stops before any tests run, so a broken fixture shows up as a clear seed error instead of 40 confusing test failures.
The same pattern works in GitLab CI (services: [postgres:16]), CircleCI (a secondary Postgres image), and Azure Pipelines (service containers). Only the YAML syntax changes.
Common pitfalls
Foreign keys and insert order. Seed parent tables before child tables: users before orders, orders before order_items. TRUNCATE ... CASCADE takes care of clearing them in the right order.
Sequences after explicit IDs. If a table uses an integer serial or identity column and your fixture supplies the IDs, Postgres doesn't advance the sequence. The first insert your app makes during a test then collides with an existing ID. Reset it after seeding:
SELECT setval(pg_get_serial_sequence('orders', 'id'), (SELECT max(id) FROM orders));
UUID keys, like the ones in this example, avoid the problem entirely.
Unique constraints. Random data occasionally repeats a value. Check before you commit a fixture:
jq '[.[].email] | length == (unique | length)' test/fixtures/users.json
If that prints false, regenerate. To catch type mistakes too, turn one record into a schema with the JSON Schema Generator and validate the fixture against it in CI.
Dates that go stale. A fixture with an appointment on a fixed date in March is "upcoming" until March, and then your tests start failing for no obvious reason. Keep date columns out of the fixture and set them in the seed script relative to the current time, e.g. now() + interval '3 days'.
Fixtures that grow forever. If the seed step takes longer than the tests, the data set is too big. Integration tests need coverage of cases, not volume.
Why this matters beyond convenience
The quiet benefit of synthetic seed data is what's not in your pipeline. With no real customer data on your runners, a leaked CI log or a misconfigured artifact bucket exposes nothing that matters. For teams working under HIPAA, SOC 2 or government security frameworks, keeping real data out of CI also keeps your build infrastructure out of the most expensive part of an audit.
It also makes onboarding simpler. A new developer clones the repo, runs migrate and seed locally, and has the same database the pipeline uses, with no production access and no request ticket.
Wrapping up
The whole setup is three files: a fixture generated from a template, a 25-line seed script, and a workflow that runs migrate, seed and test in order. Once it's in place, every pipeline run starts from a known, realistic and safe database.
If your team is setting up pipelines like this for a regulated environment and wants outside help, Nebustream's DevOps consulting practice designs and builds CI/CD pipelines, infrastructure as code and DevSecOps scanning for healthcare, government and enterprise teams.