Skip to content

Testing LLM API Without Real Requests: Mock Server and Fixtures

Summary

Setting up a local mock server that mimics LLM API responses to test integrations without real calls and costs.

Why Use a Mock Server

Real LLM API calls cost money, depend on network conditions, and are non-deterministic. For unit tests, CI/CD, and development, it's convenient to replace the API with a mock. A mock server returns pre-prepared responses, making tests fast and reproducible.

Step 1. Define Response Format

First, I fix the response structure of the provider. For OpenAI-compatible APIs, this is JSON of the form:

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1700000000,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello!"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 5,
    "total_tokens": 15
  }
}

For DeepSeek, OpenRouter, and other providers, the format is usually compatible with OpenAI. I check the specific API documentation.

Step 2. Create a Mock Server in Python

I use the standard library http.server or FastAPI. A minimal FastAPI example:

from fastapi import FastAPI, Request
from pydantic import BaseModel

app = FastAPI()

class ChatRequest(BaseModel):
    model: str
    messages: list[dict]
    temperature: float | None = None

@app.post("/v1/chat/completions")
async def chat_completion(req: ChatRequest):
    # Logic for selecting fixture based on request content
    content = "This is a mock response"
    return {
        "id": "chatcmpl-mock",
        "object": "chat.completion",
        "created": 1700000000,
        "model": req.model,
        "choices": [{"index": 0, "message": {"role": "assistant", "content": content}, "finish_reason": "stop"}],
        "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
    }

Run the server: uvicorn mock_server:app --port 8000.

Step 3. Generate Fixtures

Fixtures are saved API responses. I collect them manually or with a real call once and save them to a file. Example fixture fixtures/hello.json:

{
  "request": {
    "model": "gpt-4o-mini",
    "messages": [{"role": "user", "content": "Hello"}]
  },
  "response": {
    "choices": [{"message": {"content": "Hi there!"}}]
  }
}

In the mock server, I match the request with the fixture by key fields: model and the last user message.

Step 4. Connect Mock to Client

In the client code, I specify the base URL of the mock server through an environment variable:

import os
from openai import OpenAI

client = OpenAI(
    api_key="test-key",
    base_url=os.getenv("LLM_BASE_URL", "http://localhost:8000/v1")
)

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)

In tests, I set LLM_BASE_URL=http://localhost:8000/v1.

Step 5. Add Delays and Errors

To test timeouts and retries, the mock server can simulate delays or return errors:

import asyncio
from fastapi import HTTPException

@app.post("/v1/chat/completions")
async def chat_completion(req: ChatRequest):
    if req.messages[-1]["content"] == "error":
        raise HTTPException(status_code=429, detail="Rate limit exceeded")
    await asyncio.sleep(0.5)  # simulate delay
    return {...}

Step 6. Integrate with CI/CD

In GitHub Actions, I run the mock server as a separate service:

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      mock-llm:
        image: python:3.12
        ports:
          - 8000:8000
        options: >-
          --health-cmd "curl -f http://localhost:8000/health"
    steps:
      - uses: actions/checkout@v4
      - run: pip install -r requirements.txt
      - run: uvicorn mock_server:app --host 0.0.0.0 --port 8000 &
      - run: pytest

Step 7. Check Scenario Coverage

I compile a list of scenarios that should be covered by fixtures:

Scenario Expected Response
Normal request Correct text
Empty response Empty string
Error 429 HTTP 429
Timeout Delay > 10 sec
Invalid JSON HTTP 400

Conclusion

A mock server allows testing integrations with LLM API without costs and instability. Fixtures make tests deterministic, and error simulation checks error handling. More on retries and timeouts in the post llm-api-timeout-retry, on abuse protection in the guide llm-api-cost-protection.