LiteLLM Testing Guide: Proxy, Model Routing, Fallbacks, and Mock Testing

LiteLLM Testing Guide: Proxy, Model Routing, Fallbacks, and Mock Testing

LiteLLM is the Swiss army knife of LLM integration — it provides a unified OpenAI-compatible API across 100+ models from OpenAI, Anthropic, Mistral, Groq, and beyond. But with great abstraction comes great testing responsibility. When your proxy routes between models, applies fallbacks, and enforces rate limits, every configuration decision needs verification.

This guide covers how to test LiteLLM deployments thoroughly: from unit-testing routing logic to integration-testing the proxy server itself.

What Makes LiteLLM Testing Different

Testing LiteLLM isn't just testing an API call — it's testing a policy engine. Your LiteLLM config defines:

  • Model aliases: gpt-4 might actually route to claude-3-5-sonnet
  • Fallback chains: if gpt-4 fails, try gpt-3.5-turbo, then mistral-medium
  • Rate limit enforcement: per-key, per-model, per-user budgets
  • Caching: semantic cache, exact-match cache
  • Callbacks: logging, alerting, cost tracking

Each of these is a testable behavior, not just configuration.

Setting Up Your Test Environment

Install dependencies:

pip install litellm pytest pytest-asyncio httpx respx

For proxy server testing:

pip install litellm[proxy] docker

Basic pytest configuration in conftest.py:

import pytest
import os
from unittest.mock import patch, MagicMock

@pytest.fixture(autouse=True)
def mock_env_vars(monkeypatch):
    """Prevent real API calls during tests."""
    monkeypatch.setenv("OPENAI_API_KEY", "test-key-openai")
    monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key-anthropic")
    monkeypatch.setenv("GROQ_API_KEY", "test-key-groq")

@pytest.fixture
def mock_litellm_response():
    """Standard mock LLM response."""
    mock = MagicMock()
    mock.choices = [MagicMock()]
    mock.choices[0].message.content = "Test response"
    mock.choices[0].message.role = "assistant"
    mock.usage.prompt_tokens = 10
    mock.usage.completion_tokens = 20
    mock.usage.total_tokens = 30
    mock.model = "gpt-3.5-turbo"
    return mock

Testing Basic LiteLLM Completion Calls

Start with the fundamentals — verifying your wrapper around litellm.completion:

import pytest
import litellm
from unittest.mock import patch, MagicMock

def test_basic_completion_call(mock_litellm_response):
    """Test that completion calls succeed with expected structure."""
    with patch("litellm.completion", return_value=mock_litellm_response) as mock_call:
        response = litellm.completion(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": "Hello"}]
        )
        
        mock_call.assert_called_once()
        assert response.choices[0].message.content == "Test response"
        assert response.usage.total_tokens == 30

def test_completion_passes_correct_model():
    """Verify model name is passed through correctly."""
    with patch("litellm.completion") as mock_completion:
        mock_completion.return_value = MagicMock(
            choices=[MagicMock(message=MagicMock(content="ok"))]
        )
        
        litellm.completion(
            model="claude-3-5-sonnet-20241022",
            messages=[{"role": "user", "content": "test"}]
        )
        
        call_kwargs = mock_completion.call_args.kwargs
        assert call_kwargs["model"] == "claude-3-5-sonnet-20241022"

@pytest.mark.asyncio
async def test_async_completion():
    """Test async completion works correctly."""
    mock_response = MagicMock()
    mock_response.choices = [MagicMock()]
    mock_response.choices[0].message.content = "Async response"
    
    with patch("litellm.acompletion", return_value=mock_response):
        response = await litellm.acompletion(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": "Hello async"}]
        )
        assert response.choices[0].message.content == "Async response"

Testing Model Routing Configuration

LiteLLM's model aliasing is powerful but needs explicit validation:

import yaml
import pytest
from pathlib import Path

@pytest.fixture
def litellm_config():
    """Load LiteLLM config for testing."""
    config_path = Path(__file__).parent / "litellm_config.yaml"
    with open(config_path) as f:
        return yaml.safe_load(f)

def test_model_aliases_defined(litellm_config):
    """All required model aliases must be configured."""
    required_aliases = ["gpt-4", "gpt-3.5-turbo", "claude-3-opus", "embedding-model"]
    model_names = [m["model_name"] for m in litellm_config["model_list"]]
    
    for alias in required_aliases:
        assert alias in model_names, f"Required alias '{alias}' not in model_list"

def test_each_model_has_litellm_params(litellm_config):
    """Each model entry must have litellm_params with model field."""
    for model_entry in litellm_config["model_list"]:
        assert "litellm_params" in model_entry, \
            f"Model '{model_entry['model_name']}' missing litellm_params"
        assert "model" in model_entry["litellm_params"], \
            f"Model '{model_entry['model_name']}' missing litellm_params.model"

def test_production_models_use_correct_providers(litellm_config):
    """Validate that production model aliases route to expected providers."""
    model_map = {
        entry["model_name"]: entry["litellm_params"]["model"]
        for entry in litellm_config["model_list"]
    }
    
    # gpt-4 alias should route to OpenAI or a compatible provider
    assert model_map.get("gpt-4", "").startswith(("openai/", "azure/", "gpt-"))
    
    # Embedding model should be a real embedding model
    embedding_model = model_map.get("embedding-model", "")
    assert any(provider in embedding_model for provider in [
        "text-embedding", "embed", "ada"
    ])

Testing Fallback Chains

Fallbacks are the most critical LiteLLM feature — they're your resilience layer:

import litellm
import pytest
from unittest.mock import patch, MagicMock, side_effect

def make_error_response(error_type="rate_limit"):
    """Create mock LiteLLM exceptions."""
    if error_type == "rate_limit":
        return litellm.RateLimitError(
            message="Rate limit exceeded",
            llm_provider="openai",
            model="gpt-4"
        )
    elif error_type == "api_error":
        return litellm.APIError(
            status_code=500,
            message="Internal server error",
            llm_provider="openai",
            model="gpt-4"
        )

def test_fallback_triggers_on_rate_limit():
    """When primary model hits rate limit, fallback model should be used."""
    primary_error = make_error_response("rate_limit")
    fallback_response = MagicMock()
    fallback_response.choices = [MagicMock()]
    fallback_response.choices[0].message.content = "Fallback response"
    fallback_response.model = "gpt-3.5-turbo"
    
    call_count = [0]
    
    def mock_completion(**kwargs):
        call_count[0] += 1
        if kwargs.get("model") == "gpt-4":
            raise primary_error
        return fallback_response
    
    with patch("litellm.completion", side_effect=mock_completion):
        response = litellm.completion(
            model="gpt-4",
            messages=[{"role": "user", "content": "test"}],
            fallbacks=["gpt-3.5-turbo"]
        )
        
        assert response.model == "gpt-3.5-turbo"
        assert response.choices[0].message.content == "Fallback response"

def test_fallback_chain_exhaustion_raises():
    """When all fallbacks fail, exception should propagate."""
    error = litellm.ServiceUnavailableError(
        message="Service unavailable",
        llm_provider="openai",
        model="gpt-4"
    )
    
    with patch("litellm.completion", side_effect=error):
        with pytest.raises(litellm.ServiceUnavailableError):
            litellm.completion(
                model="gpt-4",
                messages=[{"role": "user", "content": "test"}],
                fallbacks=["gpt-3.5-turbo", "mistral-medium"],
                # No actual fallback logic in mock — all calls raise
            )

def test_context_window_fallback():
    """Long context should route to context-window-appropriate model."""
    context_error = litellm.ContextWindowExceededError(
        message="Context length exceeded",
        model="gpt-3.5-turbo",
        llm_provider="openai"
    )
    
    long_context_response = MagicMock()
    long_context_response.choices = [MagicMock()]
    long_context_response.choices[0].message.content = "Handled long context"
    long_context_response.model = "gpt-4-turbo"
    
    def mock_completion(**kwargs):
        if kwargs.get("model") == "gpt-3.5-turbo":
            raise context_error
        return long_context_response
    
    with patch("litellm.completion", side_effect=mock_completion):
        # LiteLLM context_window_fallbacks feature
        response = litellm.completion(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": "very long message..."}],
            context_window_fallbacks=[{"gpt-3.5-turbo": ["gpt-4-turbo"]}]
        )
        
        assert "gpt-4" in response.model

Testing the LiteLLM Proxy Server

The proxy server deserves its own integration test suite. Spin it up with Docker:

import pytest
import httpx
import subprocess
import time
import os
from pathlib import Path

@pytest.fixture(scope="session")
def litellm_proxy(tmp_path_factory):
    """Start LiteLLM proxy for integration tests."""
    config_content = """
model_list:
  - model_name: gpt-3.5-turbo
    litellm_params:
      model: openai/gpt-3.5-turbo
      api_key: fake-test-key

litellm_settings:
  drop_params: true
  set_verbose: false
"""
    tmp_dir = tmp_path_factory.mktemp("litellm")
    config_file = tmp_dir / "config.yaml"
    config_file.write_text(config_content)
    
    proc = subprocess.Popen(
        ["litellm", "--config", str(config_file), "--port", "4000", "--num_workers", "1"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env={**os.environ, "OPENAI_API_KEY": "sk-test"}
    )
    
    # Wait for proxy to start
    for _ in range(30):
        try:
            httpx.get("http://localhost:4000/health/readiness", timeout=1)
            break
        except Exception:
            time.sleep(1)
    
    yield "http://localhost:4000"
    proc.terminate()

def test_proxy_health_endpoint(litellm_proxy):
    """Proxy health endpoint should return healthy status."""
    response = httpx.get(f"{litellm_proxy}/health/readiness")
    assert response.status_code == 200

def test_proxy_model_list(litellm_proxy):
    """Proxy should expose configured models."""
    response = httpx.get(f"{litellm_proxy}/v1/models")
    assert response.status_code == 200
    models = response.json()["data"]
    model_ids = [m["id"] for m in models]
    assert "gpt-3.5-turbo" in model_ids

Testing Cost Tracking and Budget Enforcement

Budget enforcement is a critical production concern:

def test_budget_limit_raises_error():
    """Calls exceeding budget should raise BudgetExceededError."""
    import litellm
    
    # Configure a very low budget
    litellm.max_budget = 0.000001  # $0.000001 — will be exceeded immediately
    
    response = MagicMock()
    response.usage.total_tokens = 1000  # Will calculate high cost
    response.choices = [MagicMock()]
    
    with patch("litellm.completion", return_value=response):
        # In a real scenario, LiteLLM tracks cumulative spend
        # Test that your wrapper enforces budgets
        pass
    
    # Reset budget
    litellm.max_budget = None

def test_cost_calculation_per_model():
    """Verify cost calculation uses correct per-model pricing."""
    cost = litellm.completion_cost(
        model="gpt-3.5-turbo",
        prompt_tokens=1000,
        completion_tokens=500
    )
    
    # GPT-3.5-turbo pricing: ~$0.001/1K input, $0.002/1K output
    assert cost > 0
    assert cost < 0.01  # Sanity check — shouldn't be absurdly high

def test_streaming_response_cost_calculated():
    """Streaming responses should also track token usage."""
    chunks = []
    
    mock_stream = iter([
        MagicMock(
            choices=[MagicMock(delta=MagicMock(content="Hello"))],
            usage=None
        ),
        MagicMock(
            choices=[MagicMock(delta=MagicMock(content=" world"))],
            usage=MagicMock(prompt_tokens=5, completion_tokens=2, total_tokens=7)
        )
    ])
    
    with patch("litellm.completion", return_value=mock_stream):
        stream = litellm.completion(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": "Hi"}],
            stream=True
        )
        
        for chunk in stream:
            chunks.append(chunk)
        
        assert len(chunks) == 2

Testing Caching Behavior

LiteLLM's caching layer is invaluable for cost control but needs careful testing:

import litellm
from litellm.caching import Cache
from unittest.mock import patch, MagicMock

@pytest.fixture
def in_memory_cache():
    """Set up in-memory cache for testing."""
    litellm.cache = Cache(type="local")
    yield litellm.cache
    litellm.cache = None

def test_identical_requests_use_cache(in_memory_cache):
    """Second identical request should return cached response."""
    messages = [{"role": "user", "content": "What is 2+2?"}]
    
    response_1 = MagicMock()
    response_1.choices = [MagicMock()]
    response_1.choices[0].message.content = "4"
    response_1.id = "unique-response-id"
    
    call_count = [0]
    
    def mock_completion(**kwargs):
        call_count[0] += 1
        return response_1
    
    with patch("litellm.completion", side_effect=mock_completion):
        first = litellm.completion(model="gpt-3.5-turbo", messages=messages, caching=True)
        second = litellm.completion(model="gpt-3.5-turbo", messages=messages, caching=True)
    
    # With caching enabled, second call should not hit the API
    assert call_count[0] == 1  # Only one actual API call

def test_different_messages_bypass_cache(in_memory_cache):
    """Different messages should not use cached response."""
    response = MagicMock()
    response.choices = [MagicMock()]
    response.choices[0].message.content = "response"
    
    call_count = [0]
    
    def mock_completion(**kwargs):
        call_count[0] += 1
        return response
    
    with patch("litellm.completion", side_effect=mock_completion):
        litellm.completion(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": "Question 1"}],
            caching=True
        )
        litellm.completion(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": "Question 2"}],
            caching=True
        )
    
    assert call_count[0] == 2  # Both should hit API

Running LiteLLM Tests in CI/CD

GitHub Actions workflow for LiteLLM testing:

name: LiteLLM Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"
      
      - name: Install dependencies
        run: |
          pip install litellm pytest pytest-asyncio pytest-cov
          pip install litellm[proxy]
      
      - name: Run unit tests (no real API calls)
        run: |
          pytest tests/unit/ -v --cov=src --cov-report=xml
        env:
          OPENAI_API_KEY: "test-key-never-used"
          ANTHROPIC_API_KEY: "test-key-never-used"
      
      - name: Run config validation tests
        run: |
          pytest tests/config/ -v
      
      - name: Validate LiteLLM config YAML
        run: |
          python -c "
          import yaml, sys
          with open('litellm_config.yaml') as f:
              config = yaml.safe_load(f)
          assert 'model_list' in config, 'model_list required'
          assert len(config['model_list']) > 0, 'at least one model required'
          print(f'Config valid: {len(config[\"model_list\"])} models configured')
          "

Common LiteLLM Testing Mistakes

Mistake 1: Not mocking at the right level

# Wrong — mocks the HTTP client, not LiteLLM's abstraction
with patch("httpx.post") as mock:
    pass

# Right — mock at LiteLLM's completion function
with patch("litellm.completion") as mock:
    pass

Mistake 2: Forgetting to test fallback ordering

The order of fallbacks matters. ["gpt-3.5-turbo", "mistral-medium"] and ["mistral-medium", "gpt-3.5-turbo"] have different cost and latency implications. Test both orderings if your application is cost-sensitive.

Mistake 3: Not testing the unhappy path for caching

Cache misses on cold starts can cause latency spikes. Test what happens when the cache is empty or expired.

Integration with HelpMeTest

For continuous LiteLLM proxy monitoring, HelpMeTest provides end-to-end validation that goes beyond unit tests. You can create tests in plain English that verify your proxy routing and fallback logic against the real deployed system:

  • Monitor that your /v1/chat/completions endpoint responds within SLA thresholds
  • Verify fallback chains trigger correctly when upstream providers have incidents
  • Track cost-per-request trends over time

The free tier includes 24/7 monitoring at 5-minute intervals — useful for catching LiteLLM proxy regressions before your users do.

Summary

Testing LiteLLM effectively means testing at three layers:

  1. Configuration layer — YAML validation, model alias completeness, routing correctness
  2. SDK layer — completion calls, fallback chains, caching behavior, cost calculation
  3. Proxy layer — HTTP endpoints, authentication, rate limiting, health checks

The mocking patterns in this guide let you run the full suite in CI without incurring real API costs, while the integration test fixtures let you validate against a real proxy instance in staging. Start with config validation (fastest feedback) and work your way up to proxy integration tests.

Read more

Start now free