Quality is not optional. It's our standard. Free QA tools for testers and developers.

Webhook Test Data: Valid, Invalid, and Replay Scenarios

QTQA3 Team

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:

FamilyGoalTypical Sources
ValidExercise the normal code path, confirm schema compliance, verify business logicProduction samples, provider documentation, sandbox environments
InvalidSurface validation gaps, error‑handling branches, security regressionsMutated valid payloads, spec‑defined error codes, fuzzing tools
ReplayRe‑create exact historic events for regression, debugging, or compliance auditsCaptured 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_failed handler. The unit tests pass, but the staging deployment threw a 500 when a malformed metadata object 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:

  1. Cataloguing every event type your system consumes.
  2. Defining a baseline valid payload for each type.
  3. Deriving systematic invalid variations.
  4. Capturing real‑world events for replay scenarios.

2. Decision Criteria & Workflow

2.1 Choose a Representation Format

FormatWhen to UseTooling
JSON files (one per event)Small‑to‑medium test suites, version‑controlledGit, any editor
YAML + templatingNeed for parameterised fields (e.g., timestamps, IDs)jinja2, helm‑style templates
Programmatic generators (Python, Go, JS)Large matrices, dynamic values, CI integrationCustom scripts, QA3 test‑data generator
Recorded traffic (HAR, pcap, OpenAPI examples)Replay fidelity, compliance evidencemitmproxy, 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 IDProviderSpec VersionValid Sample PathInvalid VariantsReplay Source
stripe.invoice.payment_failedStripe2023‑10‑16samples/stripe/invoice_payment_failed.jsonmetadata_missing, amount_negative, signature_invalidcaptures/2024‑03‑12/
github.pull_request.openedGitHub2024‑01‑01samples/github/pr_opened.jsonbase_ref_null, head_sha_malformedcaptures/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)

CheckTool / MethodPass Criteria
Schema conformanceJSON Schema (ajv, jsonschema), OpenAPI validatorNo validation errors
Signature verificationProvider SDK or HMAC re‑calculationSignature matches header
Idempotency key uniquenessIn‑memory set or DB unique constraintNo duplicate key in test run
Timestamp freshnessCompare created/event_time to now ± 5 minWithin window
Required business fieldsCustom rule engine (e.g., amount > 0)All rules true
Size limitsContent‑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

VariantMutationExpected Behaviour
metadata_missingRemove data.object.metadataHandler logs warning, continues processing
amount_negativeSet amount_due: -500Validation rejects with 400, error logged
signature_invalidCorrupt Stripe-Signature headerMiddleware returns 401, no DB write
idempotency_duplicateRe‑use idem_abcdef123456 in two requestsSecond request returns 409, no double‑processing
timestamp_futurecreated: 9999999999Rejected 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

  1. Enable request logging in your staging ingress (e.g., NGINX access_log with $request_body).
  2. Filter for type=invoice.payment_failed.
  3. Export the raw bodies to captures/2024-03-12/stripe_invoice_payment_failed_001.json.
  4. Redact PII (customer emails, card tokens) using a script that scrubs known fields.
  5. 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

CategoryOptionsStrengthsLimits
Schema‑driven generatorsjson-schema-faker, quicktype + custom script, QA3 generatorGuarantees structural validity, easy to extendRequires up‑to‑date schema
Fuzzing / mutation enginesradamsa, go-fuzz, hypothesis (Python)Finds obscure parser bugsMay produce semantically nonsense payloads
Traffic capture & replaymitmproxy + mitmdump, wiremock record/playback, hoverflyReal‑world fidelity, supports binary protosNeeds secure storage, PII handling
Contract testingpact, spring-cloud-contractGuarantees provider/consumer alignmentOverhead for many third‑party webhooks
CI integrationGitHub Actions matrix, GitLab parallel:matrix, Jenkins pipelineRuns full matrix on every PRExecution 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

PitfallSymptomMitigation
Schema drift – provider adds a field but your schema stays staticValid payloads start failing validationSchedule 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 realityTest suite explodes with false positivesConstrain mutations to spec‑defined error codes and business‑rule boundaries (e.g., negative amounts, missing required objects)
PII leakage in replay capturesProduction data appears in test repoAutomate redaction in the capture pipeline; store only hashed identifiers
Flaky signature verification – clock skew between test runner and providerIntermittent 401sMock the provider’s signing clock or use a fixed timestamp in test payloads
Idempotency key collisions across test runs409 errors in parallel CI jobsPrefix 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 validRegression tests pass but hide new bugsTag 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.