testutil

package
v0.1.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package testutil provides utilities for end-to-end CLI testing.

Index

Constants

View Source
const (
	// EnvLiveTest enables live API testing when set to "true" or "1".
	EnvLiveTest = "STACKEYE_E2E_LIVE"
	// EnvLiveAPIURL overrides the API URL for live testing.
	EnvLiveAPIURL = "STACKEYE_E2E_API_URL"
	// DefaultLiveAPIURL is the default API URL for live testing.
	DefaultLiveAPIURL = "https://api-dev.stackeye.io"
)

Environment variables for live testing.

View Source
const (
	ProbeID1       = "11111111-1111-1111-1111-111111111111"
	ProbeID2       = "22222222-2222-2222-2222-222222222222"
	AlertID1       = "aaaaaaaa-1111-1111-1111-111111111111"
	ChannelID1     = "cccccccc-1111-1111-1111-111111111111"
	ChannelID2     = "cccccccc-2222-2222-2222-222222222222"
	OrganizationID = "00000000-0000-0000-0000-000000000001"
)

Known fixture IDs for consistent testing Note: All IDs must be valid UUIDs (36 chars, proper hex format)

View Source
const TestAPIKey = "se_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"

TestAPIKey is a fixed API key for testing.

View Source
const TestContextName = "test"

TestContextName is the default test context name.

Variables

This section is empty.

Functions

func AlertFixture

func AlertFixture(id string) map[string]interface{}

AlertFixture returns an alert fixture by ID.

func AlertHistoryFixture

func AlertHistoryFixture() []map[string]interface{}

AlertHistoryFixture returns alert history entries.

func AlertListFixture

func AlertListFixture() []map[string]interface{}

AlertListFixture returns a list of alerts for testing. Note: Field names MUST match SDK's Alert struct JSON tags exactly.

func ChannelFixture

func ChannelFixture(id string) map[string]interface{}

ChannelFixture returns a channel fixture by ID.

func ChannelListFixture

func ChannelListFixture() []map[string]interface{}

ChannelListFixture returns a list of notification channels for testing. Note: Field names MUST match SDK's Channel struct JSON tags exactly.

func GetLiveAPIURL

func GetLiveAPIURL() string

GetLiveAPIURL returns the API URL for live testing.

func IsLiveTestEnabled

func IsLiveTestEnabled() bool

IsLiveTestEnabled returns true if live testing is enabled via environment.

func NewChannelFixture

func NewChannelFixture() map[string]interface{}

NewChannelFixture returns a newly created channel fixture.

func NewProbeFixture

func NewProbeFixture() map[string]interface{}

NewProbeFixture returns a newly created probe fixture.

func ProbeFixture

func ProbeFixture(id string) map[string]interface{}

ProbeFixture returns a probe fixture by ID.

func ProbeHistoryFixture

func ProbeHistoryFixture() []map[string]interface{}

ProbeHistoryFixture returns probe history entries.

func ProbeListFixture

func ProbeListFixture() []map[string]interface{}

ProbeListFixture returns a list of probes for testing. Note: Field names MUST match SDK's Probe struct JSON tags exactly.

func ProbeStatsFixture

func ProbeStatsFixture() map[string]interface{}

ProbeStatsFixture returns probe statistics fixture.

func ProbeTestResultFixture

func ProbeTestResultFixture() map[string]interface{}

ProbeTestResultFixture returns a probe test result fixture. Note: Field names MUST match SDK's ProbeTestResponse struct JSON tags exactly.

func RegionListByContinent

func RegionListByContinent() map[string][]map[string]interface{}

RegionListByContinent returns regions grouped by continent, matching SDK's RegionListResponse.Data format. SDK expects: map[string][]Region where key is continent slug like "north_america", "europe".

func RegionListFixture

func RegionListFixture() []map[string]interface{}

RegionListFixture returns a flat list of available regions (legacy format).

func RespondWithError

func RespondWithError(w http.ResponseWriter, status int, message string)

RespondWithError writes an error response.

func RespondWithJSON

func RespondWithJSON(w http.ResponseWriter, status int, data interface{})

RespondWithJSON writes a JSON response.

Types

type APIMeta

type APIMeta struct {
	Page    int  `json:"page"`
	Limit   int  `json:"limit"`
	Total   int  `json:"total"`
	Pages   int  `json:"pages"`
	HasNext bool `json:"has_next"`
}

APIMeta contains pagination metadata.

type APIResponse

type APIResponse struct {
	Status string      `json:"status"`
	Data   interface{} `json:"data,omitempty"`
	Error  string      `json:"error,omitempty"`
	Meta   *APIMeta    `json:"meta,omitempty"`
}

APIResponse represents a standardized API response.

type CLIRunner

type CLIRunner struct {
	// BinaryPath is the path to the CLI binary.
	BinaryPath string
	// ConfigPath is the path to the config file.
	ConfigPath string
	// XDGConfigHome is the XDG_CONFIG_HOME value to use.
	// This ensures the CLI's Save() function writes to the correct location.
	XDGConfigHome string
	// Env contains additional environment variables.
	Env map[string]string
}

CLIRunner executes CLI commands for E2E testing.

func NewCLIRunner

func NewCLIRunner(configPath, xdgConfigHome string) *CLIRunner

NewCLIRunner creates a new CLI runner with the given config path and XDG config home. It expects the binary to be built and available in the project root or path. The xdgConfigHome parameter is set as XDG_CONFIG_HOME environment variable so that the CLI's Save() function writes to the correct location (not the user's actual config).

func (*CLIRunner) Run

func (r *CLIRunner) Run(args ...string) *RunResult

Run executes the CLI with the given arguments.

func (*CLIRunner) RunExpectError

func (r *CLIRunner) RunExpectError(args ...string) *RunResult

RunExpectError executes and expects a non-zero exit code.

func (*CLIRunner) RunRaw

func (r *CLIRunner) RunRaw(args ...string) *RunResult

RunRaw executes the CLI with exact arguments (no automatic config flag).

func (*CLIRunner) RunWithOutput

func (r *CLIRunner) RunWithOutput(args ...string) (string, error)

RunWithOutput executes and returns stdout, failing on non-zero exit.

type MockServer

type MockServer struct {
	Server  *httptest.Server
	BaseURL string
	// contains filtered or unexported fields
}

MockServer provides a mock HTTP server for E2E testing.

func NewMockServer

func NewMockServer() *MockServer

NewMockServer creates a new mock API server with default routes.

func (*MockServer) ClearCalls

func (ms *MockServer) ClearCalls()

ClearCalls clears the recorded API calls.

func (*MockServer) Close

func (ms *MockServer) Close()

Close shuts down the mock server.

func (*MockServer) GetCalls

func (ms *MockServer) GetCalls() []RecordedCall

GetCalls returns all recorded API calls.

func (*MockServer) HasCall

func (ms *MockServer) HasCall(method, pathPrefix string) bool

HasCall checks if a specific API call was made.

func (*MockServer) Register

func (ms *MockServer) Register(method, pattern string, handler RouteHandler)

Register adds a new route handler to the mock server.

func (*MockServer) RegisterDefaultRoutes

func (ms *MockServer) RegisterDefaultRoutes()

RegisterDefaultRoutes registers common API routes with fixture responses. Note: SDK uses paths like "/v1/probes" (without /api prefix). SDK directly unmarshals responses into typed structs, not wrapped APIResponse.

type RecordedCall

type RecordedCall struct {
	Method string
	Path   string
	Body   string
}

RecordedCall records details of an API call made to the mock server.

type Route

type Route struct {
	Method  string
	Pattern *regexp.Regexp
	Handler RouteHandler
}

Route represents a registered API route.

type RouteHandler

type RouteHandler func(w http.ResponseWriter, r *http.Request, matches []string)

RouteHandler is a function that handles an API route.

type RunResult

type RunResult struct {
	// Stdout contains the standard output.
	Stdout string
	// Stderr contains the standard error.
	Stderr string
	// ExitCode is the exit code of the command.
	ExitCode int
	// Err is any error that occurred during execution.
	Err error
}

RunResult contains the result of running a CLI command.

func (*RunResult) CombinedOutput

func (r *RunResult) CombinedOutput() string

CombinedOutput returns stdout and stderr combined.

func (*RunResult) Contains

func (r *RunResult) Contains(substr string) bool

Contains returns true if stdout contains the given substring.

func (*RunResult) Failed

func (r *RunResult) Failed() bool

Failed returns true if the command failed.

func (*RunResult) Lines

func (r *RunResult) Lines() []string

Lines returns stdout split into lines.

func (*RunResult) StderrContains

func (r *RunResult) StderrContains(substr string) bool

StderrContains returns true if stderr contains the given substring.

func (*RunResult) StderrLines

func (r *RunResult) StderrLines() []string

StderrLines returns stderr split into lines.

func (*RunResult) String

func (r *RunResult) String() string

String returns a debug representation of the result.

func (*RunResult) Success

func (r *RunResult) Success() bool

Success returns true if the command succeeded.

type TestConfig

type TestConfig struct {
	// Dir is the temporary config directory.
	Dir string
	// ConfigPath is the path to the config file.
	ConfigPath string
	// Config is the configuration object.
	Config *config.Config
}

TestConfig manages temporary configuration for E2E tests.

func NewTestConfig

func NewTestConfig(apiURL string) (*TestConfig, error)

NewTestConfig creates a new test configuration with a temporary directory. The returned TestConfig must be cleaned up with Cleanup().

The directory structure matches XDG_CONFIG_HOME expectations: - Dir (XDG_CONFIG_HOME): /tmp/stackeye-e2e-xxx/ - ConfigPath: /tmp/stackeye-e2e-xxx/stackeye/config.yaml

This allows the CLI's Save() function to work correctly when XDG_CONFIG_HOME is set to Dir.

func NewTestConfigWithMultipleContexts

func NewTestConfigWithMultipleContexts(apiURL string) (*TestConfig, error)

NewTestConfigWithMultipleContexts creates a test config with multiple contexts.

func (*TestConfig) AddContext

func (tc *TestConfig) AddContext(name string, ctx *config.Context) error

AddContext adds a new context and saves the config.

func (*TestConfig) Cleanup

func (tc *TestConfig) Cleanup()

Cleanup removes the temporary configuration directory.

func (*TestConfig) Reload

func (tc *TestConfig) Reload() error

Reload reloads the config from disk.

func (*TestConfig) RemoveContext

func (tc *TestConfig) RemoveContext(name string) error

RemoveContext removes a context and saves the config.

func (*TestConfig) SetCurrentContext

func (tc *TestConfig) SetCurrentContext(name string) error

SetCurrentContext changes the current context and saves the config.

type TestEnv

type TestEnv struct {
	// T is the testing context.
	T *testing.T
	// Server is the mock API server.
	Server *MockServer
	// Config is the test configuration.
	Config *TestConfig
	// CLI is the command runner.
	CLI *CLIRunner
}

TestEnv encapsulates all test dependencies.

func NewLiveTestEnv

func NewLiveTestEnv(t *testing.T) *TestEnv

NewLiveTestEnv creates a test environment using the user's real CLI config. This connects to the live API instead of a mock server. Requires: User must be authenticated (run `stackeye login` first).

func NewTestEnv

func NewTestEnv(t *testing.T) *TestEnv

NewTestEnv creates a complete test environment with mock server, config, and CLI runner. Call Cleanup() when done to release resources.

func NewTestEnvWithMultipleContexts

func NewTestEnvWithMultipleContexts(t *testing.T) *TestEnv

NewTestEnvWithMultipleContexts creates a test environment with multiple contexts.

func (*TestEnv) AssertAPICall

func (e *TestEnv) AssertAPICall(method, pathPrefix string)

AssertAPICall asserts that a specific API call was made. In live mode, this is a no-op (we can't inspect real API calls).

func (*TestEnv) AssertContains

func (e *TestEnv) AssertContains(result *RunResult, substr string)

AssertContains asserts that stdout contains the substring.

func (*TestEnv) AssertJSONOutput

func (e *TestEnv) AssertJSONOutput(result *RunResult, v any)

AssertJSONOutput asserts that stdout is valid JSON and unmarshals it.

func (*TestEnv) AssertNoAPICall

func (e *TestEnv) AssertNoAPICall(method, pathPrefix string)

AssertNoAPICall asserts that no API call matching the pattern was made. In live mode, this is a no-op (we can't inspect real API calls).

func (*TestEnv) AssertNotContains

func (e *TestEnv) AssertNotContains(result *RunResult, substr string)

AssertNotContains asserts that stdout does not contain the substring.

func (*TestEnv) AssertStderrContains

func (e *TestEnv) AssertStderrContains(result *RunResult, substr string)

AssertStderrContains asserts that stderr contains the substring.

func (*TestEnv) AssertTableHasRows

func (e *TestEnv) AssertTableHasRows(result *RunResult, minRows int)

AssertTableHasRows asserts that table output has at least the expected number of rows. This accounts for header row(s).

func (*TestEnv) Cleanup

func (e *TestEnv) Cleanup()

Cleanup releases all test resources.

func (*TestEnv) ClearAPICalls

func (e *TestEnv) ClearAPICalls()

ClearAPICalls clears the recorded API calls. In live mode, this is a no-op.

func (*TestEnv) GetAPICalls

func (e *TestEnv) GetAPICalls() []RecordedCall

GetAPICalls returns all recorded API calls. In live mode, returns an empty slice (we can't intercept real API calls).

func (*TestEnv) IsLiveMode

func (e *TestEnv) IsLiveMode() bool

IsLiveMode returns true if running against live API (Server is nil).

func (*TestEnv) Run

func (e *TestEnv) Run(args ...string) *RunResult

Run executes a CLI command and returns the result.

func (*TestEnv) RunError

func (e *TestEnv) RunError(args ...string) *RunResult

RunError executes and asserts failure.

func (*TestEnv) RunSuccess

func (e *TestEnv) RunSuccess(args ...string) *RunResult

RunSuccess executes and asserts success.

Jump to

Keyboard shortcuts

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