Trace-to-Test Generator Design
Overview
The Trace-to-Test Generator (T2T) is a system that automatically converts execution traces (e.g., HTTP HAR files, Jaeger traces, OpenTelemetry spans, or custom logs) into deterministic, replayable test cases. It targets API-heavy applications (e.g., web services, microservices) to enable regression testing, CI/CD integration, and property-based verification.
Key Goals
- Fidelity: Tests replay the exact sequence of interactions from a successful trace.
- Determinism: Eliminate flakiness by normalizing non-deterministic elements (e.g., timestamps, UUIDs).
- Maintainability: Generate "golden" assertions (expected responses) that can be versioned and diffed.
- Extensibility: Pluggable parsers, determinization rules, and test emitters.
- Coverage: Support stateful sessions, auth flows, parallelism (traces with branches).
High-Level Architecture
Input Trace → [Request Harvesting] → Raw Request Sequence
↓
[Determinization] → Determinized Request Sequence
↓
[Golden Assertions] → Test Suite (e.g., pytest, Jest)
| Component | Input | Output | Purpose |
|---|
| Request Harvesting | Raw trace (HAR, OTLP, logs) | Sequence of requests (method, URL, headers, body) + responses | Extract observable interactions |
| Determinization | Raw sequence | Normalized sequence (placeholders for non-dets) | Enable reliable replay |
| Golden Assertions | Determinized sequence | Executable test code + golden JSON/YAML snapshots | Assert exact matches or semantic equality |
1. Request Harvesting
Purpose
Parse traces to harvest a linear (or branched) sequence of requests (external calls: HTTP, gRPC, DB queries) and their responses. Ignore internal noise (e.g., health checks).
Inputs
- Supported Formats:
| Format | Parser | Example |
|---|
| HAR (HTTP Archive) | har-parser | Browser DevTools export |
| OpenTelemetry (OTLP/JSON) | otlp-parser | Jaeger, Zipkin exports |
| Logs (structured) | log-parser | JSON logs with http_request fields |
| Custom | YAML/JSON traces | User-defined schemas |
Processing Steps
- Parse Trace: Load and validate input.
- Identify Boundaries: Segment by spans/transactions (e.g., user session).
- Harvest Requests:
- Filter: External APIs only (configurable regex for URLs).
- Extract:
| Field | Source | Notes |
|---|
method | HTTP method | GET/POST/etc. |
url | Full URI | Normalize query params |
headers | All headers | Sensitive: redact Authorization → {{auth_token}} |
body | Request payload | Pretty-print JSON/XML |
response | Status, headers, body | Full capture |
timing | Latencies (optional) | For perf assertions |
context | Parent span ID | For branching/merging |
- Handle State:
- Track cookies/sessions across requests.
- Extract auth tokens from prior responses (e.g., JWT from
/login).
- Output: JSON sequence:
[
{
"id": "req1",
"method": "POST",
"url": "https://api.example.com/login",
"headers": {"Content-Type": "application/json"},
"body": {"username": "user", "password": "pass"},
"response": {"status": 200, "body": {"token": "abc123"}}
},
...
]
Implementation Notes
- Library: Use
pyppeteer or playwright for HAR; opentelemetry-sdk for OTLP.
- Branching: Represent parallel traces as a DAG (e.g.,
{"type": "parallel", "children": [...]}).
- Config:
harvester.yaml for filters (e.g., exclude_urls: ["/health"]).
2. Determinization
Purpose
Transform raw sequence into a reproducible one by replacing non-deterministic values with placeholders or mocks. Ensures tests pass consistently across environments.
Non-Deterministic Categories & Rules
| Category | Examples | Replacement Strategy | Placeholder |
|---|
| Timestamps | 2023-10-01T12:00:00Z, now() | Epoch-relative (e.g., trace_start + 3600s) | {{timestamp}} |
| UUIDs/IDs | uuid-v4(), auto-inc DB IDs | Sequential placeholders | {{id:1}}, {{uuid}} |
| Randomness | Nonces, CSRF tokens | Extract from trace; mock generator | {{random}} |
| External Deps | 3rd-party APIs (Stripe, AWS) | Mock responses from trace | {{mock:external}} |
| Dynamic Content | User uploads, query params | Hash/content-based normalization | {{file:hash}} |
| Floating Env | Hostnames, ports | Canonicalize to base URL | {{base_url}}/path |
Processing Steps
- Scan Sequence: Traverse requests/responses recursively (JSON/XML).
- Apply Rules (pluggable via
rules.yaml):
rules:
- pattern: regex(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z')
replace: '{{timestamp}}'
- pattern: uuid_match()
replace: '{{uuid}}'
- deps:
- url: 'https://api.stripe.com/*'
action: mock_from_trace
- Propagate State:
- Replace extracted values (e.g., login token
abc123 → {{auth_token}}, reuse in next req).
- Generate mocks for DB/external calls.
- Validate: Replay dry-run against mock server; fail if mismatch.
- Output: Determinized JSON sequence (same schema as harvesting).
Implementation Notes
- Engine: Rule-based (regex + AST walker for JSON) + ML heuristics (e.g., detect UUIDs via
uuid lib).
- State Machine: Use
statemachine to track variables (e.g., token = extract(response.body.token)).
- Diff Tool:
git diff friendly (sort keys, normalize whitespace).
3. Golden Assertions
Purpose
Emit executable tests that replay the determinized sequence and assert against "golden" (expected) values from the trace.
Inputs
- Determinized sequence.
- Config: Test framework, base URL, mocks.
Outputs
-
Test Files: Language/framework agnostic emitter.
| Emitter | Example Output |
|---|
| Pytest | test_trace_001.py |
| Jest | trace-001.test.js |
| Cypress | trace-001.cy.js |
| Raw | HAR + assertions YAML |
-
Golden Snapshots: Separate files (e.g., snapshots/trace-001.json) with expected responses (versioned via Git).
Generation Steps
- Replay Skeleton:
- Sequential:
for req in sequence: client.send(req)
- Parallel:
Promise.all() or asyncio.gather()
- Assertions:
| Type | Code Snippet (Pytest) |
|---|
| Status | assert resp.status_code == 200 |
| Headers | assert resp.headers['Content-Type'] == 'application/json' |
| Body (Exact) | assert resp.json() == load_golden('req1.json') |
| Semantic | assert len(resp.json()['items']) == 5 (auto-infer) |
| Perf | assert resp.elapsed < 500ms |
- Fixtures/Mocks:
- Auth:
login_fixture() → {{auth_token}}
- Externals: WireMock/VCR.py cassettes from trace.
- Example Pytest Output:
import pytest
import requests
import json
@pytest.fixture
def client(base_url):
return requests.Session()
def test_trace_001(client, base_url):
# Req1
resp1 = client.post(f"{base_url}/login", json={"username": "user"})
assert resp1.status_code == 200
token = resp1.json()["token"] # {{auth_token}}
# Req2
headers = {"Authorization": f"Bearer {token}"}
resp2 = client.get(f"{base_url}/profile", headers=headers)
assert resp2.status_code == 200
assert json.dumps(resp2.json(), sort_keys=True) == golden_snapshot('req2')
- Golden Files:
snapshots/trace-001-req1.json (determinized response).
Config
generator:
framework: pytest
assertions:
- exact_body
- status_code
- perf: {max_latency: 1s}
mocks: wiremock
Integration & Usage
CLI
t2t generate input.har --output-dir tests/ --config t2t.yaml
t2t update-snapshots tests/trace-*.py # Re-record golds
t2t replay tests/trace-001.py --dry-run
CI/CD Workflow
- Run app with tracing (e.g., OpenTelemetry).
- Harvest → Determinize → Generate tests.
- Commit tests + snapshots.
- PRs:
pytest --snapshot-update on green runs.
Extensibility
- Plugins: New parsers/rules/emitters via entrypoints.
- Metrics: Coverage % (requests covered), determinism score.
Limitations & Future Work
- Non-HTTP: Extend to Kafka, DB (harvest via SQL traces).
- Errors: Generate negative tests from failure traces.
- ML Assist: Auto-generate semantic assertions (e.g., "user count > 0").
- Scale: Distributed trace merging for microservices.
This design enables 80-90% automation of E2E tests from prod/PPE traces, reducing manual toil. Prototype in Python (~2k LOC).