Generate Failure-Mode Integration Tests for External API Clients

Get a deterministic integration test suite for any external API client covering timeouts, 429 rate limits, malformed JSON, and retry backoff without hitting live endpoints.

Agent prompt for ChatGPT and Claude

You get: Test Matrix, integration Test Suite and verification Commands

Prompt

Prompt
Act as a senior backend reliability engineer who specializes in resilient HTTP clients and deterministic test suites.

Write failure-mode integration tests for the external API client code I paste below. Infer the language, test runner, and HTTP mocking library from my imports. Only ask up to 2 short questions first if retry limits or timeout values are missing from the code.

Rules:
- Cover five failure modes: read timeout, HTTP 429 with Retry-After, HTTP 503 recovering on retry, malformed JSON on HTTP 200, and non-retryable HTTP 401.
- Mock traffic at the HTTP transport layer so zero live requests leave the machine and tests stay deterministic offline.
- Stub sleep or clock calls so backoff and Retry-After delays are verified by exact duration without slowing execution.
- Assert both the final exception or return value and the exact HTTP attempt count.

Output format:
1. Test Matrix: a table with columns Failure Mode, Mocked Response, Expected Attempts, and Expected Outcome.
2. Integration Test Suite: complete, runnable test code with idiomatic fixtures and zero skipped tests.
3. Verification Commands: exact CLI commands to run the suite and confirm offline isolation.

End with one line noting any timeout, retry, or circuit-breaker assumptions not visible in the pasted client code.

Example output

Expected attempts per failure modeEach failure mode is mocked, so no live API calls are made
  • Read timeout: 3
  • Rate limit (429): 2
  • Transient 503: 3
  • Malformed JSON: 1
  • Unauthorized (401): 1

Example for: a Python billing client using httpx and pytest that fetches invoice statuses from a third-party payments API.

1. Test Matrix
Failure ModeMocked ResponseExpected AttemptsExpected Outcome
Read timeouthttpx.ReadTimeout on all calls3Raises BillingTimeoutError
Rate limit (429)429 with Retry-After: 4, then 2002Sleeps 4s and returns invoice dict
Transient 503503 twice, then 2003Sleeps 1s, 2s and returns invoice dict
Malformed JSON200 with truncated body1Raises BillingParseError
Unauthorized (401)401 with auth error body1Raises BillingAuthError immediately
2. Integration Test Suite
from unittest.mock import patch
import httpx
import pytest
import respx
from billing_client import BillingClient, BillingAuthError, BillingParseError, BillingTimeoutError

BASE_URL = "https://api.payledger.example"
INVOICE_URL = "https://api.payledger.example/v1/invoices/inv_9042"

@pytest.fixture
def client():
    return BillingClient(base_url=BASE_URL, api_key="sk_test_001", max_retries=2)

@respx.mock
@patch("billing_client.time.sleep")
def test_read_timeout_exhausts_retries(mock_sleep, client):
    route = respx.get(INVOICE_URL).mock(side_effect=httpx.ReadTimeout("timed out"))
    with pytest.raises(BillingTimeoutError):
        client.get_invoice("inv_9042")
    assert route.call_count == 3
    assert [c.args[0] for c in mock_sleep.call_args_list] == [1, 2]

@respx.mock
@patch("billing_client.time.sleep")
def test_rate_limit_honors_retry_after(mock_sleep, client):
    route = respx.get(INVOICE_URL).mock(side_effect=[
        httpx.Response(429, headers=dict([("Retry-After", "4")])),
        httpx.Response(200, json=dict(id="inv_9042", status="paid")),
    ])
    result = client.get_invoice("inv_9042")
    assert result["status"] == "paid"
    assert route.call_count == 2
    mock_sleep.assert_called_once_with(4)

@respx.mock
@patch("billing_client.time.sleep")
def test_503_recovers_with_exponential_backoff(mock_sleep, client):
    route = respx.get(INVOICE_URL).mock(side_effect=[
        httpx.Response(503),
        httpx.Response(503),
        httpx.Response(200, json=dict(id="inv_9042", status="open")),
    ])
    result = client.get_invoice("inv_9042")
    assert result["status"] == "open"
    assert route.call_count == 3
    assert [c.args[0] for c in mock_sleep.call_args_list] == [1, 2]

@respx.mock
def test_malformed_json_raises_parse_error(client):
    route = respx.get(INVOICE_URL).mock(return_value=httpx.Response(200, text="not-valid-json"))
    with pytest.raises(BillingParseError):
        client.get_invoice("inv_9042")
    assert route.call_count == 1

@respx.mock
def test_401_fails_without_retry(client):
    route = respx.get(INVOICE_URL).mock(return_value=httpx.Response(401))
    with pytest.raises(BillingAuthError):
        client.get_invoice("inv_9042")
    assert route.call_count == 1
3. Verification Commands
pytest tests/test_billing_client.py -v --disable-socket

Assumptions: backoff is deterministic without random jitter, Retry-After is parsed as integer seconds, and no circuit breaker state persists across calls.

Written by AI from this prompt. Your results will vary.

Tips and common edits

Why this works

  • Forces transport-layer HTTP mocking so tests never depend on flaky sandboxes or live third-party rate limits.
  • Requires stubbing sleep calls and asserting exact attempt counts, catching hidden retry loops without slowing CI.
  • Separates retryable 429 and 503 errors from non-retryable 401 and malformed JSON failures in a clear test matrix.

Use this in GitHub Copilot Chat, ChatGPT, or Claude before shipping a new third-party API wrapper. Paste your client class or module right after the prompt so the model can match your imports and exception types.

Common edits

  • Add a sixth failure mode for HTTP 429 with an HTTP-date Retry-After header if your upstream API uses timestamps.
  • Specify your exact mocking library, such as MSW for TypeScript or WireMock for Java, in the first line.

Reuse it: Use in a workflowAdapt in the builder

Parenting & Family

Help an elementary child handle losing or feeling left out

Get practical scripts and emotion-regulation steps to support an elementary-age child after rejection, social exclusion, or losing a game.