Documentation
¶
Overview ¶
Package protocoltest provides a framework for end-to-end validation of the model gateway's protocol transformation layer.
Architecture ¶
VirtualServer — a mock HTTP provider that speaks OpenAI, Anthropic, and Google response formats. Conceptually a "virtual model" for testing.
TestEnv — wires a real gateway Server (with transform pipeline) to a VirtualServer, configures routing rules, and provides SendAs() for round-trip testing.
Matrix — executes the full cross-product of sources × targets × scenarios × streaming modes.
This package is the test-only framework, while internal/virtualmodel is the production Gin server. They share the vmodel.GenericRegistry primitive for scenario / model storage — Scenario implements vmodel.VirtualModel — but their HTTP handlers remain separate by design: virtualserver/handler.go operates on structured request/response shapes, while protocoltest scenarios serve pre-rendered byte / SSE-line payloads that exercise the gateway transform pipeline at the wire-format level.
Usage ¶
env := protocoltest.NewTestEnv(t) defer env.Close() env.SetupRoute(protocol.TypeAnthropicV1, protocol.TypeOpenAIChat, protocoltest.TextScenario()) result := env.SendAs(t, protocol.TypeAnthropicV1, protocol.TypeOpenAIChat, protocoltest.TextScenario(), false) assert.Equal(t, "assistant", result.Role)
Index ¶
- Constants
- func GetErrorSpec(id string) vmodel.SharedMockSpec
- func ResolveAPIStyle(entry RealModelEntry) (string, error)
- func ResolveAPIType(entry RealModelEntry) (string, error)
- type AgentScenario
- type AgentTestEnv
- func (env *AgentTestEnv) AppConfig() *serverconfig.Config
- func (env *AgentTestEnv) BaseURL() string
- func (env *AgentTestEnv) Close(preserve bool) error
- func (env *AgentTestEnv) ConfigDir() string
- func (env *AgentTestEnv) ModelToken() string
- func (env *AgentTestEnv) ReplayFixture(agentType AgentType, body []byte, streaming bool) (*RoundTripResult, error)
- func (env *AgentTestEnv) SetupAgent(AgentType AgentType, providerName string, modelName string) error
- func (env *AgentTestEnv) SetupRealAgent(AgentType AgentType, providerName string, modelName string, apiBase string, ...) error
- func (env *AgentTestEnv) SetupVModelAgent(AgentType AgentType, vmodelID string) error
- func (env *AgentTestEnv) SetupVirtualAgentScenario(agentType AgentType, scenario Scenario) error
- func (env *AgentTestEnv) VirtualServerURL() string
- type AgentTestResult
- type AgentType
- type Assertion
- func AssertContentContains(substring string) Assertion
- func AssertContentEquals(expected string) Assertion
- func AssertContentNonEmpty() Assertion
- func AssertErrorMessageContains(substring string) Assertion
- func AssertFinishReason(expected string) Assertion
- func AssertFinishReasonOneOf(accepted ...string) Assertion
- func AssertHTTPStatus(expected int) Assertion
- func AssertHTTPStatusAtLeast(min int) Assertion
- func AssertHasThinking() Assertion
- func AssertHasToolCalls(count int) Assertion
- func AssertModelContains(substring string) Assertion
- func AssertNoThinking() Assertion
- func AssertRoleEquals(expected string) Assertion
- func AssertStreamEventCount(min int) Assertion
- func AssertToolCallArgs(index int, key, value string) Assertion
- func AssertToolCallName(index int, name string) Assertion
- func AssertUsageNonZero() Assertion
- type AssertionError
- type CapturedRequest
- type Client
- type EndpointKind
- type FailoverRoute
- type IdempotentCase
- type Matrix
- func (m *Matrix) DefaultChains() []TransitiveChain
- func (m *Matrix) ExecuteAll() []TestResult
- func (m *Matrix) ExecuteAllFlags() []TestResult
- func (m *Matrix) ExecuteAllIdempotent() []TestResult
- func (m *Matrix) ExecuteAllTransitive() []TestResult
- func (m *Matrix) OnlyScenarios(names ...string) *Matrix
- func (m *Matrix) OnlySources(sources ...string) *Matrix
- func (m *Matrix) OnlyStreaming(streaming bool) *Matrix
- func (m *Matrix) OnlyTargets(targets ...string) *Matrix
- func (m *Matrix) Run(t *testing.T)
- func (m *Matrix) RunFull(t *testing.T)
- func (m *Matrix) RunIdempotent(t *testing.T)
- func (m *Matrix) RunTransitive(t *testing.T)
- func (m *Matrix) WithBatchCount(count int) *Matrix
- func (m *Matrix) WithClient(c Client) *Matrix
- func (m *Matrix) WithMCPEnabled() *Matrix
- func (m *Matrix) WithRecordDir(recordDir string) *Matrix
- func (m *Matrix) WithServerMode(mode string) *Matrix
- type MockResponseBuilder
- type ParsedResponse
- type ProtocolPair
- type ProviderConfig
- type ProvidersConfig
- type RealModelEntry
- type RealModelsConfig
- type ResponseFormat
- type RoundTripResult
- type Scenario
- func AllErrorScenarios() []Scenario
- func AllScenarios() []Scenario
- func Error500Scenario() Scenario
- func ErrorAuth401Scenario() Scenario
- func ErrorMidStreamCloseScenario() Scenario
- func ErrorScenario() Scenario
- func IncompleteScenario() Scenario
- func MultiTurnScenario() Scenario
- func StreamingTextScenario() Scenario
- func StreamingToolUseScenario() Scenario
- func TextScenario() Scenario
- func ThinkingScenario() Scenario
- func ToolResultScenario() Scenario
- func ToolUseScenario() Scenario
- type SendSpec
- type TestEnv
- func (env *TestEnv) Close()
- func (env *TestEnv) GatewayURL() string
- func (env *TestEnv) ModelToken() string
- func (env *TestEnv) SendAs(t *testing.T, source, target protocol.APIType, s Scenario, streaming bool) *RoundTripResult
- func (env *TestEnv) SendAsCLI(source, target protocol.APIType, s Scenario, streaming bool) (*RoundTripResult, error)
- func (env *TestEnv) SendWithModel(t *testing.T, source protocol.APIType, modelName string, streaming bool) *RoundTripResult
- func (env *TestEnv) SetupBothFailingRoute(t *testing.T, source, target protocol.APIType, failModel string) FailoverRoute
- func (env *TestEnv) SetupFailoverRoute(t *testing.T, source, target protocol.APIType, successScenario Scenario, ...) FailoverRoute
- func (env *TestEnv) SetupRoute(source, target protocol.APIType, s Scenario)
- func (env *TestEnv) SetupRouteWithFlags(source, target protocol.APIType, s Scenario, flags typ.RuleFlags) string
- func (env *TestEnv) VirtualCallCount() int
- func (env *TestEnv) VirtualURL() string
- type TestEnvOption
- type TestResult
- type TokenUsage
- type ToolCallResult
- type TransitiveChain
- type VirtualClient
- func (vc *VirtualClient) SendAnthropicV1(t *testing.T, s Scenario, streaming bool) *ParsedResponse
- func (vc *VirtualClient) SendGoogle(t *testing.T, s Scenario, streaming bool) *ParsedResponse
- func (vc *VirtualClient) SendOpenAIChat(t *testing.T, s Scenario, streaming bool) *ParsedResponse
- func (vc *VirtualClient) SendOpenAIResponses(t *testing.T, s Scenario, streaming bool) *ParsedResponse
- func (vc *VirtualClient) WithServer(vs *VirtualServer) *VirtualClient
- type VirtualServer
- func (vs *VirtualServer) CallCount() int
- func (vs *VirtualServer) Client() *VirtualClient
- func (vs *VirtualServer) Close()
- func (vs *VirtualServer) EndpointHits(kind EndpointKind) int
- func (vs *VirtualServer) LastRequest(kind EndpointKind) *CapturedRequest
- func (vs *VirtualServer) RegisterScenario(s Scenario)
- func (vs *VirtualServer) URL() string
Constants ¶
const ( FailMockPreContent429 = "virtual-fail-429" FailMockPreContent500 = "virtual-fail-500" FailMockMidStreamCut = "virtual-fail-midstream-close" FailMockMidStreamErr = "virtual-fail-midstream-event" )
Built-in failing mock IDs registered by vmodel.SharedDefaultMocks. Tests pass one of these as the primary tier to drive a deterministic failure without writing handler scaffolding.
const ( ServerModeAuto = "auto" // Per-scenario (default) ServerModeAll = "all" // Single server for all tests ServerModePair = "pair" // Per source-target pair )
ServerMode constants
Variables ¶
This section is empty.
Functions ¶
func GetErrorSpec ¶ added in v0.260611.1
func GetErrorSpec(id string) vmodel.SharedMockSpec
GetErrorSpec returns a vmodel error spec by ID from the built-in error models. Searches SharedDefaultMocks() (basic errors) and ExtendedErrorSpecs(). Results are cached for O(1) subsequent access. Returns zero value if not found.
func ResolveAPIStyle ¶
func ResolveAPIStyle(entry RealModelEntry) (string, error)
ResolveAPIStyle returns the effective api_style for an entry. Returns an error if api_style is empty or contains an invalid value. Valid values are: "openai", "anthropic", "google".
func ResolveAPIType ¶
func ResolveAPIType(entry RealModelEntry) (string, error)
ResolveAPIType returns the effective api_type for an entry. If the entry specifies one, it is validated and returned. If empty, returns a default based on api_style:
- "anthropic" → "anthropic_v1"
- "openai" → "openai_chat"
- "google" → "google"
Types ¶
type AgentScenario ¶
type AgentScenario struct {
// Name is the scenario name
Name string
// Description describes what the scenario tests
Description string
// MockResponses are the mock responses keyed by API style
MockResponses map[ResponseFormat]MockResponseBuilder
}
AgentScenario defines a test scenario for profile testing Unlike matrix scenarios which test protocol transformations, profile scenarios test client implementations (OAuth, path rewriting, etc.)
func AgentScenarios ¶
func AgentScenarios() []AgentScenario
AgentScenarios returns all built-in profile test scenarios
func AgentStreamingTextScenario ¶
func AgentStreamingTextScenario() AgentScenario
AgentStreamingTextScenario returns a scenario for streaming text response
func AgentTextScenario ¶
func AgentTextScenario() AgentScenario
AgentTextScenario returns a scenario for basic text request/response
func AgentToolUseScenario ¶
func AgentToolUseScenario() AgentScenario
AgentToolUseScenario returns a scenario for tool use request/response
func GetScenarioByName ¶
func GetScenarioByName(name string) (AgentScenario, bool)
GetScenarioByName returns a profile scenario by name
type AgentTestEnv ¶
type AgentTestEnv struct {
// contains filtered or unexported fields
}
AgentTestEnv provides an isolated test environment for Agent testing It includes: - A temporary config directory - A gateway server with virtual provider - Routing rules configured for the Agent - A virtual server that captures requests for validation
func NewAgentTestEnv ¶
func NewAgentTestEnv(AgentType AgentType) (*AgentTestEnv, error)
NewAgentTestEnv creates a new Agent test environment The environment is isolated with a temporary config directory and must be cleaned up with Close() when done
func (*AgentTestEnv) AppConfig ¶
func (env *AgentTestEnv) AppConfig() *serverconfig.Config
AppConfig returns the application configuration
func (*AgentTestEnv) BaseURL ¶
func (env *AgentTestEnv) BaseURL() string
BaseURL returns the base URL of the gateway server
func (*AgentTestEnv) Close ¶
func (env *AgentTestEnv) Close(preserve bool) error
Close cleans up the test environment If preserve is true, the config directory is kept for inspection
func (*AgentTestEnv) ConfigDir ¶
func (env *AgentTestEnv) ConfigDir() string
ConfigDir returns the temporary config directory path
func (*AgentTestEnv) ModelToken ¶
func (env *AgentTestEnv) ModelToken() string
ModelToken returns the model token for requests
func (*AgentTestEnv) ReplayFixture ¶
func (env *AgentTestEnv) ReplayFixture(agentType AgentType, body []byte, streaming bool) (*RoundTripResult, error)
ReplayFixture sends a raw request body to the agent's gateway endpoint and parses the response into a RoundTripResult ready for Scenario assertions.
The endpoint path, auth header, and response API style are all derived from agentType. `streaming` selects SSE vs JSON response parsing — it must match the fixture's own "stream" flag.
func (*AgentTestEnv) SetupAgent ¶
func (env *AgentTestEnv) SetupAgent(AgentType AgentType, providerName string, modelName string) error
SetupAgent configures the environment for a specific Agent type This creates the necessary provider and routing rules
func (*AgentTestEnv) SetupRealAgent ¶
func (env *AgentTestEnv) SetupRealAgent(AgentType AgentType, providerName string, modelName string, apiBase string, apiKey string, apiStyle string) error
SetupRealAgent configures the environment to route through a real upstream provider. Unlike SetupAgent, it does not use the virtual server — the provider points at the real apiBase with the real apiKey. apiStyle must be "openai" or "anthropic". apiType is optional and specifies the target API type (e.g., "anthropic_v1", "openai_chat"). If empty, a default is chosen based on apiStyle.
func (*AgentTestEnv) SetupVModelAgent ¶
func (env *AgentTestEnv) SetupVModelAgent(AgentType AgentType, vmodelID string) error
SetupVModelAgent configures the environment so the agent's built-in rule routes to a seeded builtin virtual-model provider.
Unlike SetupAgent (external VirtualServer mock) and SetupRealAgent (real upstream), this exercises the in-process vmodel dispatch path:
gateway → built-in-<agent> rule → vmodel builtin provider
→ provider.IsVirtual() short-circuit → in-process vmodel handler
The builtin vmodel providers are seeded into the provider store by server.NewServer, so no provider is added here — only the rule is repointed.
vmodelID must be a model registered in the vmodel registry for the agent's protocol (e.g. "virtual-claude-3", "echo-model" for Anthropic-style agents).
func (*AgentTestEnv) SetupVirtualAgentScenario ¶
func (env *AgentTestEnv) SetupVirtualAgentScenario(agentType AgentType, scenario Scenario) error
SetupVirtualAgentScenario wires the agent's built-in rule to the in-process VirtualServer and registers `scenario`'s mock responses so the VirtualServer serves them deterministically.
This is the "virtual" replay upstream: because the response is fully controlled by the scenario's MockResponses, the caller can run the scenario's content-level Assertions against the round-trip result.
The rule's upstream model encodes the scenario name as "virtual-model-<scenario>" so the VirtualServer's scenario detection resolves the right mock.
func (*AgentTestEnv) VirtualServerURL ¶
func (env *AgentTestEnv) VirtualServerURL() string
VirtualServerURL returns the URL of the virtual server
type AgentTestResult ¶
type AgentTestResult struct {
// Name is the test name
Name string
// Agent is the Agent type being tested
Agent AgentType
// Scenario is the test scenario (e.g., "text", "streaming", "tool_use")
Scenario string
// Passed indicates whether the test passed
Passed bool
// Skipped indicates whether the test was skipped
Skipped bool
// SkipReason explains why the test was skipped
SkipReason string
// Errors contains any assertion errors
Errors []AssertionError
// Duration is how long the test took
Duration int64 // milliseconds
// HTTPStatus is the HTTP status code received
HTTPStatus int
// RequestHeaders contains the request headers sent to the virtual server
RequestHeaders http.Header
// RequestBody contains the request body sent to the virtual server
RequestBody []byte
// ResponseBody contains the raw response body
ResponseBody []byte
}
AgentTestResult represents the result of a single Agent test
type AgentType ¶
type AgentType string
AgentType represents the type of agent Agent to test
func (AgentType) Scenario ¶
func (pt AgentType) Scenario() typ.RuleScenario
Scenario returns the corresponding RuleScenario for this Agent
type Assertion ¶
type Assertion struct {
Name string
Check func(r *RoundTripResult) error
}
Assertion is a named check applied to a RoundTripResult.
func AssertContentContains ¶
AssertContentContains returns an Assertion that the response content contains substring.
func AssertContentEquals ¶
AssertContentEquals returns an Assertion that the response content equals expected.
func AssertContentNonEmpty ¶
func AssertContentNonEmpty() Assertion
AssertContentNonEmpty returns an Assertion that the response carries some payload — either text content or at least one tool call. Useful as an upstream-independent structural check when the exact response text is not controlled by the test (e.g. vmodel or real upstreams).
func AssertErrorMessageContains ¶ added in v0.260611.1
AssertErrorMessageContains returns an Assertion that the raw response body contains the given substring. Useful for validating error responses where the semantic fields (Content, Role, etc.) are not populated.
func AssertFinishReason ¶
AssertFinishReason returns an Assertion that the finish_reason equals expected.
func AssertFinishReasonOneOf ¶ added in v0.260611.1
AssertFinishReasonOneOf returns an Assertion that the finish_reason matches any of the accepted values. Useful for scenarios where the expected finish reason varies by source protocol (e.g. "length" for Chat, "max_tokens" for Anthropic, "incomplete" for Responses).
func AssertHTTPStatus ¶
AssertHTTPStatus returns an Assertion that the HTTP status code equals expected.
func AssertHTTPStatusAtLeast ¶ added in v0.260611.1
AssertHTTPStatusAtLeast returns an Assertion that the HTTP status code is >= min.
func AssertHasThinking ¶
func AssertHasThinking() Assertion
AssertHasThinking returns an Assertion that thinking content is non-empty.
func AssertHasToolCalls ¶
AssertHasToolCalls returns an Assertion that exactly count tool calls are present.
func AssertModelContains ¶
AssertModelContains returns an Assertion that the model name contains substring.
func AssertNoThinking ¶
func AssertNoThinking() Assertion
AssertNoThinking returns an Assertion that no thinking content is present.
func AssertRoleEquals ¶
AssertRoleEquals returns an Assertion that the response role equals expected.
func AssertStreamEventCount ¶
AssertStreamEventCount returns an Assertion that at least min SSE events were received.
func AssertToolCallArgs ¶
AssertToolCallArgs returns an Assertion that tool call at index has key=value in its JSON args.
func AssertToolCallName ¶
AssertToolCallName returns an Assertion that the tool call at index has the given name.
func AssertUsageNonZero ¶
func AssertUsageNonZero() Assertion
AssertUsageNonZero returns an Assertion that at least one token count > 0. For streaming responses, usage extraction is protocol-dependent and may not be available, so this assertion is skipped in streaming mode.
type AssertionError ¶
type AssertionError struct {
Assertion string // assertion name
Error string // error message
Context string // additional context (truncated body, etc.)
}
AssertionError represents a single assertion failure.
type CapturedRequest ¶
type CapturedRequest struct {
// Headers contains the request headers
Headers http.Header
// Body contains the request body
Body []byte
// Method is the HTTP method
Method string
// Path is the request path
Path string
}
CapturedRequest represents a request captured by the virtual server
func (*CapturedRequest) JSON ¶ added in v0.260611.1
func (cr *CapturedRequest) JSON() map[string]interface{}
JSON decodes a captured request body into a generic map. It returns an empty map if the body is absent or not JSON. Used by flag-behavior tests to assert on what the gateway actually forwarded to the upstream provider.
type Client ¶ added in v0.260611.1
type Client interface {
// Name identifies the driver: "http", "gosdk", "python", "node".
Name() string
// Supports reports whether the driver can speak the given source protocol.
Supports(source protocol.APIType) bool
// Send issues one request and returns the normalized result. Gateway-side
// API errors (4xx/5xx) must be reported in the result (HTTPStatus/RawBody),
// not as a returned error; a non-nil error means the driver itself failed.
Send(env *TestEnv, spec SendSpec) (*RoundTripResult, error)
}
Client drives a single request through the gateway and returns the normalized RoundTripResult the assertion layer consumes. Implementations range from the raw in-process HTTP client (default) to official SDKs and external subprocess drivers (python/node), so the same matrix exercises the gateway through progressively more realistic client stacks.
func NewAISDKClient ¶ added in v0.260611.1
NewAISDKClient returns a driver backed by tests/clients/aisdk/driver.mjs (AI SDK by Vercel: ai + @ai-sdk/anthropic + @ai-sdk/openai). driverDir is the tests/clients root.
func NewGoSDKClient ¶ added in v0.260611.1
func NewGoSDKClient() Client
NewGoSDKClient returns a client driver backed by the official Go SDKs.
func NewHTTPClient ¶ added in v0.260611.1
func NewHTTPClient() Client
NewHTTPClient returns the default raw-HTTP client driver.
func NewNodeClient ¶ added in v0.260611.1
NewNodeClient returns a driver backed by tests/clients/node/driver.mjs (real @anthropic-ai/sdk + openai Node SDKs). driverDir is the tests/clients root.
func NewPythonClient ¶ added in v0.260611.1
NewPythonClient returns a driver backed by tests/clients/python/driver.py (real anthropic + openai Python SDKs). driverDir is the tests/clients root.
func NewSubprocessClient ¶ added in v0.260611.1
NewSubprocessClient returns a client driver that shells out to argv for each request, speaking the JSON-over-stdin/stdout driver contract.
type EndpointKind ¶ added in v0.260611.1
type EndpointKind string
VirtualServer is a mock provider server backed by httptest.Server. It speaks OpenAI, Anthropic, and Google response formats and returns pre-configured scenario responses.
**Provider Routes**: This server handles provider-native routes (/v1/chat/completions, /v1/messages, /v1beta/models/...), NOT gateway routes (/tingly/{scenario}/v1/...). The gateway transforms requests to provider format before forwarding to this server. EndpointKind identifies which provider-native endpoint a request hit. chat and responses are deliberately distinct: they are two different OpenAI protocols, and tests assert which one the gateway actually forwarded to.
const ( EndpointChat EndpointKind = "chat" EndpointResponses EndpointKind = "responses" EndpointAnthropic EndpointKind = "anthropic" EndpointGoogle EndpointKind = "google" )
type FailoverRoute ¶
type FailoverRoute struct {
ModelName string
PrimaryCallCount *atomic.Int64
FallbackCallCount *atomic.Int64 // nil when fallback is env.virtual
}
FailoverRoute is the handle returned by SetupFailoverRoute / SetupBothFailingRoute. ModelName is the gateway-facing model (pass to SendWithModel). PrimaryCallCount tracks how often the primary tier was hit. FallbackCallCount is non-nil only when both tiers run through vmodel mock servers (i.e. SetupBothFailingRoute); otherwise it is nil and tests must rely on content discrimination for fallback assertions.
type IdempotentCase ¶ added in v0.260611.1
type IdempotentCase struct {
Name string // human-readable label
Source protocol.APIType // A: the client-facing protocol
Mid protocol.APIType // B: the intermediate protocol the chain passes through
Baseline protocol.APIType // A': passthrough target for the baseline (same API style as A)
}
IdempotentCase describes a round-trip idempotency check. It compares the client-visible result of two request paths that should be observationally identical:
baseline: Client(A) ──[A→A passthrough]──────────────→ R0 round-trip: Client(A) ──[A→B]──[B→A]─────────────────────→ R1
The round-trip chains two real conversions: the first hop converts A→B and forwards to the gateway itself, which re-enters through B's inbound route and converts B→A before hitting the mock provider. If either conversion drops information, R0 and R1 diverge.
g(f(A)) == A where f = A→B, g = B→A
func DefaultIdempotentCases ¶ added in v0.260611.1
func DefaultIdempotentCases() []IdempotentCase
DefaultIdempotentCases returns the canonical round-trip idempotency cases: every pair among the three first-class protocols (Anthropic, OpenAI Chat, OpenAI Responses), in both directions. Chat and Responses are treated as distinct protocols — the chain head sets OpenAIEndpointMode so a Responses intermediate genuinely re-enters /responses, not /chat/completions.
Baseline is the source's same-style passthrough target:
- anthropic_v1 → anthropic_beta (Anthropic passthrough)
- openai_chat → openai_chat
- openai_responses → openai_responses
Google is omitted: the harness's virtual-provider plumbing does not yet support Google as a target, so it cannot serve as an intermediate hop.
type Matrix ¶
type Matrix struct {
Pairs []ProtocolPair
Scenarios []Scenario
Streaming []bool
RecordDir string // Optional directory for recording requests/responses
ServerMode string // Server reuse mode: auto, all, pair
BatchCount int // Number of times to run each test
MCPEnabled bool // Enable MCP feature flag in test env
Client Client // Client driver (nil = raw HTTP default)
}
Matrix defines the set of (source, target) pairs, scenarios, and streaming modes to validate.
func DefaultMatrix ¶
func DefaultMatrix() *Matrix
DefaultMatrix returns the full validation matrix covering every supported (source, target) pair, all built-in scenarios, and both streaming modes.
func (*Matrix) DefaultChains ¶ added in v0.260611.1
func (m *Matrix) DefaultChains() []TransitiveChain
DefaultChains builds transitive chains by composing pairs from the matrix where the first pair's target matches the second pair's source. Self-loops (A→B→A where first == reverse of second) are included — they test round-trip fidelity.
func (*Matrix) ExecuteAll ¶
func (m *Matrix) ExecuteAll() []TestResult
ExecuteAll runs all matrix combinations and returns structured results. This is a pure function that can be called from both tests and CLI. It does not use testing.T, making it suitable for standalone execution.
Server reuse strategies based on ServerMode: - auto (default): Reuses TestEnv per scenario - all: Uses a single TestEnv for all tests (fastest, potential for interference) - pair: Reuses TestEnv per source-target pair (balanced approach)
func (*Matrix) ExecuteAllFlags ¶ added in v0.260611.1
func (m *Matrix) ExecuteAllFlags() []TestResult
ExecuteAllFlags runs the rule-flag behavior suite without requiring testing.T. It is the CLI-compatible counterpart of TestRuleFlags, returning []TestResult. Name format: "flags/<flag key>".
func (*Matrix) ExecuteAllIdempotent ¶ added in v0.260611.1
func (m *Matrix) ExecuteAllIdempotent() []TestResult
ExecuteAllIdempotent runs round-trip idempotency tests without requiring testing.T. It is the CLI-compatible counterpart of RunIdempotent, returning []TestResult. For each scenario × case × mode it wires the baseline and round-trip routes in one gateway, drives both requests, and records whether the client-visible results are semantically equivalent (g(f(A)) == A).
Name format: "scenario/<case>/mode" (e.g. "text/openai_chat_via_anthropic/stream").
func (*Matrix) ExecuteAllTransitive ¶ added in v0.260611.1
func (m *Matrix) ExecuteAllTransitive() []TestResult
ExecuteAllTransitive runs two-hop chain tests without requiring testing.T. It is the CLI-compatible counterpart of RunTransitive, returning []TestResult. Name format: "scenario/A→B→C/mode".
func (*Matrix) OnlyScenarios ¶
OnlyScenarios returns a copy of the Matrix filtered to only the named scenarios.
func (*Matrix) OnlySources ¶
OnlySources returns a copy of the Matrix filtered to pairs whose source matches one of the given protocols.
func (*Matrix) OnlyStreaming ¶
OnlyStreaming returns a copy of the Matrix filtered to only streaming or non-streaming tests. If streaming is true, only streaming tests are included. If false, only non-streaming tests.
func (*Matrix) OnlyTargets ¶
OnlyTargets returns a copy of the Matrix filtered to pairs whose target matches one of the given protocols.
func (*Matrix) Run ¶
Run executes all matrix combinations as subtests under t. Each combination runs in its own TestEnv so state is isolated.
func (*Matrix) RunFull ¶ added in v0.260611.1
RunFull executes both single-hop and two-hop tests under t, organized as two named sub-sections:
- "single_hop": every (source→target) pair × scenario × streaming mode
- "two_hop": every (A→B→C) transitive chain × scenario × streaming mode
Run each section independently with -run TestFoo/single_hop or /two_hop.
func (*Matrix) RunIdempotent ¶ added in v0.260611.1
RunIdempotent executes round-trip idempotency tests for all cases × scenarios. For each case it wires three routes in a single gateway, drives the baseline and round-trip requests, and asserts the client-visible results are semantically equivalent.
func (*Matrix) RunTransitive ¶ added in v0.260611.1
RunTransitive executes two-hop transitive tests for all chains × scenarios. For each chain A→B→C:
- Send as A with target B → get result1 (in A's response format)
- Send as B with target C → get result2 (in B's response format)
- Assert result1 and result2 are semantically equivalent
This catches information loss that single-hop tests miss: if A→B drops a field that B→C needs, the results will diverge.
A single TestEnv is shared per scenario to limit file descriptor usage; chains within a scenario run sequentially to avoid "too many open files" under heavy parallelism.
func (*Matrix) WithBatchCount ¶
WithBatchCount returns a copy of the Matrix with the batch count set.
func (*Matrix) WithClient ¶ added in v0.260611.1
WithClient returns a copy of the Matrix that drives requests through the given client driver (official SDKs, subprocess drivers) instead of the default raw HTTP client.
func (*Matrix) WithMCPEnabled ¶
WithMCPEnabled returns a copy of the Matrix with the MCP feature flag enabled.
func (*Matrix) WithRecordDir ¶
WithRecordDir returns a copy of the Matrix with the record directory set. If recordDir is empty, recording is disabled.
func (*Matrix) WithServerMode ¶
WithServerMode returns a copy of the Matrix with the server reuse mode set.
type MockResponseBuilder ¶
type MockResponseBuilder struct {
NonStream func() (statusCode int, body []byte)
Stream func() []string
// StreamHTTPError, when >= 400, makes the streaming endpoint reply with this
// HTTP status and the NonStream JSON body instead of a 200 SSE stream. It
// models pre-content failures (auth / rate-limit / 5xx) that real providers
// surface as an HTTP error even for streaming requests — the failure happens
// before any SSE frame is written, so the status line itself carries it.
// Mid-stream failures leave this zero and use the 200 + SSE path.
StreamHTTPError int
}
MockResponseBuilder defines how a virtual server should respond for one response format.
func BuildErrorFromSpec ¶ added in v0.260611.1
func BuildErrorFromSpec(format ResponseFormat, spec vmodel.SharedMockSpec) MockResponseBuilder
BuildErrorFromSpec creates a MockResponseBuilder from a vmodel.SharedMockSpec for the specified protocol format. This enables protocoltest to use the same error definitions as vmodel, ensuring consistency across testing and production.
type ParsedResponse ¶
type ParsedResponse = vmodeltest.ParsedResponse
ParsedResponse is the result of a request sent to a virtual server.
type ProtocolPair ¶
ProtocolPair is one (source → target) conversion path to validate. The matrix is built from an explicit list of pairs rather than the Cartesian product of all sources × all targets: many cells of that product map to the same dispatch path (e.g. target=anthropic_v1 and target=anthropic_beta both pick APIStyleAnthropic; OpenAI Chat vs. Responses targets are picked by ResolveOpenAIEndpoint, not the matrix) and listing pairs keeps the matrix in lock-step with the actual dispatch graph documented in internal/protocol/README.md.
func DefaultPairs ¶
func DefaultPairs() []ProtocolPair
DefaultPairs is the canonical list of (source → target) conversion paths the matrix exercises. Adding a new dispatch path means appending to this list.
Notes:
- target=anthropic_v1 is intentionally absent. The harness picks providers by APIStyle and both Anthropic types map to the same style, so anthropic_beta as the target already exercises both Anthropic V1 passthrough (when source is V1) and the Beta conversions (when source is non-Anthropic). See internal/protocol/README.md.
- Anthropic↔Anthropic cross-version (v1↔beta) is rejected by the transform layer and not represented here.
- Google targets and the google→google passthrough are not yet supported by the harness's virtual provider plumbing.
func (ProtocolPair) String ¶
func (p ProtocolPair) String() string
String returns "source|target" for use as a map key or label.
type ProviderConfig ¶
type ProviderConfig struct {
Name string `yaml:"name"`
BaseURL string `yaml:"baseurl"`
APIKey string `yaml:"apikey"`
APIStyle string `yaml:"api_style"` // required: "openai" | "anthropic" | "google"
APIType string `yaml:"api_type"` // optional: "openai_chat" | "openai_responses" | "anthropic_v1" | "anthropic_beta" | "google"
Models []string `yaml:"models"` // list of model names to test
}
ProviderConfig is one provider entry in the config YAML file. A provider can have multiple models under it.
type ProvidersConfig ¶
type ProvidersConfig struct {
Providers []ProviderConfig `yaml:"providers"`
}
ProvidersConfig is the top-level structure of the config YAML file.
type RealModelEntry ¶
type RealModelEntry struct {
Name string // generated entry name: "provider" or "provider-model"
Provider string // original provider name
BaseURL string
APIKey string
Model string
APIStyle string
APIType string
}
RealModelEntry is an expanded entry for testing. Each (provider, model) pair becomes one entry.
func ExpandProvidersConfig ¶
func ExpandProvidersConfig(cfg *ProvidersConfig) []RealModelEntry
ExpandProvidersConfig expands a ProvidersConfig into individual test entries. Each provider's models array is expanded into separate entries.
func LoadProvidersConfig ¶
func LoadProvidersConfig(path string) ([]RealModelEntry, error)
LoadProvidersConfig reads and parses a providers config YAML file. Returns the expanded list of test entries.
type RealModelsConfig ¶
type RealModelsConfig struct {
Models []RealModelEntry
}
RealModelsConfig is the legacy format kept for backward compatibility. Deprecated: Use ProvidersConfig instead.
func LoadRealModelsConfig ¶
func LoadRealModelsConfig(path string) (*RealModelsConfig, error)
LoadRealModelsConfig is an alias for LoadProvidersConfig for backward compatibility. Deprecated: Use LoadProvidersConfig instead.
type ResponseFormat ¶
type ResponseFormat string
ResponseFormat represents the format of the mock response for different endpoints.
const ( FormatOpenAIChat ResponseFormat = "openai_chat" // /v1/chat/completions FormatOpenAIResponses ResponseFormat = "openai_responses" // /v1/responses FormatAnthropic ResponseFormat = "anthropic" // /v1/messages FormatGoogle ResponseFormat = "google" // /v1beta/models/.../generateContent )
type RoundTripResult ¶
type RoundTripResult struct {
// Source and target context
SourceProtocol protocol.APIType
TargetProtocol protocol.APIType
ScenarioName string
IsStreaming bool
// HTTP layer
HTTPStatus int
RawBody []byte
StreamEvents []string // raw SSE event lines (streaming only)
// Extracted semantics (populated by the framework after parsing)
Content string
Role string
Model string
FinishReason string
ToolCalls []ToolCallResult
ThinkingContent string
Usage *TokenUsage
}
RoundTripResult captures the full result of a round-trip request through the gateway.
type Scenario ¶
type Scenario struct {
Name string
Description string
Tags []string
MockResponses map[ResponseFormat]MockResponseBuilder
Assertions []Assertion
// SkipTransitive marks scenarios that should be excluded from two-hop
// transitive tests (e.g. error scenarios that produce no comparable output).
SkipTransitive bool
}
Scenario is a named test scenario describing what the mock provider returns and what assertions to run on the round-trip result.
Scenario satisfies vmodel.VirtualModel so scenario storage can reuse vmodel.GenericRegistry.
func AllErrorScenarios ¶ added in v0.260611.1
func AllErrorScenarios() []Scenario
AllErrorScenarios returns all error scenarios for tests that need to exercise error handling comprehensively.
func AllScenarios ¶
func AllScenarios() []Scenario
AllScenarios returns the full set of built-in validation scenarios.
func Error500Scenario ¶ added in v0.260611.1
func Error500Scenario() Scenario
Error500Scenario tests upstream server error (500) propagated to client.
func ErrorAuth401Scenario ¶ added in v0.260611.1
func ErrorAuth401Scenario() Scenario
ErrorAuth401Scenario tests authentication failure (401) propagated to client.
func ErrorMidStreamCloseScenario ¶ added in v0.260611.1
func ErrorMidStreamCloseScenario() Scenario
ErrorMidStreamCloseScenario tests mid-stream connection close failure.
func ErrorScenario ¶
func ErrorScenario() Scenario
func IncompleteScenario ¶ added in v0.260611.1
func IncompleteScenario() Scenario
IncompleteScenario exercises the max-output-tokens truncation path. The provider returns a partial response that was cut short; the gateway must preserve the partial content and map the finish reason correctly (Chat → "length", Anthropic → "max_tokens", Responses → "incomplete").
func MultiTurnScenario ¶
func MultiTurnScenario() Scenario
MultiTurnScenario tests a conversation with system prompt + 2 turns of history.
func StreamingTextScenario ¶
func StreamingTextScenario() Scenario
StreamingTextScenario tests SSE streaming for a plain text response.
func StreamingToolUseScenario ¶
func StreamingToolUseScenario() Scenario
StreamingToolUseScenario tests SSE streaming for a tool call response.
func TextScenario ¶
func TextScenario() Scenario
TextScenario is the baseline: a single user message and a plain text reply.
func ThinkingScenario ¶
func ThinkingScenario() Scenario
ThinkingScenario tests that extended thinking blocks are present in Anthropic responses.
func ToolResultScenario ¶
func ToolResultScenario() Scenario
ToolResultScenario tests a multi-turn conversation including a tool result message.
func ToolUseScenario ¶
func ToolUseScenario() Scenario
ToolUseScenario exercises a single tool/function call.
func (Scenario) GetDescription ¶
func (Scenario) GetType ¶
func (s Scenario) GetType() vmodel.VirtualModelType
func (Scenario) SimulatedDelay ¶
type SendSpec ¶ added in v0.260611.1
type SendSpec struct {
Source protocol.APIType
Target protocol.APIType
ScenarioName string
RequestModel string
Streaming bool
GatewayURL string // real HTTP base URL of the gateway, e.g. http://127.0.0.1:PORT
APIKey string // gateway model token
}
SendSpec carries everything a client driver needs to issue one request through the gateway. Target and ScenarioName are response metadata only; the request itself varies only by (Source, RequestModel, Streaming).
type TestEnv ¶
type TestEnv struct {
// contains filtered or unexported fields
}
TestEnv wires a real gateway Server (with the full transform pipeline) to a VirtualServer (mock provider). It manages config, routing rules, and provides SendAs() for full round-trip testing.
**Routing Architecture**:
Client Request → Gateway (/tingly/{scenario}/v1/...)
→ Protocol Transform
→ Provider Request (virtual-server-url/v1/...)
→ VirtualServer (mock provider response)
The gateway handles /tingly/{scenario}/v1/... routes, transforms the request to provider format, and forwards to the virtual server which speaks provider native APIs (/v1/chat/completions, /v1/messages, etc.).
func NewTestEnv ¶
func NewTestEnv(t *testing.T, opts ...TestEnvOption) *TestEnv
NewTestEnv creates a TestEnv with a fresh gateway config and a new VirtualServer. All resources are cleaned up via t.Cleanup. Only the client option is honored in test mode; recording is a CLI-only concern.
func NewTestEnvForCLI ¶
func NewTestEnvForCLI(opts ...TestEnvOption) (*TestEnv, error)
NewTestEnvForCLI creates a TestEnv for CLI use (without testing.T). Resources must be cleaned up via explicit Close() call.
func (*TestEnv) Close ¶
func (env *TestEnv) Close()
Close cleans up resources. For testing mode, it's a no-op (resources are cleaned up via t.Cleanup). For CLI mode, it closes the servers and removes the config directory.
func (*TestEnv) GatewayURL ¶ added in v0.260611.1
GatewayURL returns the base URL of the real gateway HTTP server, for client drivers that speak real HTTP (SDKs, subprocess drivers).
func (*TestEnv) ModelToken ¶ added in v0.260611.1
ModelToken returns the gateway model token client drivers authenticate with.
func (*TestEnv) SendAs ¶
func (env *TestEnv) SendAs(t *testing.T, source, target protocol.APIType, s Scenario, streaming bool) *RoundTripResult
SendAs sends a request to the gateway as the given source protocol, using the request model configured by SetupRoute, and returns the parsed result.
Streaming requests use the real httptest.Server (env.gatewayServer) because httptest.ResponseRecorder does not support Gin's streaming/SSE machinery. Non-streaming requests use the recorder for simplicity.
func (*TestEnv) SendAsCLI ¶
func (env *TestEnv) SendAsCLI(source, target protocol.APIType, s Scenario, streaming bool) (*RoundTripResult, error)
SendAsCLI sends a request to the gateway as the given source protocol, using the request model configured by SetupRoute, and returns the parsed result. This version is for CLI use and returns errors instead of calling t.Fatalf.
func (*TestEnv) SendWithModel ¶
func (env *TestEnv) SendWithModel(t *testing.T, source protocol.APIType, modelName string, streaming bool) *RoundTripResult
SendWithModel sends a request using an explicit model name (bypassing the SetupRoute route map). Used for failover tests where the rule's request model doesn't follow SetupRoute's naming convention.
func (*TestEnv) SetupBothFailingRoute ¶
func (env *TestEnv) SetupBothFailingRoute( t *testing.T, source, target protocol.APIType, failModel string, ) FailoverRoute
SetupBothFailingRoute wires a two-tier rule where BOTH tiers trip the same pre-content injection. Used for the all-tiers-fail test: client must see a non-200 once the orchestrator exhausts its budget.
func (*TestEnv) SetupFailoverRoute ¶
func (env *TestEnv) SetupFailoverRoute( t *testing.T, source, target protocol.APIType, successScenario Scenario, primaryFailModel string, ) FailoverRoute
SetupFailoverRoute wires a two-tier rule using vmodel's pre-registered error mocks for the primary tier. Both tiers run inside httptest servers; the primary always trips the named injection (SharedDefaultMocks IDs above), the fallback serves successScenario via env.virtual.
The orchestrator dispatches under TacticTier; the primary (Tier 0) is tried first; pre-content failures are retryable; mid-stream failures commit the gate (no retry). This is the single helper that covers all failover-test shapes: 429/500 pre-content, mid-stream close, mid-stream event.
func (*TestEnv) SetupRoute ¶
SetupRoute configures a gateway rule that routes source protocol requests to the virtual server acting as a target protocol provider.
The virtual server is pre-registered with the scenario's mock responses. If the route has already been set up, this is a no-op (idempotent).
**Routing Flow**: 1. Client sends request to gateway: POST /tingly/{scenario}/v1/chat/completions 2. Gateway transforms request to provider format based on source protocol 3. Gateway forwards to provider: POST {virtualURL}/v1/chat/completions 4. VirtualServer (provider mock) returns pre-configured scenario response
The provider's APIBase includes the /v1 suffix for OpenAI-style providers to match actual provider API structure.
func (*TestEnv) SetupRouteWithFlags ¶ added in v0.260611.1
func (env *TestEnv) SetupRouteWithFlags(source, target protocol.APIType, s Scenario, flags typ.RuleFlags) string
SetupRouteWithFlags wires a route exactly like SetupRoute but stamps rule.Flags onto the gateway rule, so a request routed through it exercises the real flag-resolution and transform pipeline. Returns the request model to send to.
func (*TestEnv) VirtualCallCount ¶
VirtualCallCount returns the number of requests received by the virtual server.
func (*TestEnv) VirtualURL ¶
VirtualURL returns the URL of the underlying virtual server.
type TestEnvOption ¶
type TestEnvOption func(*testEnvConfig)
TestEnvOption is a functional option for configuring TestEnv.
func NewTestEnvOptionWithClient ¶ added in v0.260611.1
func NewTestEnvOptionWithClient(c Client) TestEnvOption
NewTestEnvOptionWithClient creates an option to set the client driver used for sending requests through the gateway. Defaults to the raw HTTP client.
func NewTestEnvOptionWithMCP ¶
func NewTestEnvOptionWithMCP() TestEnvOption
NewTestEnvOptionWithMCP creates an option to enable the MCP feature flag.
func NewTestEnvOptionWithRecordDir ¶
func NewTestEnvOptionWithRecordDir(dir string) TestEnvOption
NewTestEnvOptionWithRecordDir creates an option to set the record directory. If empty, recording is disabled.
type TestResult ¶
type TestResult struct {
// Test identification
Name string // Full test name: "scenario/source/target/mode"
Scenario string // Scenario name: "text", "tool_use", etc.
Source protocol.APIType
Target protocol.APIType
Streaming bool
// Test outcome
Passed bool // true if all assertions passed
Skipped bool // true if test was skipped
SkipReason string // reason for skipping
// Error details
Errors []AssertionError // list of assertion failures
Duration time.Duration // test execution time
// Batch statistics (populated when BatchCount > 1)
BatchCount int // number of times the test was executed
BatchPassed int // number of executions that passed
BatchMinDur time.Duration // minimum duration across executions
BatchAvgDur time.Duration // average duration across executions
BatchMaxDur time.Duration // maximum duration across executions
BatchErrors []string // unique error messages from failed executions
// Response details (for debugging/verbose output)
HTTPStatus int // HTTP status code
Response *RoundTripResult // full round-trip result (from first or last execution)
}
TestResult represents the outcome of a single matrix test combination. This is returned by Matrix.ExecuteAll() for CLI and other non-testing contexts.
type TokenUsage ¶
TokenUsage holds token counts extracted from a provider response.
type ToolCallResult ¶
ToolCallResult holds a single tool/function call extracted from a response.
type TransitiveChain ¶ added in v0.260611.1
type TransitiveChain struct {
First ProtocolPair // A→B
Second ProtocolPair // B→C (Second.Source == First.Target)
}
TransitiveChain represents a two-hop conversion path: A→B then B→C. Both hops go through the full gateway pipeline. The test verifies that the semantic content (text, role, tool calls) is preserved across both conversions.
func (TransitiveChain) String ¶ added in v0.260611.1
func (c TransitiveChain) String() string
String returns a human-readable label like "anthropic_v1→openai_chat→anthropic_beta".
type VirtualClient ¶
type VirtualClient struct {
*vmodeltest.Client
// contains filtered or unexported fields
}
VirtualClient sends provider-native HTTP requests for testing. It embeds vmodeltest.Client for model-parameterized methods and adds scenario-based methods that auto-register on a bound VirtualServer.
func NewVirtualClient ¶
func NewVirtualClient(baseURL string) *VirtualClient
NewVirtualClient creates a client pointing at baseURL.
func (*VirtualClient) SendAnthropicV1 ¶
func (vc *VirtualClient) SendAnthropicV1(t *testing.T, s Scenario, streaming bool) *ParsedResponse
SendAnthropicV1 sends a request to the Anthropic Messages endpoint.
func (*VirtualClient) SendGoogle ¶
func (vc *VirtualClient) SendGoogle(t *testing.T, s Scenario, streaming bool) *ParsedResponse
SendGoogle sends a request to the Google GenerateContent endpoint.
func (*VirtualClient) SendOpenAIChat ¶
func (vc *VirtualClient) SendOpenAIChat(t *testing.T, s Scenario, streaming bool) *ParsedResponse
SendOpenAIChat sends a request to the OpenAI Chat Completions endpoint.
func (*VirtualClient) SendOpenAIResponses ¶
func (vc *VirtualClient) SendOpenAIResponses(t *testing.T, s Scenario, streaming bool) *ParsedResponse
SendOpenAIResponses sends a request to the OpenAI Responses API endpoint.
func (*VirtualClient) WithServer ¶
func (vc *VirtualClient) WithServer(vs *VirtualServer) *VirtualClient
WithServer binds the client to a VirtualServer.
type VirtualServer ¶
type VirtualServer struct {
// contains filtered or unexported fields
}
func NewVirtualServer ¶
func NewVirtualServer(t *testing.T) *VirtualServer
NewVirtualServer creates a new VirtualServer and registers cleanup with t.
func NewVirtualServerForCLI ¶
func NewVirtualServerForCLI() *VirtualServer
NewVirtualServerForCLI creates a new VirtualServer for CLI use (without testing.T). The caller must call Close() to clean up resources.
**Provider Mock**: This is a provider mock, not a gateway. Routes are /v1/... (provider-native), not /tingly/... (gateway). The gateway transforms /tingly/{scenario}/v1/... requests to provider format before forwarding to this server.
func (*VirtualServer) CallCount ¶
func (vs *VirtualServer) CallCount() int
CallCount returns the total number of requests received.
func (*VirtualServer) Client ¶
func (vs *VirtualServer) Client() *VirtualClient
Client returns a VirtualClient pre-pointed at this VirtualServer and bound to it.
func (*VirtualServer) EndpointHits ¶ added in v0.260611.1
func (vs *VirtualServer) EndpointHits(kind EndpointKind) int
EndpointHits returns how many requests hit a specific provider endpoint. Lets tests assert that, e.g., target=openai_responses actually forwarded to /v1/responses rather than silently falling back to /v1/chat/completions.
func (*VirtualServer) LastRequest ¶ added in v0.260611.1
func (vs *VirtualServer) LastRequest(kind EndpointKind) *CapturedRequest
LastRequest returns the most recent request the gateway forwarded to the given provider endpoint, or nil if that endpoint was never hit.
func (*VirtualServer) RegisterScenario ¶
func (vs *VirtualServer) RegisterScenario(s Scenario)
RegisterScenario registers a scenario so the virtual server can serve its mock responses. If a scenario with the same name was previously registered it is replaced (the registry ordinarily errors on duplicate IDs, so we pre-clear).
func (*VirtualServer) URL ¶
func (vs *VirtualServer) URL() string
URL returns the base URL of the virtual server.