Documentation
¶
Overview ¶
Package test provides test utilities for the client package.
Package test provides test utilities for the client package.
Package test provides utilities for testing the MCP implementation.
Index ¶
- Variables
- func AssertContentEquivalence(t *testing.T, version1 string, content1 interface{}, version2 string, ...)
- func AssertCorrectFallback(t *testing.T, clientVersions []string, serverVersions []string, ...)
- func AssertFeatureSupport(t *testing.T, version string, response []byte, featurePath ...string)
- func AssertJSONContains(t *testing.T, jsonData []byte, expectedKey string, expectedValue interface{})
- func AssertJSONPath(t *testing.T, jsonData []byte, path []string, expectedValue interface{})
- func AssertMethodEquals(t *testing.T, jsonData []byte, expectedMethod string)
- func AssertMethodInHistory(t *testing.T, m *MockTransport, expectedMethod string)
- func AssertRequestParams(t *testing.T, request []byte, expected map[string]interface{})
- func AssertResponseError(t *testing.T, jsonData []byte, expectedCode int)
- func AssertResponseSuccess(t *testing.T, jsonData []byte)
- func AssertRootOperations(t *testing.T, version string, transport *MockTransport)
- func AssertVersionCapabilities(t *testing.T, version string, response []byte)
- func AssertVersionCompatibility(t *testing.T, version string, jsonData []byte)
- func AssertVersionFallbackMatrix(t *testing.T, ...)
- func AssertVersionMatrixCompatibility(t *testing.T, fn func(t *testing.T, clientVersion, serverVersion string))
- func AssertVersionNegotiation(t *testing.T, clientVersion, serverVersion string, response []byte)
- func AssertVersionSpecificError(t *testing.T, version string, response []byte, expectedCode int)
- func AssertVersionSpecificOperation(t *testing.T, version string, operation func() ([]byte, error), ...)
- func AssertVersionSpecificResource(t *testing.T, version string, response []byte)
- func Capabilities(version string) map[string]interface{}
- func ClientInfo(name, version string) map[string]interface{}
- func CreateAudioSamplingMessage(role, audioData, mimeType string) client.SamplingMessage
- func CreateEmptyResponse(id interface{}) []byte
- func CreateImageSamplingMessage(role, imageData, mimeType string) client.SamplingMessage
- func CreateInitializeResponse(version string, capabilities map[string]interface{}) []byte
- func CreateMockResourceResponse(version string, id interface{}) []byte
- func CreateNotificationResponse(method string, params map[string]interface{}) []byte
- func CreatePromptResponse(prompt, rendered string) []byte
- func CreatePromptResponseWithID(id interface{}, prompt, rendered string, metadata map[string]interface{}) []byte
- func CreateResource(uri, text string, content []interface{}) map[string]interface{}
- func CreateResourceContent(contentType string, data interface{}) interface{}
- func CreateResourceResponse(version string, content interface{}) []byte
- func CreateResourceResponseWithPath(version string, path string, content interface{}, id interface{}) []byte
- func CreateRoot(path, name string, metadata map[string]interface{}) map[string]interface{}
- func CreateRootListResponse(version string, id interface{}) []byte
- func CreateRootsListResponse(id interface{}, roots []map[string]interface{}) []byte
- func CreateSamplingAudioResponse(id interface{}, version string, data string, mimeType string, model string) []byte
- func CreateSamplingImageResponse(id interface{}, version string, data string, mimeType string, model string) []byte
- func CreateSamplingResponse(id interface{}, version string, text string, options map[string]interface{}) []byte
- func CreateSamplingTextResponse(id interface{}, version string, text string, model string) []byte
- func CreateStreamingChatRequest(messages []client.SamplingMessage, systemPrompt, version string) (*client.SamplingOptions, error)
- func CreateStreamingSamplingCompletion(id interface{}, version string, model string, stopReason string) ([]byte, error)
- func CreateStreamingSamplingResponse(id interface{}, version string, options map[string]interface{}) ([]byte, error)
- func CreateStreamingSamplingTextChunk(id interface{}, version string, chunkID string, text string) ([]byte, error)
- func CreateTextSamplingMessage(role, text string) client.SamplingMessage
- func CreateToolErrorResponse(id interface{}, code int, message string, data interface{}) []byte
- func CreateToolResponse(output interface{}) []byte
- func CreateToolResponseWithID(id interface{}, output interface{}, metadata map[string]interface{}) []byte
- func CreateVersionError(version string, id interface{}, code int, message string, data interface{}) []byte
- func CreateVersionSpecificInitializeResponse(version string, id interface{}) []byte
- func EmptySuccessResponse(id interface{}) map[string]interface{}
- func EnsureConnected(transport *MockTransport)
- func ErrorResponse(code int, message string) map[string]interface{}
- func ErrorResponseWithID(id interface{}, code int, message string, data interface{}) map[string]interface{}
- func GetFixtureData(t *testing.T, fixtureName string) map[string]interface{}
- func GetJSONRPCID(jsonData []byte) (interface{}, error)
- func GetJSONRPCParams(jsonData []byte) (map[string]interface{}, error)
- func InitializeRequest(clientName, clientVersion string, supportedVersions []string) map[string]interface{}
- func InitializeResponse(id interface{}, version string, serverName, serverVersion string, ...) map[string]interface{}
- func IsRequestMethod(method string) func([]byte) bool
- func IsStreamingSupportedForVersion(version string) bool
- func IsStreamingSupportedInVersion(version string) bool
- func NewMockSamplingResponse(role string, contentType string, contentText string) *client.SamplingResponse
- func NewSamplingConfig() client.SamplingModelPreferences
- func NewSamplingRequest(messages []client.SamplingMessage, prefs client.SamplingModelPreferences) *client.SamplingOptions
- func NewStreamingSamplingRequest(messages []client.SamplingMessage, prefs client.SamplingModelPreferences) *client.SamplingOptions
- func NotificationRequest(method string, params interface{}) map[string]interface{}
- func ParseResponse(t *testing.T, response []byte) *jsonrpc.JSONRPC
- func ParseVersionSpecificResource(t *testing.T, version string, response []byte) *jsonrpc.JSONRPC
- func PromptRequest(name string, variables map[string]interface{}) map[string]interface{}
- func PromptRequestWithID(id interface{}, name string, variables map[string]interface{}) map[string]interface{}
- func RequestHasID(id interface{}) func([]byte) bool
- func ResourceRequest(path string) map[string]interface{}
- func ResourceRequestWithID(id interface{}, path string) map[string]interface{}
- func ResourceRequestWithOptions(id interface{}, path string, options map[string]interface{}) map[string]interface{}
- func RootsListChangedNotification() map[string]interface{}
- func SamplingCreateMessageMatcher() func([]byte) bool
- func SamplingCreateStreamingMessageMatcher() func([]byte) bool
- func ServerInfo(name, version string) map[string]interface{}
- func SetSamplingHandler(c client.Client, handler client.SamplingHandler) client.Client
- func ShutdownRequest(id interface{}) map[string]interface{}
- func SuccessResponse(id interface{}, result interface{}) map[string]interface{}
- func TimestampNow() string
- func ToolRequest(name string, args map[string]interface{}) map[string]interface{}
- func ToolRequestWithID(id interface{}, name string, args map[string]interface{}) map[string]interface{}
- func VerifyFixture(t *testing.T, fixtureName string, c client.Client)
- type MockError
- type MockTransport
- func NewMockTransport() *MockTransport
- func SetupClientWithMockTransport(t *testing.T, version string) (client.Client, *MockTransport)
- func SetupClientWithOptions(t *testing.T, version string, options ...client.Option) (client.Client, *MockTransport)
- func SetupFixture(t *testing.T, fixtureName string, version string) (client.Client, *MockTransport)
- func SetupMockTransport(version string) *MockTransport
- func SetupSamplingMockTransport(version string, mockTransport *MockTransport) *MockTransport
- func (m *MockTransport) ClearHistory() *MockTransport
- func (m *MockTransport) ClearResponses() *MockTransport
- func (m *MockTransport) Connect() error
- func (m *MockTransport) ConnectWithContext(ctx context.Context) error
- func (m *MockTransport) Disconnect() error
- func (m *MockTransport) GetRequestByID(id interface{}) *RequestRecord
- func (m *MockTransport) GetRequestHistory() []RequestRecord
- func (m *MockTransport) GetRequestsByMethod(method string) []RequestRecord
- func (m *MockTransport) QueueConditionalResponse(data []byte, err error, condition func([]byte) bool) *MockTransport
- func (m *MockTransport) QueueFlaky(data []byte, err error, probability float64) *MockTransport
- func (m *MockTransport) QueueResponse(data []byte, err error) *MockTransport
- func (m *MockTransport) QueueResponseWithDelay(data []byte, err error, delay time.Duration) *MockTransport
- func (m *MockTransport) RegisterNotificationHandler(handler func(method string, params []byte))
- func (m *MockTransport) Send(message []byte) ([]byte, error)
- func (m *MockTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (m *MockTransport) SetConnectionTimeout(timeout time.Duration)
- func (m *MockTransport) SetErrorRate(errorPercent int) *MockTransport
- func (m *MockTransport) SetLatency(latencyMs int, jitterPercent int) *MockTransport
- func (m *MockTransport) SetPacketLoss(lossPercent int) *MockTransport
- func (m *MockTransport) SetRequestTimeout(timeout time.Duration)
- func (m *MockTransport) SimulateDisconnect() *MockTransport
- func (m *MockTransport) SimulateDisconnectAfter(requestCount int) *MockTransport
- func (m *MockTransport) SimulateNotification(method string, message []byte)
- func (m *MockTransport) WaitForNotification(method string, timeout time.Duration) bool
- func (m *MockTransport) WithDefaultResponse(data []byte, err error) *MockTransport
- func (m *MockTransport) WithNetworkConditions(conditions NetworkConditions) *MockTransport
- type NetworkConditions
- type RequestRecord
- type ResponseConfig
- type ServerWithHandler
- type TestFixture
Constants ¶
This section is empty.
Variables ¶
var CommonFixtureSetups = map[string]func(*testing.T, *MockTransport){
"BasicClient": setupBasicClient,
"ResourceServer": setupResourceServer,
"ToolServer": setupToolServer,
"VersionNegotiation": setupVersionNegotiation,
}
CommonFixtureSetups defines setup functions to avoid circular dependencies
var CommonFixtures = map[string]TestFixture{ "BasicClient": { Name: "BasicClient", Description: "Basic client setup with initialization response", Setup: setupBasicClient, Verify: func(t *testing.T, c client.Client) { if !c.IsInitialized() { t.Fatal("Client should be initialized") } }, }, "ResourceServer": { Name: "ResourceServer", Description: "Server with sample resources for testing resource operations", Setup: setupResourceServer, Verify: func(t *testing.T, c client.Client) { result, err := c.GetResource("/test/doc1.md") if err != nil { t.Fatalf("Failed to get resource: %v", err) } if result == nil { t.Fatal("Resource response should not be nil") } }, Data: map[string]interface{}{ "resourcePaths": []string{ "/test/doc1.md", "/test/doc2.md", "/test/image.jpg", "/test/data.json", }, }, }, "ToolServer": { Name: "ToolServer", Description: "Server with sample tools for testing tool operations", Setup: setupToolServer, Verify: func(t *testing.T, c client.Client) { result, err := c.CallTool("calculator", map[string]interface{}{}) if err != nil { t.Fatalf("Failed to call tool: %v", err) } if result == nil { t.Fatal("Tool response should not be nil") } }, Data: map[string]interface{}{ "tools": []string{ "calculator", "echo", "list", "error", }, }, }, "VersionNegotiation": { Name: "VersionNegotiation", Description: "Fixture for testing version negotiation and fallback", Setup: setupVersionNegotiation, Verify: func(t *testing.T, c client.Client) { }, Data: map[string]interface{}{ "serverVersions": map[string][]string{ "newest": {"draft", "2024-11-05", "2025-03-26"}, "legacy": {"draft", "2024-11-05"}, "draftOnly": {"draft"}, "middleOnly": {"2024-11-05"}, "newestOnly": {"2025-03-26"}, }, }, }, }
CommonFixtures contains a set of commonly used test fixtures
Functions ¶
func AssertContentEquivalence ¶
func AssertContentEquivalence(t *testing.T, version1 string, content1 interface{}, version2 string, content2 interface{})
AssertContentEquivalence compares resource content across different protocol versions
func AssertCorrectFallback ¶
func AssertCorrectFallback(t *testing.T, clientVersions []string, serverVersions []string, expectedVersion string)
AssertCorrectFallback verifies that the client correctly falls back to a supported version
func AssertFeatureSupport ¶
AssertFeatureSupport verifies that a specific feature is supported in a given protocol version based on the capabilities response
func AssertJSONContains ¶
func AssertJSONContains(t *testing.T, jsonData []byte, expectedKey string, expectedValue interface{})
AssertJSONContains checks if the given JSON data contains the expected key with expected value
func AssertJSONPath ¶
AssertJSONPath checks if the given JSON data contains a value at the specified path
func AssertMethodEquals ¶
AssertMethodEquals checks if the JSON-RPC method matches the expected value
func AssertMethodInHistory ¶ added in v1.5.0
func AssertMethodInHistory(t *testing.T, m *MockTransport, expectedMethod string)
AssertMethodInHistory checks if the specified method was sent in the message history
func AssertRequestParams ¶
AssertRequestParams checks if a request has the expected parameters
func AssertResponseError ¶
AssertResponseError checks if the JSON-RPC response indicates an error with the expected code
func AssertResponseSuccess ¶
AssertResponseSuccess checks if the JSON-RPC response indicates success
func AssertRootOperations ¶
func AssertRootOperations(t *testing.T, version string, transport *MockTransport)
AssertRootOperations verifies that the root notifications work correctly for the given protocol version (correct MCP behavior)
func AssertVersionCapabilities ¶
AssertVersionCapabilities verifies that the capabilities in the response are appropriate for the protocol version
func AssertVersionCompatibility ¶
AssertVersionCompatibility verifies a message is compatible with the specified version
func AssertVersionFallbackMatrix ¶
func AssertVersionFallbackMatrix(t *testing.T, fallbackFn func(t *testing.T, clientVersions, serverVersions []string) string)
AssertVersionFallbackMatrix tests that a client correctly falls back to compatible versions across different combinations
func AssertVersionMatrixCompatibility ¶
func AssertVersionMatrixCompatibility(t *testing.T, fn func(t *testing.T, clientVersion, serverVersion string))
AssertVersionMatrixCompatibility verifies client behavior across a matrix of client and server versions
func AssertVersionNegotiation ¶
AssertVersionNegotiation verifies that the client correctly negotiates the protocol version with the server
func AssertVersionSpecificError ¶
AssertVersionSpecificError checks if an error response is properly formatted for the specified protocol version and has the expected code
func AssertVersionSpecificOperation ¶
func AssertVersionSpecificOperation(t *testing.T, version string, operation func() ([]byte, error), validator func(t *testing.T, version string, response []byte))
AssertVersionSpecificOperation tests that an operation behaves correctly based on the specific protocol version
func AssertVersionSpecificResource ¶
AssertVersionSpecificResource verifies that a resource response follows the correct structure for the specified protocol version
func Capabilities ¶
Capabilities generates capabilities for the given protocol version
func ClientInfo ¶
ClientInfo generates client information with the given name and version
func CreateAudioSamplingMessage ¶ added in v1.5.0
func CreateAudioSamplingMessage(role, audioData, mimeType string) client.SamplingMessage
CreateAudioSamplingMessage creates an audio sampling message for testing
func CreateEmptyResponse ¶
func CreateEmptyResponse(id interface{}) []byte
CreateEmptyResponse creates a simple success response with empty result
func CreateImageSamplingMessage ¶ added in v1.5.0
func CreateImageSamplingMessage(role, imageData, mimeType string) client.SamplingMessage
CreateImageSamplingMessage creates an image sampling message for testing
func CreateInitializeResponse ¶
CreateInitializeResponse creates a mock initialize response for the specified version
func CreateMockResourceResponse ¶
CreateMockResourceResponse creates a structured resource response for testing
func CreateNotificationResponse ¶
CreateNotificationResponse creates a notification (no ID) response
func CreatePromptResponse ¶
CreatePromptResponse creates a prompt response with the given prompt template and rendered text This matches the new PromptResponse struct with description and messages
func CreatePromptResponseWithID ¶
func CreatePromptResponseWithID(id interface{}, prompt, rendered string, metadata map[string]interface{}) []byte
CreatePromptResponseWithID creates a prompt response with a specific ID This matches the new PromptResponse struct with description and messages
func CreateResource ¶
CreateResource creates a complete resource with the given URI, text, and content
func CreateResourceContent ¶
func CreateResourceContent(contentType string, data interface{}) interface{}
CreateResourceContent generates content for a resource based on the given type
func CreateResourceResponse ¶
CreateResourceResponse creates a resource response for the given version and content
func CreateResourceResponseWithPath ¶
func CreateResourceResponseWithPath(version string, path string, content interface{}, id interface{}) []byte
CreateResourceResponseWithPath creates a resource response for a specific resource path
func CreateRoot ¶
CreateRoot creates a root object for roots/list responses
func CreateRootListResponse ¶
CreateRootListResponse creates a response for roots/list request
func CreateRootsListResponse ¶
CreateRootsListResponse creates a response for a roots/list request
func CreateSamplingAudioResponse ¶
func CreateSamplingAudioResponse(id interface{}, version string, data string, mimeType string, model string) []byte
CreateSamplingAudioResponse creates an audio sampling response
func CreateSamplingImageResponse ¶
func CreateSamplingImageResponse(id interface{}, version string, data string, mimeType string, model string) []byte
CreateSamplingImageResponse creates an image sampling response
func CreateSamplingResponse ¶
func CreateSamplingResponse(id interface{}, version string, text string, options map[string]interface{}) []byte
CreateSamplingResponse generates a sampling response in the format appropriate for the specified version
func CreateSamplingTextResponse ¶
CreateSamplingTextResponse is a convenience function to create a text sampling response
func CreateStreamingChatRequest ¶ added in v1.5.0
func CreateStreamingChatRequest(messages []client.SamplingMessage, systemPrompt, version string) (*client.SamplingOptions, error)
CreateStreamingChatRequest creates a streaming sampling request for testing
func CreateStreamingSamplingCompletion ¶
func CreateStreamingSamplingCompletion(id interface{}, version string, model string, stopReason string) ([]byte, error)
CreateStreamingSamplingCompletion creates a streaming completion response
func CreateStreamingSamplingResponse ¶
func CreateStreamingSamplingResponse(id interface{}, version string, options map[string]interface{}) ([]byte, error)
CreateStreamingSamplingResponse generates a streaming response in the format appropriate for the specified version Note: streaming is only supported in v20241105 and v20250326, not in draft
func CreateStreamingSamplingTextChunk ¶
func CreateStreamingSamplingTextChunk(id interface{}, version string, chunkID string, text string) ([]byte, error)
CreateStreamingSamplingTextChunk creates a streaming text chunk response
func CreateTextSamplingMessage ¶ added in v1.5.0
func CreateTextSamplingMessage(role, text string) client.SamplingMessage
CreateTextSamplingMessage creates a text sampling message for testing
func CreateToolErrorResponse ¶
CreateToolErrorResponse creates an error response for a tool execution
func CreateToolResponse ¶
func CreateToolResponse(output interface{}) []byte
CreateToolResponse creates a response for a tool execution with the given output
func CreateToolResponseWithID ¶
func CreateToolResponseWithID(id interface{}, output interface{}, metadata map[string]interface{}) []byte
CreateToolResponseWithID creates a response for a tool execution with a specific ID
func CreateVersionError ¶
func CreateVersionError(version string, id interface{}, code int, message string, data interface{}) []byte
CreateVersionError creates an error response with version-specific format
func CreateVersionSpecificInitializeResponse ¶
CreateVersionSpecificInitializeResponse creates an initialize response for the given version with appropriate capabilities for that version
func EmptySuccessResponse ¶
func EmptySuccessResponse(id interface{}) map[string]interface{}
EmptySuccessResponse generates a success response with an empty result
func EnsureConnected ¶
func EnsureConnected(transport *MockTransport)
EnsureConnected sets the Connected property of the MockTransport to true to prevent "connection closed" errors in tests
func ErrorResponse ¶
ErrorResponse generates an error response with the given code and message
func ErrorResponseWithID ¶
func ErrorResponseWithID(id interface{}, code int, message string, data interface{}) map[string]interface{}
ErrorResponseWithID generates an error response with a specific ID
func GetFixtureData ¶
GetFixtureData gets data from a named fixture
func GetJSONRPCID ¶
GetJSONRPCID extracts the ID from a JSON-RPC message
func GetJSONRPCParams ¶
GetJSONRPCParams extracts the params from a JSON-RPC message
func InitializeRequest ¶
func InitializeRequest(clientName, clientVersion string, supportedVersions []string) map[string]interface{}
InitializeRequest generates an initialize request with the given client info
func InitializeResponse ¶
func InitializeResponse(id interface{}, version string, serverName, serverVersion string, capabilities map[string]interface{}) map[string]interface{}
InitializeResponse generates an initialize response for the given version
func IsRequestMethod ¶
IsRequestMethod checks if a given request uses the specified method
func IsStreamingSupportedForVersion ¶ added in v1.5.0
IsStreamingSupportedForVersion checks if streaming is supported for a version
func IsStreamingSupportedInVersion ¶
IsStreamingSupportedInVersion returns true if streaming is supported in the specified version
func NewMockSamplingResponse ¶
func NewMockSamplingResponse(role string, contentType string, contentText string) *client.SamplingResponse
NewMockSamplingResponse creates a mock sampling response for testing
func NewSamplingConfig ¶ added in v1.5.0
func NewSamplingConfig() client.SamplingModelPreferences
NewSamplingConfig creates a new sampling model preferences for testing
func NewSamplingRequest ¶ added in v1.5.0
func NewSamplingRequest(messages []client.SamplingMessage, prefs client.SamplingModelPreferences) *client.SamplingOptions
NewSamplingRequest creates a new sampling options for testing
func NewStreamingSamplingRequest ¶ added in v1.5.0
func NewStreamingSamplingRequest(messages []client.SamplingMessage, prefs client.SamplingModelPreferences) *client.SamplingOptions
NewStreamingSamplingRequest creates a new streaming sampling options for testing
func NotificationRequest ¶
NotificationRequest generates a notification with the given method and params
func ParseResponse ¶
ParseResponse parses a JSON-RPC response using the JSONRPC struct
func ParseVersionSpecificResource ¶
ParseVersionSpecificResource parses a resource response and checks if it matches the expected format for the specified version
func PromptRequest ¶
PromptRequest generates a prompt request with the given name and variables
func PromptRequestWithID ¶
func PromptRequestWithID(id interface{}, name string, variables map[string]interface{}) map[string]interface{}
PromptRequestWithID generates a prompt request with a specific ID
func RequestHasID ¶
RequestHasID checks if a given request has the specified ID
func ResourceRequest ¶
ResourceRequest generates a resource request for the given path
func ResourceRequestWithID ¶
ResourceRequestWithID generates a resource request with a specific ID
func ResourceRequestWithOptions ¶
func ResourceRequestWithOptions(id interface{}, path string, options map[string]interface{}) map[string]interface{}
ResourceRequestWithOptions generates a resource request with additional options
func RootsListChangedNotification ¶ added in v1.6.0
func RootsListChangedNotification() map[string]interface{}
RootsListChangedNotification generates a notification for when roots change
func SamplingCreateMessageMatcher ¶
SamplingCreateMessageMatcher creates a condition function that matches sampling/createMessage requests
func SamplingCreateStreamingMessageMatcher ¶
SamplingCreateStreamingMessageMatcher creates a condition function that matches sampling/createStreamingMessage requests
func ServerInfo ¶
ServerInfo generates server information with the given name and version
func SetSamplingHandler ¶
SetSamplingHandler is a helper function to set a sampling handler on a client
func ShutdownRequest ¶
func ShutdownRequest(id interface{}) map[string]interface{}
ShutdownRequest generates a shutdown request
func SuccessResponse ¶
func SuccessResponse(id interface{}, result interface{}) map[string]interface{}
SuccessResponse generates a success response with the given result
func TimestampNow ¶
func TimestampNow() string
TimestampNow generates a current timestamp string in ISO 8601 format
func ToolRequest ¶
ToolRequest generates a tool request with the given name and arguments
func ToolRequestWithID ¶
func ToolRequestWithID(id interface{}, name string, args map[string]interface{}) map[string]interface{}
ToolRequestWithID generates a tool request with a specific ID
Types ¶
type MockTransport ¶
type MockTransport struct {
// Connection state
ConnectCalled bool
DisconnectCalled bool
ConnectionAttempts int
Connected bool
// Request/Response handling - minimal protection for slice operations only
LastSentMessage []byte
RequestHistory []RequestRecord
ResponseQueue []ResponseConfig
DefaultResponse *ResponseConfig
ResponseHistory [][]byte
// Network simulation
NetworkConditions NetworkConditions
RequestTimeout time.Duration
ConnectionTimeout time.Duration
ErrorRate float64 // Probability of returning an error on any request
// Handlers
NotificationHandlerFunc func(method string, params []byte)
// RequestInterceptor can modify outgoing requests for testing
// If set, every request sent through Send/SendWithContext will be processed by this function
RequestInterceptor func(request []byte) []byte
// contains filtered or unexported fields
}
MockTransport is a mock transport for testing with enhanced capabilities
func NewMockTransport ¶
func NewMockTransport() *MockTransport
NewMockTransport creates a new mock transport with default settings
func SetupClientWithMockTransport ¶
SetupClientWithMockTransport creates a client with a mock transport for the given version and returns the client and transport
func SetupClientWithOptions ¶
func SetupClientWithOptions(t *testing.T, version string, options ...client.Option) (client.Client, *MockTransport)
SetupClientWithOptions creates a client with a mock transport and additional client options
func SetupFixture ¶
SetupFixture sets up a named fixture and returns a configured client
func SetupMockTransport ¶
func SetupMockTransport(version string) *MockTransport
SetupMockTransport sets up a mock transport with a successful initialize response for the specified version
func SetupSamplingMockTransport ¶
func SetupSamplingMockTransport(version string, mockTransport *MockTransport) *MockTransport
SetupSamplingMockTransport configures a mock transport with appropriate responses for sampling tests
func (*MockTransport) ClearHistory ¶
func (m *MockTransport) ClearHistory() *MockTransport
ClearHistory clears the request history
func (*MockTransport) ClearResponses ¶
func (m *MockTransport) ClearResponses() *MockTransport
ClearResponses removes all queued responses
func (*MockTransport) Connect ¶
func (m *MockTransport) Connect() error
Connect implements the Transport interface
func (*MockTransport) ConnectWithContext ¶
func (m *MockTransport) ConnectWithContext(ctx context.Context) error
ConnectWithContext implements the Transport interface
func (*MockTransport) Disconnect ¶
func (m *MockTransport) Disconnect() error
Disconnect implements the Transport interface
func (*MockTransport) GetRequestByID ¶
func (m *MockTransport) GetRequestByID(id interface{}) *RequestRecord
GetRequestByID finds a request in the history by its ID
func (*MockTransport) GetRequestHistory ¶
func (m *MockTransport) GetRequestHistory() []RequestRecord
GetRequestHistory returns a copy of the request history
func (*MockTransport) GetRequestsByMethod ¶
func (m *MockTransport) GetRequestsByMethod(method string) []RequestRecord
GetRequestsByMethod finds requests in the history by method
func (*MockTransport) QueueConditionalResponse ¶
func (m *MockTransport) QueueConditionalResponse(data []byte, err error, condition func([]byte) bool) *MockTransport
QueueConditionalResponse adds a response that is only used if the condition is met
func (*MockTransport) QueueFlaky ¶
func (m *MockTransport) QueueFlaky(data []byte, err error, probability float64) *MockTransport
QueueFlaky adds a response that is used with the given probability
func (*MockTransport) QueueResponse ¶
func (m *MockTransport) QueueResponse(data []byte, err error) *MockTransport
QueueResponse adds a response to the queue (responses are used in FIFO order)
func (*MockTransport) QueueResponseWithDelay ¶
func (m *MockTransport) QueueResponseWithDelay(data []byte, err error, delay time.Duration) *MockTransport
QueueResponseWithDelay adds a response with a specified delay
func (*MockTransport) RegisterNotificationHandler ¶
func (m *MockTransport) RegisterNotificationHandler(handler func(method string, params []byte))
RegisterNotificationHandler implements the Transport interface
func (*MockTransport) Send ¶
func (m *MockTransport) Send(message []byte) ([]byte, error)
Send implements the Transport interface
func (*MockTransport) SendWithContext ¶
SendWithContext implements the Transport interface
func (*MockTransport) SetConnectionTimeout ¶
func (m *MockTransport) SetConnectionTimeout(timeout time.Duration)
SetConnectionTimeout implements the Transport interface
func (*MockTransport) SetErrorRate ¶
func (m *MockTransport) SetErrorRate(errorPercent int) *MockTransport
SetErrorRate configures the probability of returning errors on any request
func (*MockTransport) SetLatency ¶
func (m *MockTransport) SetLatency(latencyMs int, jitterPercent int) *MockTransport
SetLatency configures the latency simulation
func (*MockTransport) SetPacketLoss ¶
func (m *MockTransport) SetPacketLoss(lossPercent int) *MockTransport
SetPacketLoss configures packet loss simulation
func (*MockTransport) SetRequestTimeout ¶
func (m *MockTransport) SetRequestTimeout(timeout time.Duration)
SetRequestTimeout implements the Transport interface
func (*MockTransport) SimulateDisconnect ¶
func (m *MockTransport) SimulateDisconnect() *MockTransport
SimulateDisconnect forces the transport to disconnect after a certain number of requests
func (*MockTransport) SimulateDisconnectAfter ¶
func (m *MockTransport) SimulateDisconnectAfter(requestCount int) *MockTransport
SimulateDisconnectAfter configures the transport to disconnect after a specified number of requests
func (*MockTransport) SimulateNotification ¶
func (m *MockTransport) SimulateNotification(method string, message []byte)
SimulateNotification simulates a notification from the server
func (*MockTransport) WaitForNotification ¶ added in v1.6.0
func (m *MockTransport) WaitForNotification(method string, timeout time.Duration) bool
WaitForNotification waits for a specific notification method to be received Returns true if the notification was received within the timeout, false otherwise
func (*MockTransport) WithDefaultResponse ¶
func (m *MockTransport) WithDefaultResponse(data []byte, err error) *MockTransport
WithDefaultResponse sets a default response to use when the queue is empty
func (*MockTransport) WithNetworkConditions ¶
func (m *MockTransport) WithNetworkConditions(conditions NetworkConditions) *MockTransport
WithNetworkConditions configures simulated network conditions
type NetworkConditions ¶
type NetworkConditions struct {
Latency time.Duration // Base latency for all operations
LatencyJitter time.Duration // Random variation in latency
PacketLossRate float64 // Probability (0-1) of packet loss
DisconnectAfter int // Number of requests after which to simulate disconnection, 0 = never
RequestCount int // Internal counter of processed requests
}
NetworkConditions allows configuration of simulated network conditions
type RequestRecord ¶
type RequestRecord struct {
Message []byte
Raw []byte // The raw request message (same as Message)
Timestamp time.Time
ID interface{}
Method string
}
RequestRecord stores information about a sent request
type ResponseConfig ¶
type ResponseConfig struct {
Data []byte
Error error
Delay time.Duration
Condition func([]byte) bool // If set, this response only applies if the condition is true
Probability float64 // Probability (0-1) of this response being used (for simulating flakiness)
AfterUseFunc func() // Called after this response is used
}
ResponseConfig defines a response configuration
type ServerWithHandler ¶
ServerWithHandler is a wrapper for Server that exposes the handleMessage method for testing This is kept for backward compatibility with existing tests
func WrapServer ¶
func WrapServer(s server.Server) *ServerWithHandler
WrapServer wraps a Server to expose its handleMessage method for testing
func (*ServerWithHandler) HandleMessage ¶
func (s *ServerWithHandler) HandleMessage(message []byte) ([]byte, error)
HandleMessage exposes the handleMessage method of serverImpl for testing
type TestFixture ¶
type TestFixture struct {
Name string // Name of the fixture for identification
Description string // Description of what the fixture is for
Setup func(*testing.T, *MockTransport) // Setup function to prepare the fixture
Teardown func(*testing.T, *MockTransport) // Teardown function to clean up
Verify func(*testing.T, client.Client) // Function to verify the fixture works as expected
Data map[string]interface{} // Data associated with the fixture
Responses [][]byte // Pre-defined responses
}
TestFixture defines a reusable test scenario that can be used across multiple tests