testutil

package
v1.0.66 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package testutil provides shared testing utilities for HTTP-related tests.

Package testutil provides shared utilities for integration testing across the AI Provider Kit. These helpers reduce duplication in integration tests by providing common setup patterns, mock authentication configurations, and test scenarios.

Package testutil provides mock implementations and testing utilities for the AI Provider Kit. These mocks are used across the codebase to facilitate unit and integration testing.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertCommonHeaders added in v1.0.60

func AssertCommonHeaders(t *testing.T, resp *http.Response, expectedHeaders map[string]string)

AssertCommonHeaders asserts that common HTTP headers are present.

func AssertMetricsIncremented added in v1.0.60

func AssertMetricsIncremented(t *testing.T, before, after types.ProviderMetrics, requestDelta int64)

AssertMetricsIncremented asserts that metrics were incremented after an operation.

func AwaitCondition added in v1.0.60

func AwaitCondition(t *testing.T, timeout time.Duration, condition func() bool)

AwaitCondition waits for a condition to be true or times out.

func BadGatewayResponse added in v1.0.60

func BadGatewayResponse(message string) http.HandlerFunc

BadGatewayResponse creates a handler that returns a 502 Bad Gateway.

func BadRequestResponse added in v1.0.60

func BadRequestResponse(message string) http.HandlerFunc

BadRequestResponse creates a handler that returns a 400 Bad Request.

func ChunkedResponseHandler added in v1.0.60

func ChunkedResponseHandler(chunks [][]byte, delays []time.Duration) http.HandlerFunc

ChunkedResponseHandler creates a handler that sends a response in chunks with delays. This simulates slow or streaming responses.

func ConcurrentScenario added in v1.0.60

func ConcurrentScenario(t *testing.T, provider types.Provider, ctx context.Context, concurrency int)

ConcurrentScenario runs concurrent access tests for a provider.

func ContextCancellingHandler added in v1.0.60

func ContextCancellingHandler(delay time.Duration) http.HandlerFunc

ContextCancellingHandler creates a handler that cancels the context after a delay.

func CountingHandler added in v1.0.60

func CountingHandler(handler http.HandlerFunc, headerName string) (http.HandlerFunc, *atomicInt32)

CountingHandler creates a handler that counts the number of times it's called. The count is stored in a header value.

func CreateMockHTTPResponse added in v1.0.60

func CreateMockHTTPResponse(statusCode int, headers map[string]string, body string) *http.Response

CreateMockHTTPResponse creates a mock HTTP response for testing.

func CreateMockJSONResponse added in v1.0.60

func CreateMockJSONResponse(statusCode int, data interface{}) *http.Response

CreateMockJSONResponse creates a mock HTTP response with JSON body.

func CreatedResponse added in v1.0.60

func CreatedResponse(data interface{}) http.HandlerFunc

CreatedResponse creates a handler that returns a 201 Created with JSON data.

func DefaultAuthConfig added in v1.0.60

func DefaultAuthConfig(config types.ProviderConfig) types.AuthConfig

DefaultAuthConfig creates a standard auth config from a provider config.

func DefaultProviderConfig added in v1.0.60

func DefaultProviderConfig(providerType types.ProviderType, name string) types.ProviderConfig

DefaultProviderConfig creates a standard provider config with sensible defaults.

func DelayHandler added in v1.0.60

func DelayHandler(delay time.Duration, handler http.HandlerFunc) http.HandlerFunc

DelayHandler creates a handler that delays before responding.

func DrainBody added in v1.0.60

func DrainBody(t *testing.T, resp *http.Response) []byte

DrainBody reads and closes the response body, useful for testing.

func DrainBodyString added in v1.0.60

func DrainBodyString(t *testing.T, resp *http.Response) string

DrainBodyString reads and closes the response body, returning it as a string.

func ErrorHandler added in v1.0.60

func ErrorHandler(statusCode int, message string) http.HandlerFunc

ErrorHandler creates a handler that responds with an error status and message.

func ErrorScenario added in v1.0.60

func ErrorScenario(t *testing.T, provider types.Provider, ctx context.Context)

ErrorScenario runs standard error handling tests for a provider.

func ForbiddenResponse added in v1.0.60

func ForbiddenResponse(message string) http.HandlerFunc

ForbiddenResponse creates a handler that returns a 403 Forbidden.

func GatewayTimeoutResponse added in v1.0.60

func GatewayTimeoutResponse(message string) http.HandlerFunc

GatewayTimeoutResponse creates a handler that returns a 504 Gateway Timeout.

func HappyPathScenario added in v1.0.60

func HappyPathScenario(t *testing.T, provider types.Provider, ctx context.Context)

HappyPathScenario runs a standard happy path test for a provider.

func InternalServerErrorResponse added in v1.0.60

func InternalServerErrorResponse(message string) http.HandlerFunc

InternalServerErrorResponse creates a handler that returns a 500 Internal Server Error.

func JSONHandler added in v1.0.60

func JSONHandler(data interface{}, statusCode int) http.HandlerFunc

JSONHandler creates a handler that responds with JSON data.

func MakeJSONRequest added in v1.0.60

func MakeJSONRequest(t *testing.T, method, url string, data interface{}) *http.Request

MakeJSONRequest creates an HTTP request with a JSON body.

func MakeRequest added in v1.0.60

func MakeRequest(t *testing.T, method, url string, body io.Reader) *http.Request

MakeRequest creates an HTTP request for testing. It's a convenience wrapper around http.NewRequest.

func MockChatCompletionServer added in v1.0.60

func MockChatCompletionServer(t *testing.T, responseContent string) *httptest.Server

MockChatCompletionServer creates a mock server that returns chat completion responses.

func MockHTTPServer added in v1.0.60

func MockHTTPServer(t *testing.T, config MockServerConfig) *httptest.Server

MockHTTPServer creates a configurable mock HTTP server for testing.

func MockStreamingChatCompletionServer added in v1.0.60

func MockStreamingChatCompletionServer(t *testing.T, chunks []string) *httptest.Server

MockStreamingChatCompletionServer creates a mock server that returns streaming chat completion responses.

func MultiOAuthTestConfig added in v1.0.60

func MultiOAuthTestConfig(count int) []*types.OAuthCredentialSet

MultiOAuthTestConfig creates multiple test OAuth credential sets for failover testing.

func NewLineDelimitedJSONHandler added in v1.0.60

func NewLineDelimitedJSONHandler(objects []interface{}) http.HandlerFunc

NewLineDelimitedJSONHandler creates a handler that streams newline-delimited JSON. This is commonly used by providers like Ollama.

func NewRedirectHandler added in v1.0.60

func NewRedirectHandler(to string, statusCode int) http.HandlerFunc

NewRedirectHandler creates a handler that redirects to another URL.

func NewTestContext added in v1.0.60

func NewTestContext(t *testing.T, timeout time.Duration) context.Context

NewTestContext creates a test context with timeout.

func NewTestServer added in v1.0.60

func NewTestServer(t *testing.T, opts ...ServerOption) *httptest.Server

NewTestServer creates a new HTTP test server with the given options. The server is automatically closed when the test ends via t.Cleanup.

func NoContentResponse added in v1.0.60

func NoContentResponse() http.HandlerFunc

NoContentResponse creates a handler that returns a 204 No Content.

func NotFoundResponse added in v1.0.60

func NotFoundResponse(message string) http.HandlerFunc

NotFoundResponse creates a handler that returns a 404 Not Found.

func OAuthTestConfig added in v1.0.60

func OAuthTestConfig(clientID, clientSecret string, scopes []string) *types.OAuthCredentialSet

OAuthTestConfig creates a test OAuth configuration.

func ParseJSONBody added in v1.0.60

func ParseJSONBody(t *testing.T, resp *http.Response, v interface{})

ParseJSONBody parses the response body as JSON.

func ProviderConfigWithOAuth added in v1.0.60

func ProviderConfigWithOAuth(providerType types.ProviderType, name string, oauthCreds []*types.OAuthCredentialSet) types.ProviderConfig

ProviderConfigWithOAuth creates a provider config with OAuth credentials.

func RequireProviderAuthenticated added in v1.0.60

func RequireProviderAuthenticated(t *testing.T, provider types.Provider)

RequireProviderAuthenticated is a test helper that requires a provider to be authenticated.

func RequireProviderHealthy added in v1.0.60

func RequireProviderHealthy(t *testing.T, provider types.Provider, ctx context.Context)

RequireProviderHealthy is a test helper that requires a provider to be healthy.

func RetryableServer added in v1.0.60

func RetryableServer(errorCount int, errorStatusCode int, successHandler http.HandlerFunc) http.HandlerFunc

RetryableServer creates a server that returns errors a specified number of times before succeeding.

func SSEHandler added in v1.0.60

func SSEHandler(chunks []SSEChunk) http.HandlerFunc

SSEHandler creates a handler that streams Server-Sent Events. The handler supports automatic flushing and proper SSE formatting.

func SSEStreamHandler added in v1.0.60

func SSEStreamHandler(chunks []SSEChunk, delay time.Duration) http.HandlerFunc

SSEStreamHandler creates a handler that streams SSE chunks with delays between them.

func SequentialResponseHandler added in v1.0.60

func SequentialResponseHandler(responses []http.HandlerFunc) http.HandlerFunc

SequentialResponseHandler creates a handler that returns different responses on each call. Useful for testing retry logic.

func ServiceUnavailableResponse added in v1.0.60

func ServiceUnavailableResponse(message string) http.HandlerFunc

ServiceUnavailableResponse creates a handler that returns a 503 Service Unavailable.

func StreamingScenario added in v1.0.60

func StreamingScenario(t *testing.T, provider types.Provider, ctx context.Context)

StreamingScenario runs streaming-specific tests for a provider.

func SuccessResponse added in v1.0.60

func SuccessResponse(data interface{}) http.HandlerFunc

SuccessResponse creates a handler that returns a 200 OK with JSON data.

func TimeoutHandler added in v1.0.60

func TimeoutHandler() http.HandlerFunc

TimeoutHandler creates a handler that never responds, simulating a timeout.

func TooManyRequestsResponse added in v1.0.60

func TooManyRequestsResponse(message string, retryAfter int) http.HandlerFunc

TooManyRequestsResponse creates a handler that returns a 429 Too Many Requests. It can include standard rate limit headers.

func UnauthorizedResponse added in v1.0.60

func UnauthorizedResponse(message string) http.HandlerFunc

UnauthorizedResponse creates a handler that returns a 401 Unauthorized.

func WaitForCondition added in v1.0.60

func WaitForCondition(t *testing.T, condition func() bool, timeout, checkInterval time.Duration, description string)

WaitForCondition waits for a condition to be true, with timeout.

func WebSocketUpgradeHandler added in v1.0.60

func WebSocketUpgradeHandler() http.HandlerFunc

WebSocketUpgradeHandler creates a handler that attempts to upgrade to WebSocket. Note: This is a simplified version for testing - actual WebSocket testing requires more setup.

Types

type ChatMessageBuilder added in v1.0.60

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

ChatMessageBuilder builds chat messages for testing.

func NewChatMessageBuilder added in v1.0.60

func NewChatMessageBuilder() *ChatMessageBuilder

NewChatMessageBuilder creates a new chat message builder.

func (*ChatMessageBuilder) Build added in v1.0.60

func (b *ChatMessageBuilder) Build() []types.ChatMessage

Build returns the built messages.

func (*ChatMessageBuilder) WithAssistant added in v1.0.60

func (b *ChatMessageBuilder) WithAssistant(content string) *ChatMessageBuilder

WithAssistant adds an assistant message.

func (*ChatMessageBuilder) WithSystem added in v1.0.60

func (b *ChatMessageBuilder) WithSystem(content string) *ChatMessageBuilder

WithSystem adds a system message.

func (*ChatMessageBuilder) WithTool added in v1.0.60

func (b *ChatMessageBuilder) WithTool(toolCallID, content string) *ChatMessageBuilder

WithTool adds a tool message.

func (*ChatMessageBuilder) WithUser added in v1.0.60

func (b *ChatMessageBuilder) WithUser(content string) *ChatMessageBuilder

WithUser adds a user message.

type GenerateOptionsBuilder added in v1.0.60

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

GenerateOptionsBuilder builds generate options for testing.

func NewGenerateOptionsBuilder added in v1.0.60

func NewGenerateOptionsBuilder() *GenerateOptionsBuilder

NewGenerateOptionsBuilder creates a new generate options builder.

func (*GenerateOptionsBuilder) Build added in v1.0.60

Build returns the built options.

func (*GenerateOptionsBuilder) WithMaxTokens added in v1.0.60

func (b *GenerateOptionsBuilder) WithMaxTokens(maxTokens int) *GenerateOptionsBuilder

WithMaxTokens sets the max tokens.

func (*GenerateOptionsBuilder) WithMessages added in v1.0.60

func (b *GenerateOptionsBuilder) WithMessages(messages []types.ChatMessage) *GenerateOptionsBuilder

WithMessages sets the messages.

func (*GenerateOptionsBuilder) WithMetadata added in v1.0.60

func (b *GenerateOptionsBuilder) WithMetadata(metadata map[string]interface{}) *GenerateOptionsBuilder

WithMetadata adds metadata.

func (*GenerateOptionsBuilder) WithModel added in v1.0.60

WithModel sets the model.

func (*GenerateOptionsBuilder) WithPrompt added in v1.0.60

func (b *GenerateOptionsBuilder) WithPrompt(prompt string) *GenerateOptionsBuilder

WithPrompt sets a simple prompt.

func (*GenerateOptionsBuilder) WithStreaming added in v1.0.60

func (b *GenerateOptionsBuilder) WithStreaming() *GenerateOptionsBuilder

WithStreaming enables streaming.

func (*GenerateOptionsBuilder) WithTemperature added in v1.0.60

func (b *GenerateOptionsBuilder) WithTemperature(temperature float64) *GenerateOptionsBuilder

WithTemperature sets the temperature.

type MockAuthenticator added in v1.0.55

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

MockAuthenticator is a mock implementation of Authenticator for testing.

func NewMockAuthenticator added in v1.0.55

func NewMockAuthenticator() *MockAuthenticator

NewMockAuthenticator creates a new MockAuthenticator with default values.

func (*MockAuthenticator) Authenticate added in v1.0.55

func (m *MockAuthenticator) Authenticate(ctx context.Context, config types.AuthConfig) error

Authenticate authenticates using the mock authenticator.

func (*MockAuthenticator) GetAuthMethod added in v1.0.55

func (m *MockAuthenticator) GetAuthMethod() types.AuthMethod

GetAuthMethod returns the authentication method used by the mock authenticator.

func (*MockAuthenticator) GetToken added in v1.0.55

func (m *MockAuthenticator) GetToken() (string, error)

GetToken returns the authentication token from the mock authenticator.

func (*MockAuthenticator) IsAuthenticated added in v1.0.55

func (m *MockAuthenticator) IsAuthenticated() bool

IsAuthenticated returns whether the mock authenticator is authenticated.

func (*MockAuthenticator) Logout added in v1.0.55

func (m *MockAuthenticator) Logout(ctx context.Context) error

Logout logs out the mock authenticator.

func (*MockAuthenticator) RefreshToken added in v1.0.55

func (m *MockAuthenticator) RefreshToken(ctx context.Context) error

RefreshToken refreshes the authentication token.

func (*MockAuthenticator) SetAuthenticated added in v1.0.55

func (m *MockAuthenticator) SetAuthenticated(authenticated bool)

SetAuthenticated sets the authenticated state of the mock authenticator.

func (*MockAuthenticator) SetLogoutError added in v1.0.55

func (m *MockAuthenticator) SetLogoutError(err error)

SetLogoutError configures the mock to fail on logout with the given error.

func (*MockAuthenticator) SetRefreshError added in v1.0.55

func (m *MockAuthenticator) SetRefreshError(err error)

SetRefreshError configures the mock to fail on token refresh with the given error.

type MockProvider added in v1.0.55

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

MockProvider is a comprehensive mock implementation of types.Provider for testing. It combines features from multiple test implementations to provide a flexible testing tool.

func NewMockProvider added in v1.0.55

func NewMockProvider(name string, providerType types.ProviderType) *MockProvider

NewMockProvider creates a new MockProvider with sensible defaults.

func (*MockProvider) Authenticate added in v1.0.55

func (m *MockProvider) Authenticate(ctx context.Context, authConfig types.AuthConfig) error

Authenticate authenticates the mock provider with the given configuration.

func (*MockProvider) Configure added in v1.0.55

func (m *MockProvider) Configure(config types.ProviderConfig) error

Configure configures the mock provider with the given configuration.

func (*MockProvider) Description added in v1.0.55

func (m *MockProvider) Description() string

Description returns the description of the mock provider.

func (*MockProvider) GenerateChatCompletion added in v1.0.55

func (m *MockProvider) GenerateChatCompletion(ctx context.Context, options types.GenerateOptions) (types.ChatCompletionStream, error)

GenerateChatCompletion generates a mock chat completion stream.

func (*MockProvider) GetConfig added in v1.0.55

func (m *MockProvider) GetConfig() types.ProviderConfig

GetConfig returns the configuration of the mock provider.

func (*MockProvider) GetDefaultModel added in v1.0.55

func (m *MockProvider) GetDefaultModel() string

GetDefaultModel returns the default model for the mock provider.

func (*MockProvider) GetMetrics added in v1.0.55

func (m *MockProvider) GetMetrics() types.ProviderMetrics

GetMetrics returns the metrics for the mock provider.

func (*MockProvider) GetModels added in v1.0.55

func (m *MockProvider) GetModels(ctx context.Context) ([]types.Model, error)

GetModels returns the list of models supported by the mock provider.

func (*MockProvider) GetToolFormat added in v1.0.55

func (m *MockProvider) GetToolFormat() types.ToolFormat

GetToolFormat returns the tool format supported by the mock provider.

func (*MockProvider) HealthCheck added in v1.0.55

func (m *MockProvider) HealthCheck(ctx context.Context) error

HealthCheck performs a health check on the mock provider.

func (*MockProvider) InvokeServerTool added in v1.0.55

func (m *MockProvider) InvokeServerTool(ctx context.Context, toolName string, params interface{}) (interface{}, error)

InvokeServerTool invokes a server tool (not implemented in mock).

func (*MockProvider) IsAuthenticated added in v1.0.55

func (m *MockProvider) IsAuthenticated() bool

IsAuthenticated returns whether the mock provider is authenticated.

func (*MockProvider) Logout added in v1.0.55

func (m *MockProvider) Logout(ctx context.Context) error

Logout logs out the mock provider.

func (*MockProvider) Name added in v1.0.55

func (m *MockProvider) Name() string

Name returns the name of the mock provider.

func (*MockProvider) SetDescription added in v1.0.55

func (m *MockProvider) SetDescription(description string)

SetDescription allows setting a custom description.

func (*MockProvider) SetHealthy added in v1.0.55

func (m *MockProvider) SetHealthy(healthy bool, err error)

SetHealthy allows setting the health status of the mock provider.

func (*MockProvider) SetModels added in v1.0.55

func (m *MockProvider) SetModels(models []types.Model)

SetModels allows setting custom models for the mock provider.

func (*MockProvider) SupportsResponsesAPI added in v1.0.55

func (m *MockProvider) SupportsResponsesAPI() bool

SupportsResponsesAPI returns whether the mock provider supports the responses API.

func (*MockProvider) SupportsStreaming added in v1.0.55

func (m *MockProvider) SupportsStreaming() bool

SupportsStreaming returns whether the mock provider supports streaming.

func (*MockProvider) SupportsToolCalling added in v1.0.55

func (m *MockProvider) SupportsToolCalling() bool

SupportsToolCalling returns whether the mock provider supports tool calling.

func (*MockProvider) Type added in v1.0.55

func (m *MockProvider) Type() types.ProviderType

Type returns the provider type of the mock provider.

type MockServerConfig added in v1.0.60

type MockServerConfig struct {
	StatusCode    int
	ResponseBody  string
	ResponseDelay time.Duration
	ErrorAfter    int // Return error after this many requests
	RequestCount  int
}

MockServerConfig configures a mock HTTP server for testing.

type MockStream added in v1.0.55

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

MockStream is a mock implementation of types.ChatCompletionStream for testing.

func NewMockStream added in v1.0.55

func NewMockStream() *MockStream

NewMockStream creates a new MockStream with default behavior.

func NewMockStreamWithChunks added in v1.0.55

func NewMockStreamWithChunks(chunks []types.ChatCompletionChunk) *MockStream

NewMockStreamWithChunks creates a new MockStream with custom chunks.

func (*MockStream) Close added in v1.0.55

func (m *MockStream) Close() error

Close closes the mock stream.

func (*MockStream) IsClosed added in v1.0.55

func (m *MockStream) IsClosed() bool

IsClosed returns whether the stream has been closed.

func (*MockStream) Next added in v1.0.55

Next returns the next chunk in the mock stream.

type MockTokenStorage added in v1.0.55

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

MockTokenStorage is a mock implementation of TokenStorage for testing.

func NewMockTokenStorage added in v1.0.55

func NewMockTokenStorage() *MockTokenStorage

NewMockTokenStorage creates a new MockTokenStorage.

func (*MockTokenStorage) CleanupExpired added in v1.0.55

func (m *MockTokenStorage) CleanupExpired() error

CleanupExpired cleans up expired tokens from the mock token storage.

func (*MockTokenStorage) DeleteToken added in v1.0.55

func (m *MockTokenStorage) DeleteToken(key string) error

DeleteToken deletes a token from the mock token storage.

func (*MockTokenStorage) IsTokenValid added in v1.0.55

func (m *MockTokenStorage) IsTokenValid(key string) bool

IsTokenValid checks if a token is valid in the mock token storage.

func (*MockTokenStorage) ListTokens added in v1.0.55

func (m *MockTokenStorage) ListTokens() ([]string, error)

ListTokens lists all tokens in the mock token storage.

func (*MockTokenStorage) RetrieveToken added in v1.0.55

func (m *MockTokenStorage) RetrieveToken(key string) (*types.OAuthConfig, error)

RetrieveToken retrieves a token from the mock token storage.

func (*MockTokenStorage) SetCleanupError added in v1.0.55

func (m *MockTokenStorage) SetCleanupError(err error)

SetCleanupError configures the mock to fail on cleanup with the given error.

func (*MockTokenStorage) SetDeleteError added in v1.0.55

func (m *MockTokenStorage) SetDeleteError(err error)

SetDeleteError configures the mock to fail on delete with the given error.

func (*MockTokenStorage) StoreToken added in v1.0.55

func (m *MockTokenStorage) StoreToken(key string, config *types.OAuthConfig) error

StoreToken stores a token in the mock token storage.

type ProviderTestSetup added in v1.0.60

type ProviderTestSetup struct {
	Provider    types.Provider
	Config      types.ProviderConfig
	AuthConfig  types.AuthConfig
	Context     context.Context
	CleanupFunc func() error
}

ProviderTestSetup contains common test setup for providers.

func NewProviderTestSetup added in v1.0.60

func NewProviderTestSetup(t *testing.T, providerType types.ProviderType, name string) *ProviderTestSetup

NewProviderTestSetup creates a standard provider test setup with sensible defaults. This is a convenience function for integration tests that need a fully configured provider.

func (*ProviderTestSetup) AuthenticateProvider added in v1.0.60

func (s *ProviderTestSetup) AuthenticateProvider(t *testing.T)

AuthenticateProvider authenticates the provider using the auth config.

func (*ProviderTestSetup) Cleanup added in v1.0.60

func (s *ProviderTestSetup) Cleanup(t *testing.T)

Cleanup performs cleanup operations for the test setup.

func (*ProviderTestSetup) VerifyProviderCapabilities added in v1.0.60

func (s *ProviderTestSetup) VerifyProviderCapabilities(t *testing.T, expectsToolCalling, expectsStreaming, expectsResponsesAPI bool)

VerifyProviderCapabilities performs common capability checks.

func (*ProviderTestSetup) WithCleanup added in v1.0.60

func (s *ProviderTestSetup) WithCleanup(cleanup func() error) *ProviderTestSetup

WithCleanup sets a custom cleanup function in the test setup.

func (*ProviderTestSetup) WithContext added in v1.0.60

func (s *ProviderTestSetup) WithContext(ctx context.Context) *ProviderTestSetup

WithContext sets a custom context in the test setup.

func (*ProviderTestSetup) WithProvider added in v1.0.60

func (s *ProviderTestSetup) WithProvider(provider types.Provider) *ProviderTestSetup

WithProvider sets the provider in the test setup.

type RequestInspector added in v1.0.60

type RequestInspector struct {
	LastMethod    string
	LastPath      string
	LastHeaders   http.Header
	LastBody      []byte
	RequestCount  int
	CustomAsserts []func(*http.Request) error
	// contains filtered or unexported fields
}

RequestInspector is a handler that inspects and records request details.

func NewRequestInspector added in v1.0.60

func NewRequestInspector(asserts ...func(*http.Request) error) *RequestInspector

NewRequestInspector creates a new request inspector.

func (*RequestInspector) GetLastRequest added in v1.0.60

func (ri *RequestInspector) GetLastRequest() (method, path string, headers http.Header, body []byte)

GetLastRequest returns the details of the last request.

func (*RequestInspector) GetRequestCount added in v1.0.60

func (ri *RequestInspector) GetRequestCount() int

GetRequestCount returns the number of requests received.

func (*RequestInspector) Handler added in v1.0.60

func (ri *RequestInspector) Handler() http.HandlerFunc

Handler returns the HTTP handler function for the inspector.

type ResponseBuilder added in v1.0.60

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

ResponseBuilder is a builder for creating HTTP test responses.

func NewResponseBuilder added in v1.0.60

func NewResponseBuilder() *ResponseBuilder

NewResponseBuilder creates a new ResponseBuilder.

func (*ResponseBuilder) Build added in v1.0.60

func (b *ResponseBuilder) Build() http.HandlerFunc

Build creates an HTTP handler that returns the configured response.

func (*ResponseBuilder) WithBody added in v1.0.60

func (b *ResponseBuilder) WithBody(body []byte) *ResponseBuilder

WithBody sets the response body.

func (*ResponseBuilder) WithContentType added in v1.0.60

func (b *ResponseBuilder) WithContentType(contentType string) *ResponseBuilder

WithContentType sets the Content-Type header.

func (*ResponseBuilder) WithDelay added in v1.0.60

func (b *ResponseBuilder) WithDelay(delay time.Duration) *ResponseBuilder

WithDelay adds a delay before sending the response.

func (*ResponseBuilder) WithHeader added in v1.0.60

func (b *ResponseBuilder) WithHeader(key, value string) *ResponseBuilder

WithHeader adds a header to the response.

func (*ResponseBuilder) WithJSONBody added in v1.0.60

func (b *ResponseBuilder) WithJSONBody(data interface{}) *ResponseBuilder

WithJSONBody sets the response body from a JSON-serializable object.

func (*ResponseBuilder) WithStatus added in v1.0.60

func (b *ResponseBuilder) WithStatus(code int) *ResponseBuilder

WithStatus sets the HTTP status code.

func (*ResponseBuilder) WithStringBody added in v1.0.60

func (b *ResponseBuilder) WithStringBody(body string) *ResponseBuilder

WithStringBody sets the response body from a string.

type RotatingCredentialProvider added in v1.0.60

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

RotatingCredentialProvider provides rotating test credentials for failover testing.

func NewRotatingCredentialProvider added in v1.0.60

func NewRotatingCredentialProvider(credentials []types.ProviderConfig) *RotatingCredentialProvider

NewRotatingCredentialProvider creates a new rotating credential provider.

func (*RotatingCredentialProvider) GetCurrent added in v1.0.60

GetCurrent returns the current credential without advancing.

func (*RotatingCredentialProvider) GetNext added in v1.0.60

GetNext returns the next credential in the rotation.

type SSEChunk added in v1.0.60

type SSEChunk struct {
	// Event is the optional event name.
	Event string
	// ID is the optional event ID.
	ID string
	// Retry is the optional retry duration in milliseconds.
	Retry int
	// Data is the data payload.
	Data string
	// Comment indicates this is a comment line.
	Comment bool
}

SSEChunk represents a single SSE chunk to be sent.

type ServerOption added in v1.0.60

type ServerOption func(*TestServerConfig)

ServerOption is a functional option for configuring test servers.

func WithHandler added in v1.0.60

func WithHandler(h http.HandlerFunc) ServerOption

WithHandler sets a custom handler for the test server.

func WithResponseHeaders added in v1.0.60

func WithResponseHeaders(headers map[string]string) ServerOption

WithResponseHeaders sets headers to be included in all responses.

func WithTLS added in v1.0.60

func WithTLS() ServerOption

WithTLS enables TLS for the test server.

type StaticCredentialProvider added in v1.0.60

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

StaticCredentialProvider provides static test credentials.

func NewStaticCredentialProvider added in v1.0.60

func NewStaticCredentialProvider(apiKey, baseURL, defaultModel string) *StaticCredentialProvider

NewStaticCredentialProvider creates a new static credential provider.

func (*StaticCredentialProvider) GetAPIKey added in v1.0.60

func (p *StaticCredentialProvider) GetAPIKey() string

GetAPIKey returns the API key.

func (*StaticCredentialProvider) GetBaseURL added in v1.0.60

func (p *StaticCredentialProvider) GetBaseURL() string

GetBaseURL returns the base URL.

func (*StaticCredentialProvider) GetDefaultModel added in v1.0.60

func (p *StaticCredentialProvider) GetDefaultModel() string

GetDefaultModel returns the default model.

func (*StaticCredentialProvider) IsConfigured added in v1.0.60

func (p *StaticCredentialProvider) IsConfigured() bool

IsConfigured returns true if credentials are configured.

type TestCredentialProvider added in v1.0.60

type TestCredentialProvider interface {
	GetAPIKey() string
	GetBaseURL() string
	GetDefaultModel() string
	IsConfigured() bool
}

TestCredentialProvider defines an interface for providing test credentials.

type TestServerConfig added in v1.0.60

type TestServerConfig struct {
	// Handler is the custom HTTP handler to use. If nil, a default handler is used.
	Handler http.HandlerFunc
	// TLS enables TLS for the test server.
	TLS bool
	// ResponseHeaders are headers to set on all responses.
	ResponseHeaders map[string]string
}

TestServerConfig holds configuration for creating test HTTP servers.

Jump to

Keyboard shortcuts

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