test

package
v0.0.57 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package test provides utilities for testing unstructured Kubernetes objects.

The primary functionality is JSONPath-like field access for unstructured.Unstructured objects, making test assertions more readable and maintainable.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Field added in v0.0.55

func Field(obj interface{}, path string) (interface{}, bool)

Field is the core helper that traverses an unstructured object using JSONPath-like notation. It supports both dot notation (foo.bar) and array indexing (foo[0].bar). Returns (nil, false) if any intermediate field is nil, as we cannot traverse through nil.

func FieldExists added in v0.0.55

func FieldExists(obj *unstructured.Unstructured, path string) bool

FieldExists checks if a field exists at the given JSONPath-like path.

func FieldInt added in v0.0.55

func FieldInt(obj *unstructured.Unstructured, path string) int64

FieldInt retrieves an integer field from an unstructured object using JSONPath-like notation. Returns the integer value (int64), or 0 if not found or not an integer type (int, int64, int32).

IMPORTANT: This function cannot distinguish between "field doesn't exist", "field is nil", and "field exists with value 0". When asserting zero values (0), you should also verify the field exists using FieldExists:

s.True(test.FieldExists(obj, "spec.zeroValue"), "field should exist")
s.Equal(int64(0), test.FieldInt(obj, "spec.zeroValue"), "field should be 0")

Examples:

  • "spec.replicas"
  • "spec.ports[0].containerPort"

func FieldString added in v0.0.55

func FieldString(obj *unstructured.Unstructured, path string) string

FieldString retrieves a string field from an unstructured object using JSONPath-like notation. Returns the string value, or empty string if not found or not a string.

IMPORTANT: This function cannot distinguish between "field doesn't exist", "field is nil", and "field exists with empty string value". When asserting empty string values (""), you should also verify the field exists using FieldExists:

s.True(test.FieldExists(obj, "spec.emptyField"), "field should exist")
s.Equal("", test.FieldString(obj, "spec.emptyField"), "field should be empty string")

Examples:

  • "spec.runStrategy"
  • "spec.template.spec.volumes[0].containerDisk.image"
  • "spec.dataVolumeTemplates[0].spec.sourceRef.kind"

func FieldValue added in v0.0.55

func FieldValue(obj *unstructured.Unstructured, path string) interface{}

FieldValue retrieves any field value from an unstructured object using JSONPath-like notation. Returns nil if the field is not found. This is useful when you need the raw value without type conversion. Examples:

  • "spec.template.spec.containers[0]" - returns map[string]interface{}
  • "metadata.labels" - returns map[string]interface{}

func KubeConfigFake added in v0.0.51

func KubeConfigFake() *clientcmdapi.Config

func KubeconfigFile added in v0.0.53

func KubeconfigFile(t *testing.T, kubeconfig *api.Config) string

func McpInitRequest added in v0.0.54

func McpInitRequest() mcp.InitializeRequest

func Must added in v0.0.51

func Must[T any](v T, err error) T

func RandomPortAddress added in v0.0.54

func RandomPortAddress() (*net.TCPAddr, error)

func ReadFile added in v0.0.52

func ReadFile(path ...string) string

func RestoreEnv added in v0.0.54

func RestoreEnv(originalEnv []string)

func WaitForHealthz added in v0.0.55

func WaitForHealthz(tcpAddr *net.TCPAddr) error

WaitForHealthz waits for the /healthz endpoint to return a non-404 response

func WaitForServer added in v0.0.54

func WaitForServer(tcpAddr *net.TCPAddr) error

func WriteObject

func WriteObject(w http.ResponseWriter, obj runtime.Object)

Types

type DiscoveryClientHandler added in v0.0.55

type DiscoveryClientHandler struct {
	// APIResourceLists defines all API groups and their resources.
	// The handler automatically generates /api, /apis, and /apis/<group>/<version> endpoints.
	APIResourceLists []metav1.APIResourceList
}

func NewDiscoveryClientHandler added in v0.0.57

func NewDiscoveryClientHandler(additionalResources ...metav1.APIResourceList) *DiscoveryClientHandler

NewDiscoveryClientHandler creates a DiscoveryClientHandler with default Kubernetes resources.

func NewInOpenShiftHandler added in v0.0.57

func NewInOpenShiftHandler(additionalResources ...metav1.APIResourceList) *DiscoveryClientHandler

NewInOpenShiftHandler creates a DiscoveryClientHandler configured for OpenShift clusters. It includes the OpenShift project.openshift.io API group by default. Additional API resource lists can be passed to extend the handler.

func (*DiscoveryClientHandler) AddAPIResourceList added in v0.0.57

func (h *DiscoveryClientHandler) AddAPIResourceList(resourceList metav1.APIResourceList)

AddAPIResourceList adds an API resource list to the handler. This is useful for dynamically modifying the handler during tests.

func (*DiscoveryClientHandler) ServeHTTP added in v0.0.55

func (h *DiscoveryClientHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)

type LogNotification added in v0.0.57

type LogNotification struct {
	// Level is the log severity level (debug, info, notice, warning, error, critical, alert, emergency)
	Level string
	// Logger is the name of the logger that generated the message
	Logger string
	// Data contains the log message content
	Data string
}

LogNotification represents a parsed MCP logging notification. Used for asserting log messages sent to MCP clients during error handling.

type McpClient added in v0.0.51

type McpClient struct {
	*client.Client
	InitializeResult *mcp.InitializeResult
	// contains filtered or unexported fields
}

func NewMcpClient added in v0.0.51

func NewMcpClient(t *testing.T, mcpHttpServer http.Handler, options ...transport.StreamableHTTPCOption) *McpClient

func (*McpClient) CallTool added in v0.0.51

func (m *McpClient) CallTool(name string, args map[string]interface{}) (*mcp.CallToolResult, error)

CallTool helper function to call a tool by name with arguments

func (*McpClient) Close added in v0.0.51

func (m *McpClient) Close()

func (*McpClient) StartCapturingNotifications added in v0.0.57

func (m *McpClient) StartCapturingNotifications() *NotificationCapture

StartCapturingNotifications begins capturing all MCP notifications. Must be called BEFORE the operation that triggers the notification.

type MockServer

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

func NewMockServer

func NewMockServer() *MockServer

func (*MockServer) Close

func (m *MockServer) Close()

func (*MockServer) Config

func (m *MockServer) Config() *rest.Config

func (*MockServer) Handle

func (m *MockServer) Handle(handler http.Handler)

func (*MockServer) Kubeconfig added in v0.0.51

func (m *MockServer) Kubeconfig() *api.Config

func (*MockServer) KubeconfigFile added in v0.0.51

func (m *MockServer) KubeconfigFile(t *testing.T) string

func (*MockServer) ResetHandlers added in v0.0.54

func (m *MockServer) ResetHandlers()

type NotificationCapture added in v0.0.57

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

NotificationCapture captures MCP notifications for testing. Use StartCapturingNotifications to begin capturing, then RequireNotification to retrieve.

func (*NotificationCapture) RequireLogNotification added in v0.0.57

func (c *NotificationCapture) RequireLogNotification(t *testing.T, timeout time.Duration) *LogNotification

RequireLogNotification waits for a logging notification and returns it parsed. Filters for "notifications/message" method and fails the test if not received within timeout.

Timeout recommendations:

  • 2 seconds: Standard timeout for log notifications after tool calls (recommended default)

func (*NotificationCapture) RequireNotification added in v0.0.57

func (c *NotificationCapture) RequireNotification(t *testing.T, timeout time.Duration, method string) *mcp.JSONRPCNotification

RequireNotification waits for a notification matching the specified method and fails the test if not received. Iterates through all captured notifications looking for a match, waiting for new ones if needed. The method parameter specifies which notification method to wait for (e.g., "notifications/tools/list_changed").

Timeout recommendations:

  • 2 seconds: For immediate notifications like log messages after tool calls
  • 5 seconds: For notifications involving file system or cluster state changes (kubeconfig, API groups)

type StreamContext

type StreamContext struct {
	Closer       io.Closer
	StdinStream  io.ReadCloser
	StdoutStream io.WriteCloser
	StderrStream io.WriteCloser
	// contains filtered or unexported fields
}

func CreateHTTPStreams

func CreateHTTPStreams(w http.ResponseWriter, req *http.Request, opts *StreamOptions) (*StreamContext, error)

type StreamOptions

type StreamOptions struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

Jump to

Keyboard shortcuts

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