Webhook Test Data: Valid, Invalid, and Replay Scenarios
Webhook Test Data: Valid, Invalid, and Replay Scenarios
Webhooks are the nervous system of modern micro‑service architectures. They push events from payment gateways, CI/CD pipelines, messaging platforms, and countless third‑party APIs into your own services. Because the payload arrives asynchronously and outside of your control, the only reliable way to verify handling logic is to feed the system realistic test data—both the happy‑path and the edge cases that cause production incidents.
This guide walks through a repeatable process for building three families of webhook test data:
| Family | Goal | Typical Sources |
|---|---|---|
| Valid | Exercise the normal code path, confirm schema compliance, verify business logic | Production samples, provider documentation, sandbox environments |
| Invalid | Surface validation gaps, error‑handling branches, security regressions | Mutated valid payloads, spec‑defined error codes, fuzzing tools |
| Replay | Re‑create exact historic events for regression, debugging, or compliance audits | Captured live traffic, logged request bodies, event store exports |
The workflow below works whether you hand‑craft JSON files, script generators, or use a dedicated api test data generator such as the free tool at /tools/test-data-generator.
1. Problem‑Aware Hook
A typical QA conversation goes like this:
“We added a new Stripe
invoice.payment_failedhandler. The unit tests pass, but the staging deployment threw a 500 when a malformedmetadataobject arrived.”
The root cause is usually missing test coverage for malformed or unexpected payloads. Webhooks are external contracts; you cannot rely on the provider to send only what the docs describe. Network glitches, version upgrades, and custom integrations all produce payloads that deviate from the spec.
A disciplined test‑data strategy eliminates the “works on my machine” blind spot by:
- Cataloguing every event type your system consumes.
- Defining a baseline valid payload for each type.
- Deriving systematic invalid variations.
- Capturing real‑world events for replay scenarios.
2. Decision Criteria & Workflow
2.1 Choose a Representation Format
| Format | When to Use | Tooling |
|---|---|---|
| JSON files (one per event) | Small‑to‑medium test suites, version‑controlled | Git, any editor |
| YAML + templating | Need for parameterised fields (e.g., timestamps, IDs) | jinja2, helm‑style templates |
| Programmatic generators (Python, Go, JS) | Large matrices, dynamic values, CI integration | Custom scripts, QA3 test‑data generator |
| Recorded traffic (HAR, pcap, OpenAPI examples) | Replay fidelity, compliance evidence | mitmproxy, tcpdump, provider sandboxes |
Rule of thumb: start with static JSON files for the first 10‑15 event types. When the matrix explodes (multiple accounts, locales, feature flags), migrate to a generator.
2.2 Define a Test‑Data Catalogue
Create a catalogue spreadsheet (or a lightweight markdown table) with one row per event type:
| Event ID | Provider | Spec Version | Valid Sample Path | Invalid Variants | Replay Source |
|---|---|---|---|---|---|
stripe.invoice.payment_failed | Stripe | 2023‑10‑16 | samples/stripe/invoice_payment_failed.json | metadata_missing, amount_negative, signature_invalid | captures/2024‑03‑12/ |
github.pull_request.opened | GitHub | 2024‑01‑01 | samples/github/pr_opened.json | base_ref_null, head_sha_malformed | captures/2024‑02‑28/ |
The catalogue becomes the single source of truth for test‑data ownership, review cadence, and automation hooks.
2.3 Validation Checklist (Run on Every New Payload)
| Check | Tool / Method | Pass Criteria |
|---|---|---|
| Schema conformance | JSON Schema (ajv, jsonschema), OpenAPI validator | No validation errors |
| Signature verification | Provider SDK or HMAC re‑calculation | Signature matches header |
| Idempotency key uniqueness | In‑memory set or DB unique constraint | No duplicate key in test run |
| Timestamp freshness | Compare created/event_time to now ± 5 min | Within window |
| Required business fields | Custom rule engine (e.g., amount > 0) | All rules true |
| Size limits | Content‑Length header vs. config max | ≤ configured max |
Automate the checklist in a pre‑test hook (GitHub Actions, GitLab CI, Jenkins) so every PR that adds or modifies a sample runs the full suite.
3. Worked Example: Stripe invoice.payment_failed
3.1 Baseline Valid Payload
{
"id": "evt_1N2X3Y4Z5W6V7U8T",
"object": "event",
"api_version": "2023-10-16",
"created": 1709423400,
"data": {
"object": {
"id": "in_1A2B3C4D5E6F7G8H",
"object": "invoice",
"amount_due": 2000,
"amount_paid": 0,
"amount_remaining": 2000,
"currency": "usd",
"customer": "cus_ABCDEFGHIJKL",
"status": "open",
"metadata": {
"order_id": "ord_12345",
"source": "web"
}
}
},
"livemode": false,
"type": "invoice.payment_failed",
"request": {
"id": "req_1A2B3C4D5E6F7G",
"idempotency_key": "idem_abcdef123456"
}
}
Stored at samples/stripe/invoice_payment_failed.json.
3.2 Invalid Variants
| Variant | Mutation | Expected Behaviour |
|---|---|---|
metadata_missing | Remove data.object.metadata | Handler logs warning, continues processing |
amount_negative | Set amount_due: -500 | Validation rejects with 400, error logged |
signature_invalid | Corrupt Stripe-Signature header | Middleware returns 401, no DB write |
idempotency_duplicate | Re‑use idem_abcdef123456 in two requests | Second request returns 409, no double‑processing |
timestamp_future | created: 9999999999 | Rejected as stale/future event |
Generation tip: Use the QA3 test‑data generator (/tools/test-data-generator) with a JSON Schema for the Stripe event. Enable “mutate” mode to automatically produce the five variants above, then commit them under samples/stripe/invalid/.
3.3 Replay Capture
- Enable request logging in your staging ingress (e.g., NGINX
access_logwith$request_body). - Filter for
type=invoice.payment_failed. - Export the raw bodies to
captures/2024-03-12/stripe_invoice_payment_failed_001.json. - Redact PII (customer emails, card tokens) using a script that scrubs known fields.
- Add the capture to the catalogue as a replay source.
When a regression appears (e.g., a new Stripe version adds payment_intent), you can re‑run the captured payload against the updated handler to verify backward compatibility without waiting for a live event.
4. Tool Considerations
| Category | Options | Strengths | Limits |
|---|---|---|---|
| Schema‑driven generators | json-schema-faker, quicktype + custom script, QA3 generator | Guarantees structural validity, easy to extend | Requires up‑to‑date schema |
| Fuzzing / mutation engines | radamsa, go-fuzz, hypothesis (Python) | Finds obscure parser bugs | May produce semantically nonsense payloads |
| Traffic capture & replay | mitmproxy + mitmdump, wiremock record/playback, hoverfly | Real‑world fidelity, supports binary protos | Needs secure storage, PII handling |
| Contract testing | pact, spring-cloud-contract | Guarantees provider/consumer alignment | Overhead for many third‑party webhooks |
| CI integration | GitHub Actions matrix, GitLab parallel:matrix, Jenkins pipeline | Runs full matrix on every PR | Execution time grows with variant count |
Practical recommendation:
- Start with a schema‑driven generator for valid data.
- Layer a mutation step for invalid data (the QA3 generator can do both).
- Add a nightly job that pulls the latest captures from staging and stores them as replay fixtures.
5. Validation Checks in Depth
5.1 JSON Schema Validation
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Stripe Invoice Payment Failed",
"type": "object",
"required": ["id", "type", "data", "created"],
"properties": {
"id": { "type": "string", "pattern": "^evt_[A-Za-z0-9]{16}$" },
"type": { "const": "invoice.payment_failed" },
"created": { "type": "integer", "minimum": 1400000000 },
"data": {
"type": "object",
"required": ["object"],
"properties": {
"object": {
"type": "object",
"required": ["id", "amount_due", "currency", "customer", "metadata"],
"properties": {
"id": { "type": "string", "pattern": "^in_[A-Za-z0-9]{16}$" },
"amount_due": { "type": "integer", "minimum": 0 },
"currency": { "type": "string", "enum": ["usd", "eur", "gbp"] },
"customer": { "type": "string", "pattern": "^cus_[A-Za-z0-9]{14}$" },
"metadata": { "type": "object" }
}
}
}
}
}
}
Run with ajv validate -s schema.json -d samples/stripe/invoice_payment_failed.json. Any failure stops the pipeline.
5.2 Signature Verification
Most providers sign the raw request body with a secret. In tests:
import hmac, hashlib, base64
def verify_stripe_signature(payload: bytes, header: str, secret: str) -> bool:
# header format: t=timestamp,v1=signature
parts = dict(part.split("=") for part in header.split(","))
signed_payload = f"{parts['t']}.{payload.decode()}".encode()
expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts['v1'])
Add a unit test that feeds the valid payload with a correct header, then the invalid payload with a corrupted header.
5.3 Idempotency Keys
Store every processed request.idempotency_key in a Redis set with a TTL of 24 h. In the test harness:
func TestIdempotencyDuplicate(t *testing.T) {
key := "idem_abcdef123456"
// first call
resp1 := postWebhook(validPayload, key)
assert.Equal(t, 200, resp1.Code)
// second call with same key
resp2 := postWebhook(validPayload, key)
assert.Equal(t, 409, resp2.Code)
}
5.4 Timestamp Freshness
Define a configurable window (e.g., ±5 minutes). Reject events outside the window before any business logic runs. This prevents replay attacks and stale queue processing.
const MAX_AGE_MS = 5 * 60 * 1000;
function isFresh(created) {
const now = Date.now() / 1000; // Stripe uses seconds
return Math.abs(now - created) <= MAX_AGE_MS / 1000;
}
6. Pitfalls & Mitigations
| Pitfall | Symptom | Mitigation |
|---|---|---|
| Schema drift – provider adds a field but your schema stays static | Valid payloads start failing validation | Schedule a monthly schema sync: pull the latest OpenAPI/JSON Schema from the provider, diff, update catalogue |
| Over‑mutating – fuzzer creates payloads that never occur in reality | Test suite explodes with false positives | Constrain mutations to spec‑defined error codes and business‑rule boundaries (e.g., negative amounts, missing required objects) |
| PII leakage in replay captures | Production data appears in test repo | Automate redaction in the capture pipeline; store only hashed identifiers |
| Flaky signature verification – clock skew between test runner and provider | Intermittent 401s | Mock the provider’s signing clock or use a fixed timestamp in test payloads |
| Idempotency key collisions across test runs | 409 errors in parallel CI jobs | Prefix keys with build ID (${GITHUB_RUN_ID}_${key}) or use a per‑run Redis namespace |
| Replay data becomes stale – business logic changes, old captures no longer valid | Regression tests pass but hide new bugs | Tag captures with the code version they were recorded against; retire captures older than two major releases |
7. Scaling the Approach
7.1 Matrix Expansion
When you support multiple accounts, regions, or feature flags, the Cartesian product can explode. Use parameterised templates:
# template.yaml
event: "invoice.payment_failed"
account_id: "{{ account }}"
region: "{{ region }}"
metadata:
order_id: "ord_{{ order }}"
source: "{{ source }}"
Render with a small script that iterates over a CSV of accounts/regions. Commit only the template and the parameter file; generated JSON lives in generated/ and is git‑ignored.
7.2 Contract Testing with Providers
If a provider publishes a Pact contract, import it as a JSON Schema source. Your generator then guarantees that every valid payload satisfies the contract. For providers without contracts, treat the official documentation as the source of truth and version it in the catalogue.
7.3 Observability‑Driven Test Data
Instrument your webhook endpoint with structured logs (event_type, processing_time_ms, validation_result). Periodically query the logs for rare validation failures and promote those payloads into the invalid catalogue. This creates a feedback loop: production anomalies become test cases automatically.
8. Checklist for a New Webhook Integration
- Add entry to Test‑Data Catalogue (event ID, provider, spec version).
- Obtain official JSON Schema or write one from docs.
- Generate baseline valid sample (store under
samples/<provider>/). - Run schema validation in CI.
- Create invalid variants covering: missing required fields, type mismatches, out‑of‑range values, signature tampering, duplicate idempotency keys, stale timestamps.
- Implement signature verification test (valid + invalid).
- Enable request capture in staging; schedule nightly export.
- Redact PII and commit replay fixtures under
captures/<date>/. - Add replay test that re‑posts each
Read more
Idempotency Test Data for Safe API Retry Testing
A practical guide to “Idempotency Test Data for Safe API Retry Testing,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.
Rate-Limit Test Data for 429 and Retry-After Validation
A practical guide to “Rate-Limit Test Data for 429 and Retry-After Validation,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.
API Pagination Test Data: Page, Cursor, and Offset Scenarios
A practical guide to “API Pagination Test Data: Page, Cursor, and Offset Scenarios,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.