Repository navigation
Description
Summary
Add a mock inference-gateway (library + standalone binary) that serves the exact HTTP API surface the CLI consumes, selecting canned scenarios via regex matching on the user prompt — enabling hermetic, deterministic end-to-end testing of both chat (SSE streaming) and headless (sync) agent modes with no real LLM, no API key, and no network.
Implemented by #817.
Motivation
Before this, zero tests spoke /v1/chat/completions:
- The streaming consumer (
internal/agent/agent_streaming.go) was never driven by real SSE frames — tool-call fragment accumulation, multi-turn tool loops, reasoning deltas, retry, cancel-mid-stream were all unexercised against real parsing. - Agent tests mocked
domain.SDKClient(counterfeiterFakeSDKClient) and hand-assembled agent internals — white-box and fragile, and no wire-level fidelity. - Testing against a real gateway needs an API key, costs money, and is non-deterministic in CI.
Counterfeiter fakes remain the convention for unit tests; the mock gateway covers the layer an interface fake structurally cannot: real SDK client, real HTTP/SSE wire, real retry loop, real turn loop. The harness immediately paid for itself by catching four latent bugs (stream-failure hang/goroutine leak, ignored ctx cancellation, dropped usage-only chunks, a data race on parallel tool calls) — see #817.
Design
Stateless scenario resolution. Every request carries the full message history, so the mock needs no per-session state:
- Scenario = first regex (file order wins) matching the latest
role:usermessage that is not an injected<system-reminder>(string content or concatenated text content-parts). Each interactive chat prompt re-routes to its scenario; the headless loop's injected automated check never re-routes a run. - Step = count of
role:assistantmessages after that anchor →turns[step], so every new prompt restarts its scenario at turn 0; past the last turn a top-levelfallbackturn (plain text) is served, which lets the headless termination rule (two consecutive no-tool-call turns) trigger naturally. - The only mutable state is the error-injection counter and request recording, under one mutex — safe for concurrent use.
Wire fidelity via SDK types. Responses marshal sdk.CreateChatCompletionResponse / sdk.CreateChatCompletionStreamResponse; requests decode into sdk.CreateChatCompletionRequest. SSE frames are data: <json>\n\n + flush, terminated by data: [DONE]. Streaming tool-call arguments are deliberately split into ≥2 fragments per call so the CLI's index-keyed accumulator is always exercised. Zero new dependencies (gopkg.in/yaml.v3 is already direct).
Layout (supersedes this issue's original internal/infra/adapters/mock_gateway sketch — a main package doesn't belong in the production adapter tree):
internal/mockgateway/ library: handler, scenario schema, embedded built-ins, self-tests
tests/mockgateway/ standalone `mock-gateway` binary (-port, -scenarios)
tests/integration/ in-process e2e (real container + real SDK client + httptest mock)
tests/e2e/ subprocess e2e of the built binary (build tag `e2e`)
A main under tests/ provably cannot leak into release builds (release workflow builds package . only).
Scenario schema (YAML)
fallback:
content: "Done."
scenarios:
- name: parallel-reads
match: '(?i)execute (the )?Read tool 4 times in parallel'
turns:
- tool_calls:
- { name: Read, args: { file_path: "a.txt" } }
- { name: Read, args: { file_path: "b.txt" } }
- { name: Read, args: { file_path: "c.txt" } }
- { name: Read, args: { file_path: "d.txt" } }
- content: "All four files read."Turn fields: content, reasoning (→ reasoning_content deltas), tool_calls[{name, args}], usage{prompt_tokens, completion_tokens} (default 10/5), chunk_size (runes per SSE fragment, default 16), delay_ms (per-frame sleep, aborts on client disconnect), error{status, times} (fail the first N matching requests; -1 = forever), malformed (emit one garbage data: frame). Strict decode rejects unknown fields; validation compiles regexes and rejects error.status: 400 (400 is in the CLI's retryable list — an intended hard failure would become a retry storm).
Built-in scenario library
| name | prompt trigger | pins down |
|---|---|---|
text-only |
"say hello" | basic turn, [DONE] termination; headless exits after exactly 2 requests |
parallel-reads |
"execute the Read tool 4 times in parallel" | 4 tool calls in one turn → bounded-parallel dispatch, index-ordered results, multi-index fragment accumulation |
search |
"please search for …" | tool round-trip, role:tool result, fragmented-arguments accumulation |
sequential-explore |
"explore the project structure" | multi-turn loop (Tree → Read → answer), step-by-assistant-count |
write-blocked |
"create a file named blocked.txt" | headless approval gate: Write blocked without an approver, file never created |
bash-allowed / bash-blocked |
"run the echo command" / "run the forbidden command" | per-mode bash allow-list gate |
error-retry |
"flaky backend" | 429 twice then success → exactly 3 POSTs through the SDK retry loop |
error-hard |
"always fails" | persistent 500 → retry exhaustion → agent_error + non-zero exit |
malformed-sse |
"garbled stream" | bad data: frame skipped, stream continues |
slow-stream |
"stream slowly" | progressive rendering, cancel-mid-stream (and future TUI spinner assertions) |
usage-report |
"report your usage" | wire usage → session stats |
reasoning |
"think step by step" | reasoning deltas accumulate separately from content |
Test plan
- Mock self-tests (
internal/mockgateway): scenario/step resolution, content-part prompts, SSE frames round-tripped through SDK types, error-injection counting, load validation. - In-process integration (
tests/integration, plaingo test ./..., race-clean): realcontainer.NewServiceContainer+ real SDK client against anhttptestmock — accumulation, parallel completeness/order (no timing asserts), multi-turn, retry (INFER_CLIENT_RETRY_INITIAL_BACKOFF_SEC=0, explicitMaxAttempts), hard errors, malformed frames, ctx cancel, usage, syncRunpath. - Binary e2e (
tests/e2e,//go:build e2e,task test:e2e, CI job):TestMainbuildsinferonce (INFER_E2E_BINARYto reuse); subprocess envINFER_GATEWAY_URL+INFER_GATEWAY_RUN=false+INFER_AGENT_MODEL+INFER_STORAGE_ENABLED=false+HOME=$(mktemp -d); asserts headless JSON output contract, termination rule, tool side effects on disk,Blocked:rejections,agent_error+ exit code, piped-chat streaming.
Manual use
One env var (gateway.mock) boots the embedded mock in-process — no port, no extra config:
INFER_GATEWAY_MOCK=true infer chat
INFER_GATEWAY_MOCK=true infer agent -m openai/gpt-4o "please execute the Read tool 4 times in parallel"Custom scenario files use the standalone binary:
task build:mockgateway
.infer/bin/mock-gateway -port 0 -scenarios my.yaml # first stdout line announces the address
INFER_GATEWAY_URL=http://127.0.0.1:<port> INFER_GATEWAY_RUN=false infer chatThe embedded internal/mockgateway/scenarios.yaml doubles as the schema reference.
Out of scope
- Simulating real LLM semantics (responses are canned scripts, deliberately)
- TUI automation — follow-up: driving
infer chatinside tmux with screen-capture assertions, for which themock-gatewaybinary is the prerequisite - Admin/inspection HTTP API on the binary (in-process tests use
Server.Requests(); the binary logs one line per request to stderr) - Multi-model catalogs
Acceptance criteria
- Mock self-tests, integration tests and e2e tests green under
-race - No new go.mod entries; release binary unchanged (mock lives under
tests/) - golangci clean
-
task test:e2ewired into CI
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
[-]feat: add mock LLM client for hermetic end-to-end agent testing[/-][+][FEATURE] Add mock LLM client for hermetic end-to-end agent testing[/+][-][FEATURE] Add mock LLM client for hermetic end-to-end agent testing[/-][+][FEATURE] Add mock inference-gateway binary for hermetic end-to-end testing of chat and headless mode[/+]feat(gateway): hermetic mock gateway with INFER_GATEWAY_MOCK mode, sc…
inference-gateway-releaser commentedon Jul 10, 2026
🎉 This issue has been resolved in version 0.141.0 🎉
The release is available on:
Your semantic-release bot 📦🚀