testutil

package
v2.38.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: AGPL-3.0 Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// WaitLong is the default timeout for test operations that may take a while
	// (e.g. integration tests with HTTP round-trips).
	WaitLong = 30 * time.Second

	// WaitMedium is a timeout for moderately slow operations.
	WaitMedium = 10 * time.Second

	// WaitShort is a timeout for operations expected to complete quickly.
	WaitShort = 5 * time.Second

	// IntervalFast is a short polling interval for require.Eventually and similar.
	IntervalFast = 50 * time.Millisecond
)

Shared test timeout and interval constants. Using named constants avoids magic numbers and makes timeout policy easy to adjust across the entire test suite.

Variables

This section is empty.

Functions

func KeyFromHeader added in v2.35.0

func KeyFromHeader(name string, h http.Header) string

KeyFromHeader reads the API key an upstream request carried in the named auth header. Authorization headers are unwrapped from their "Bearer " prefix, and other headers are returned verbatim.

func SingleKeyPool added in v2.35.0

func SingleKeyPool(name, key string) *keypool.Pool

SingleKeyPool builds a centralized key pool containing a single key, or nil when key is empty (no centralized credential). It panics if the pool cannot be built, which does not happen for a non-empty key.

Types

type MockProvider

type MockProvider struct {
	NameStr         string
	URL             string
	Disabled        bool
	Bridged         []string
	Passthrough     []string
	InterceptorFunc func(w http.ResponseWriter, r *http.Request, tracer trace.Tracer) (intercept.Interceptor, error)
}

func (*MockProvider) APIDumpDir

func (*MockProvider) APIDumpDir() string

func (*MockProvider) AuthHeader

func (*MockProvider) AuthHeader() string

func (*MockProvider) BaseURL

func (m *MockProvider) BaseURL() string

func (*MockProvider) BridgedRoutes

func (m *MockProvider) BridgedRoutes() []string

func (*MockProvider) CategorizeError added in v2.36.0

func (*MockProvider) CategorizeError(error) *recorder.ErrorType

func (*MockProvider) CircuitBreakerConfig

func (*MockProvider) CircuitBreakerConfig() *config.CircuitBreaker

func (*MockProvider) CreateInterceptor

func (m *MockProvider) CreateInterceptor(w http.ResponseWriter, r *http.Request, tracer trace.Tracer) (intercept.Interceptor, error)

func (*MockProvider) Enabled added in v2.34.0

func (m *MockProvider) Enabled() bool

func (*MockProvider) KeyFailoverConfig added in v2.34.0

func (*MockProvider) KeyFailoverConfig(_ slog.Logger) keypool.KeyFailoverConfig

func (*MockProvider) KeyPool added in v2.35.0

func (*MockProvider) KeyPool() *keypool.Pool

func (*MockProvider) Name

func (m *MockProvider) Name() string

func (*MockProvider) PassthroughRoutes

func (m *MockProvider) PassthroughRoutes() []string

func (*MockProvider) RoutePrefix

func (m *MockProvider) RoutePrefix() string

func (*MockProvider) Type

func (m *MockProvider) Type() string

type MockRecorder

type MockRecorder struct {
	// contains filtered or unexported fields
}

MockRecorder is a test implementation of aibridge.Recorder that captures all recording calls for test assertions.

func (*MockRecorder) RecordInterception

func (m *MockRecorder) RecordInterception(_ context.Context, req *recorder.InterceptionRecord) error

func (*MockRecorder) RecordInterceptionEnded

func (m *MockRecorder) RecordInterceptionEnded(_ context.Context, req *recorder.InterceptionRecordEnded) error

func (*MockRecorder) RecordModelThought

func (m *MockRecorder) RecordModelThought(_ context.Context, req *recorder.ModelThoughtRecord) error

func (*MockRecorder) RecordPromptUsage

func (m *MockRecorder) RecordPromptUsage(_ context.Context, req *recorder.PromptUsageRecord) error

func (*MockRecorder) RecordTokenUsage

func (m *MockRecorder) RecordTokenUsage(_ context.Context, req *recorder.TokenUsageRecord) error

func (*MockRecorder) RecordToolUsage

func (m *MockRecorder) RecordToolUsage(_ context.Context, req *recorder.ToolUsageRecord) error

func (*MockRecorder) RecordedInterceptionEnd

func (m *MockRecorder) RecordedInterceptionEnd(id string) *recorder.InterceptionRecordEnded

RecordedInterceptionEnd returns the stored InterceptionRecordEnded for the given interception ID, or nil if not found.

func (*MockRecorder) RecordedInterceptions

func (m *MockRecorder) RecordedInterceptions() []*recorder.InterceptionRecord

RecordedInterceptions returns a copy of recorded interceptions in a thread-safe manner. Note: This is a shallow clone (see RecordedTokenUsages for details).

func (*MockRecorder) RecordedModelThoughts

func (m *MockRecorder) RecordedModelThoughts() []*recorder.ModelThoughtRecord

RecordedModelThoughts returns a copy of recorded model thoughts in a thread-safe manner. Note: This is a shallow clone (see RecordedTokenUsages for details).

func (*MockRecorder) RecordedPromptUsages

func (m *MockRecorder) RecordedPromptUsages() []*recorder.PromptUsageRecord

RecordedPromptUsages returns a copy of recorded prompt usages in a thread-safe manner. Note: This is a shallow clone (see RecordedTokenUsages for details).

func (*MockRecorder) RecordedTokenUsages

func (m *MockRecorder) RecordedTokenUsages() []*recorder.TokenUsageRecord

RecordedTokenUsages returns a copy of recorded token usages in a thread-safe manner. Note: This is a shallow clone - the slice is copied but the pointers reference the same underlying records. This is sufficient for our test assertions which only read the data and don't modify the records.

func (*MockRecorder) RecordedToolUsages

func (m *MockRecorder) RecordedToolUsages() []*recorder.ToolUsageRecord

RecordedToolUsages returns a copy of recorded tool usages in a thread-safe manner. Note: This is a shallow clone (see RecordedTokenUsages for details).

func (*MockRecorder) ToolUsages

func (m *MockRecorder) ToolUsages() []*recorder.ToolUsageRecord

ToolUsages returns the raw toolUsages slice for direct field access in tests. Use RecordedToolUsages() for thread-safe access when assertions don't need direct field access.

func (*MockRecorder) TotalCacheReadInputTokens

func (m *MockRecorder) TotalCacheReadInputTokens() int64

TotalCacheReadInputTokens returns the sum of cache read input tokens across all recorded token usages.

func (*MockRecorder) TotalCacheWriteInputTokens

func (m *MockRecorder) TotalCacheWriteInputTokens() int64

TotalCacheWriteInputTokens returns the sum of cache write input tokens across all recorded token usages.

func (*MockRecorder) TotalInputTokens

func (m *MockRecorder) TotalInputTokens() int64

TotalInputTokens returns the sum of input tokens across all recorded token usages.

func (*MockRecorder) TotalOutputTokens

func (m *MockRecorder) TotalOutputTokens() int64

TotalOutputTokens returns the sum of output tokens across all recorded token usages.

func (*MockRecorder) VerifyAllInterceptionsEnded

func (m *MockRecorder) VerifyAllInterceptionsEnded(t *testing.T)

VerifyAllInterceptionsEnded verifies all recorded interceptions have been marked as completed.

func (*MockRecorder) VerifyModelThoughtsRecorded

func (m *MockRecorder) VerifyModelThoughtsRecorded(t *testing.T, expected []recorder.ModelThoughtRecord)

type MockServerProxier added in v2.35.0

type MockServerProxier struct {
	Tools []*mcp.Tool
	// ResolveAnyTool makes GetTool return a stub tool, backed by a
	// StubToolCaller, for any id not present in Tools, and makes ListTools
	// report one stub when Tools is empty so the interceptor injects tools.
	// Use it to exercise injected-tool agentic loops where the test does not
	// need to validate which tool was called.
	ResolveAnyTool bool
}

MockServerProxier is a test mcp.ServerProxier that injects a fixed set of tools. When ResolveAnyTool is set, ListTools reports a stub tool and GetTool resolves any unregistered tool to a stub, so callers that only need the tool loop to proceed need not register each tool the fixture might call.

func (*MockServerProxier) CallTool added in v2.35.0

func (*MockServerProxier) GetTool added in v2.35.0

func (m *MockServerProxier) GetTool(id string) *mcp.Tool

func (*MockServerProxier) Init added in v2.35.0

func (*MockServerProxier) ListTools added in v2.35.0

func (m *MockServerProxier) ListTools() []*mcp.Tool

func (*MockServerProxier) Shutdown added in v2.35.0

type MockUpstream added in v2.35.0

type MockUpstream struct {
	*httptest.Server

	// Calls is incremented atomically on every request.
	Calls atomic.Uint32

	// StatusCode overrides the HTTP status for non-streaming responses.
	// Zero means 200.
	StatusCode int

	// AllowOverflow disables the strict call-count check. When true,
	// requests beyond the last response repeat that response, and the
	// cleanup assertion only verifies that at least len(responses)
	// requests were made. This is useful for error-response tests where
	// the bridge may retry.
	AllowOverflow bool
	// contains filtered or unexported fields
}

MockUpstream replays txtar fixture responses, validates incoming request bodies, and counts calls. It stands in for a real AI provider API (Anthropic, OpenAI) during integration tests.

func NewMockUpstream added in v2.35.0

func NewMockUpstream(ctx context.Context, t *testing.T, responses ...UpstreamResponse) *MockUpstream

NewMockUpstream creates a started httptest.Server that replays fixture responses. Responses are returned in order: first call → first response. The test fails if the number of requests doesn't match the number of responses (when AllowOverflow is not set, default).

srv := NewMockUpstream(ctx, t, NewFixtureResponse(fix))                        // simple
srv := NewMockUpstream(ctx, t, NewFixtureResponse(fix), NewFixtureToolResponse(fix)) // multi-turn

func (*MockUpstream) ReceivedRequests added in v2.35.0

func (ms *MockUpstream) ReceivedRequests() []ReceivedRequest

ReceivedRequests returns a copy of all requests received so far.

type ReceivedRequest added in v2.35.0

type ReceivedRequest struct {
	Method string
	Path   string
	Header http.Header
	Body   []byte
}

ReceivedRequest captures the details of a single request handled by MockUpstream.

type StubToolCaller added in v2.35.0

type StubToolCaller struct{}

StubToolCaller is a minimal tool client that returns a fixed text result.

func (StubToolCaller) CallTool added in v2.35.0

type UpstreamResponse added in v2.35.0

type UpstreamResponse struct {
	Streaming []byte // returned when the request has "stream": true.
	Blocking  []byte // returned for non-streaming requests.

	// OnRequest, if non-nil, is called with the incoming request and body
	// before the response is sent. Use it for per-request assertions.
	OnRequest func(r *http.Request, body []byte)
}

UpstreamResponse defines a single response that MockUpstream will replay for one incoming request. Use NewFixtureResponse or NewFixtureToolResponse to construct one from a parsed txtar archive.

func NewErrorResponse added in v2.35.0

func NewErrorResponse(status int, retryAfter string) UpstreamResponse

NewErrorResponse returns an UpstreamResponse that replays a raw HTTP error response with the given status code and optional Retry-After header. SDK auto-retries are disabled via x-should-retry.

func NewFixtureResponse added in v2.35.0

func NewFixtureResponse(fix fixtures.Fixture) UpstreamResponse

NewFixtureResponse creates an UpstreamResponse from a parsed fixture archive. It reads whichever of 'streaming' and 'non-streaming' sections exist; not every fixture has both (e.g. error fixtures may only define one).

func NewFixtureToolResponse added in v2.35.0

func NewFixtureToolResponse(fix fixtures.Fixture) UpstreamResponse

NewFixtureToolResponse creates an UpstreamResponse from the tool-call fixture files. It reads whichever of 'streaming/tool-call' and 'non-streaming/tool-call' sections exist.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL