test

package
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 16 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var CommonFixtureSetups = map[string]func(*testing.T, *MockTransport){
	"BasicClient":        setupBasicClient,
	"ResourceServer":     setupResourceServer,
	"ToolServer":         setupToolServer,
	"VersionNegotiation": setupVersionNegotiation,
}

CommonFixtureSetups defines setup functions to avoid circular dependencies

View Source
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

func AssertFeatureSupport(t *testing.T, version string, response []byte, featurePath ...string)

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

func AssertJSONPath(t *testing.T, jsonData []byte, path []string, expectedValue interface{})

AssertJSONPath checks if the given JSON data contains a value at the specified path

func AssertMethodEquals

func AssertMethodEquals(t *testing.T, jsonData []byte, expectedMethod string)

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

func AssertRequestParams(t *testing.T, request []byte, expected map[string]interface{})

AssertRequestParams checks if a request has the expected parameters

func AssertResponseError

func AssertResponseError(t *testing.T, jsonData []byte, expectedCode int)

AssertResponseError checks if the JSON-RPC response indicates an error with the expected code

func AssertResponseSuccess

func AssertResponseSuccess(t *testing.T, jsonData []byte)

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

func AssertVersionCapabilities(t *testing.T, version string, response []byte)

AssertVersionCapabilities verifies that the capabilities in the response are appropriate for the protocol version

func AssertVersionCompatibility

func AssertVersionCompatibility(t *testing.T, version string, jsonData []byte)

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

func AssertVersionNegotiation(t *testing.T, clientVersion, serverVersion string, response []byte)

AssertVersionNegotiation verifies that the client correctly negotiates the protocol version with the server

func AssertVersionSpecificError

func AssertVersionSpecificError(t *testing.T, version string, response []byte, expectedCode int)

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

func AssertVersionSpecificResource(t *testing.T, version string, response []byte)

AssertVersionSpecificResource verifies that a resource response follows the correct structure for the specified protocol version

func Capabilities

func Capabilities(version string) map[string]interface{}

Capabilities generates capabilities for the given protocol version

func ClientInfo

func ClientInfo(name, version string) map[string]interface{}

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

func CreateInitializeResponse(version string, capabilities map[string]interface{}) []byte

CreateInitializeResponse creates a mock initialize response for the specified version

func CreateMockResourceResponse

func CreateMockResourceResponse(version string, id interface{}) []byte

CreateMockResourceResponse creates a structured resource response for testing

func CreateNotificationResponse

func CreateNotificationResponse(method string, params map[string]interface{}) []byte

CreateNotificationResponse creates a notification (no ID) response

func CreatePromptResponse

func CreatePromptResponse(prompt, rendered string) []byte

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

func CreateResource(uri, text string, content []interface{}) map[string]interface{}

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

func CreateResourceResponse(version string, content interface{}) []byte

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

func CreateRoot(path, name string, metadata map[string]interface{}) map[string]interface{}

CreateRoot creates a root object for roots/list responses

func CreateRootListResponse

func CreateRootListResponse(version string, id interface{}) []byte

CreateRootListResponse creates a response for roots/list request

func CreateRootsListResponse

func CreateRootsListResponse(id interface{}, roots []map[string]interface{}) []byte

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

func CreateSamplingTextResponse(id interface{}, version string, text string, model string) []byte

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

func CreateToolErrorResponse(id interface{}, code int, message string, data interface{}) []byte

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

func CreateVersionSpecificInitializeResponse(version string, id interface{}) []byte

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

func ErrorResponse(code int, message string) map[string]interface{}

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

func GetFixtureData(t *testing.T, fixtureName string) map[string]interface{}

GetFixtureData gets data from a named fixture

func GetJSONRPCID

func GetJSONRPCID(jsonData []byte) (interface{}, error)

GetJSONRPCID extracts the ID from a JSON-RPC message

func GetJSONRPCParams

func GetJSONRPCParams(jsonData []byte) (map[string]interface{}, error)

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

func IsRequestMethod(method string) func([]byte) bool

IsRequestMethod checks if a given request uses the specified method

func IsStreamingSupportedForVersion added in v1.5.0

func IsStreamingSupportedForVersion(version string) bool

IsStreamingSupportedForVersion checks if streaming is supported for a version

func IsStreamingSupportedInVersion

func IsStreamingSupportedInVersion(version string) bool

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

func NotificationRequest(method string, params interface{}) map[string]interface{}

NotificationRequest generates a notification with the given method and params

func ParseResponse

func ParseResponse(t *testing.T, response []byte) *jsonrpc.JSONRPC

ParseResponse parses a JSON-RPC response using the JSONRPC struct

func ParseVersionSpecificResource

func ParseVersionSpecificResource(t *testing.T, version string, response []byte) *jsonrpc.JSONRPC

ParseVersionSpecificResource parses a resource response and checks if it matches the expected format for the specified version

func PromptRequest

func PromptRequest(name string, variables map[string]interface{}) map[string]interface{}

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

func RequestHasID(id interface{}) func([]byte) bool

RequestHasID checks if a given request has the specified ID

func ResourceRequest

func ResourceRequest(path string) map[string]interface{}

ResourceRequest generates a resource request for the given path

func ResourceRequestWithID

func ResourceRequestWithID(id interface{}, path string) map[string]interface{}

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

func SamplingCreateMessageMatcher() func([]byte) bool

SamplingCreateMessageMatcher creates a condition function that matches sampling/createMessage requests

func SamplingCreateStreamingMessageMatcher

func SamplingCreateStreamingMessageMatcher() func([]byte) bool

SamplingCreateStreamingMessageMatcher creates a condition function that matches sampling/createStreamingMessage requests

func ServerInfo

func ServerInfo(name, version string) map[string]interface{}

ServerInfo generates server information with the given name and version

func SetSamplingHandler

func SetSamplingHandler(c client.Client, handler client.SamplingHandler) client.Client

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

func ToolRequest(name string, args map[string]interface{}) map[string]interface{}

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

func VerifyFixture

func VerifyFixture(t *testing.T, fixtureName string, c client.Client)

VerifyFixture verifies a named fixture

Types

type MockError

type MockError struct {
	Message string
}

MockError is a mock error for testing

func (*MockError) Error

func (e *MockError) Error() string

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

func SetupClientWithMockTransport(t *testing.T, version string) (client.Client, *MockTransport)

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

func SetupFixture(t *testing.T, fixtureName string, version string) (client.Client, *MockTransport)

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

func (m *MockTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

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

type ServerWithHandler struct {
	Server server.Server
}

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

Directories

Path Synopsis
Package draft provides test utilities specific to the draft protocol version.
Package draft provides test utilities specific to the draft protocol version.

Jump to

Keyboard shortcuts

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