How do you write unit tests for LLM API integrations using deterministic recorded HTTP fixtures (VCR/Polly)? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you write unit tests for LLM API integrations using deterministic recorded HTTP fixtures (VCR/Polly)?

message-square
0

How Deterministic Recorded HTTP Fixtures (VCR/Polly) Work for LLM Tests

Testing LLM orchestration code against live APIs in CI is slow, expensive, non-deterministic, and prone to rate limits or network flakiness. Recording and replaying HTTP traffic—using tools like Polly.JS in Node.js/TypeScript or VCR / pytest-recording in Python—captures real request/response payloads (including SSE streaming chunks and tool-call responses) as committed fixture files so CI runs offline with exact, reproducible wire responses.

  • Real wire serialization vs. hand-rolled mocks: Hand-written mock objects often drift away from real SDK/provider shapes (such as SSE chunk framing, usage blocks, or tool_calls IDs), whereas recorded fixtures preserve real HTTP headers, status codes, and payload structures while still exercising your actual SDK client and parser code.
  • Deterministic request matching: Because LLM requests include fields like timestamps, nonces, or dynamic IDs, fixture matchers must normalize or ignore volatile headers/fields (Authorization, x-request-id, timestamps) while matching semantically meaningful inputs (model, messages, tools, stream).
  • Record-once, replay-in-CI workflow: Fixtures are recorded intentionally during development or schema upgrades, scrubbed of secrets (Bearer tokens, api-key headers), and replayed deterministically in CI without live API credentials.

Steps to Test LLM Integrations with Recorded HTTP Fixtures

  1. Choose a recorder matching your runtime and transport: Use Polly.JS (@pollyjs/core, @pollyjs/node-http or @pollyjs/adapter-fetch) for Node.js/TypeScript fetch/HTTP clients (or MSW with recorded JSON/SSE fixtures), and VCR.py / pytest-recording for Python.
  2. Configure secret scrubbing and deterministic request matchers: Strip API keys and cookies before writing fixture files to disk, and configure body/header matchers so Authorization headers do not break fixture matching when keys rotate.
  3. Record normal, streaming, tool-calling, and error fixtures: Capture real responses for standard completions, SSE streams (stream: true), tool_calls responses, and 429/500/524 error states so retry, rate-limit, and schema-validation logic are all tested deterministically.
  4. Lock CI to replay mode (replay / fail on missing recording): Run CI with recording disabled so any unrecorded network call fails loudly instead of silently hitting a live endpoint or hanging.

TypeScript Example: Deterministic Fixture Replay with Polly.JS and Vitest/Jest

import { Polly } from "@pollyjs/core";
import NodeHttpAdapter from "@pollyjs/adapter-node-http";
import FetchAdapter from "@pollyjs/adapter-fetch";
import FSPersister from "@pollyjs/persister-fs";
import OpenAI from "openai";
import path from "node:path";

Polly.register(NodeHttpAdapter);
Polly.register(FetchAdapter);
Polly.register(FSPersister);

export interface CreatePollyOptions {
  recordingName: string;
  mode?: "replay" | "record";
  fixturesDir?: string;
}

export function startLlmFixturePolly({
  recordingName,
  mode = process.env.RECORD_LLM_FIXTURES === "true" ? "record" : "replay",
  fixturesDir = path.resolve(process.cwd(), "__fixtures__/llm"),
}: CreatePollyOptions): Polly {
  const polly = new Polly(recordingName, {
    mode,
    adapters: ["node-http", "fetch"],
    persister: "fs",
    persisterOptions: {
      fs: {
        recordingsDir: fixturesDir,
      },
    },
    matchRequestsBy: {
      headers: false,
      method: true,
      url: true,
      body(body) {
        if (!body) return "";
        try {
          const parsed = JSON.parse(body);
          // Strip volatile/non-semantic fields if any exist in wrapper payloads
          delete parsed.request_id;
          return JSON.stringify(parsed);
        } catch {
          return body;
        }
      },
    },
  });

  // Scrub sensitive credentials and non-deterministic headers before persisting to disk
  polly.server.any().on("beforePersist", (_req, recording) => {
    recording.request.headers = recording.request.headers.filter(
      (h: { name: string }) =>
        !["authorization", "x-api-key", "api-key", "cookie"].includes(h.name.toLowerCase())
    );
    recording.response.headers = recording.response.headers.filter(
      (h: { name: string }) => !["cf-ray", "x-request-id", "date"].includes(h.name.toLowerCase())
    );
  });

  return polly;
}

export async function fetchOrderSummary(client: OpenAI, orderId: string): Promise<string> {
  const res = await client.chat.completions.create({
    model: "gpt-4o-mini",
    temperature: 0,
    messages: [
      { role: "system", content: "Return a concise status string." },
      { role: "user", content: `Summarize order \${orderId}` },
    ],
  });

  return res.choices[0]?.message.content?.trim() ?? "";
}

// Example test usage (e.g. inside Vitest or Jest):
// const polly = startLlmFixturePolly({ recordingName: "order-summary/ord-1001" });
// const client = new OpenAI({ apiKey: "test-key-ignored-in-replay" });
// const summary = await fetchOrderSummary(client, "ORD-1001");
// await polly.stop();

Helpful Tips for Production LLM Fixture Testing

  • Never commit raw API keys or PII into fixture files: Always sanitize Authorization headers and scrub sensitive user/customer data in beforePersist before pushing recordings to Git.
  • Verify SSE streaming chunks and timing-independent behavior: When recording streaming completions, ensure your adapter/persister preserves chunk boundaries and final usage chunks so stream-assembly and token-reconciliation code run against realistic multi-chunk payloads.
  • Keep fixtures focused and refresh intentionally: Store small, readable fixtures per scenario (success, tool-call, rate-limit-429, malformed-json) and re-record only when prompts, schemas, or SDK wire formats intentionally change.