testutil

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package testutil provides testing utilities, fixtures, and mocks for unit tests.

Index

Constants

This section is empty.

Variables

View Source
var ErrMockCommandNotConfigured = errors.New("mock executor: no result configured for command")

ErrMockCommandNotConfigured indicates the MockExecutor has no result configured for a command.

View Source
var ErrMockExitStatus1 = errors.New("exit status 1")

ErrMockExitStatus1 simulates a generic "exit status 1" failure from an external command.

View Source
var ErrMockExitStatus127 = errors.New("exit status 127")

ErrMockExitStatus127 simulates a "command not found" (exit status 127) failure.

Functions

func APIRunListJSON added in v1.9.0

func APIRunListJSON(runs ...APIRun) string

APIRunListJSON renders a run listing the way the Actions API returns one.

func AsGHRunViewLog added in v1.2.2

func AsGHRunViewLog(job, step, raw string) string

AsGHRunViewLog prefixes each line of raw with the job name, step name, and a timestamp, the shape `gh run view --log` emits. A fixture without that prefix exercises no step-splitting at all, which is how a parser that never worked against real output stayed green.

func AssertCommand

func AssertCommand(t *testing.T, cmd ExecutedCommand, expectedArgs ...string)

AssertCommand verifies that an executed command matches expected arguments.

func AssertContains

func AssertContains(t *testing.T, haystack, needle string, msgAndArgs ...any)

AssertContains fails the test if haystack doesn't contain needle.

func AssertEqual

func AssertEqual[T comparable](t *testing.T, got, want T, msgAndArgs ...any)

AssertEqual fails the test if got != want.

func AssertFalse

func AssertFalse(t *testing.T, condition bool, msgAndArgs ...any)

AssertFalse fails the test if condition is true.

func AssertNil

func AssertNil(t *testing.T, value any, msgAndArgs ...any)

AssertNil fails the test if value is not nil.

func AssertNotEqual

func AssertNotEqual[T comparable](t *testing.T, got, want T, msgAndArgs ...any)

AssertNotEqual fails the test if got == want.

func AssertNotNil

func AssertNotNil(t *testing.T, value any, msgAndArgs ...any)

AssertNotNil fails the test if value is nil.

func AssertStepLogNames

func AssertStepLogNames(t *testing.T, stepLogs []*logs.StepLogs, expectedNames []string)

AssertStepLogNames verifies that step logs have the expected names.

func AssertTrue

func AssertTrue(t *testing.T, condition bool, msgAndArgs ...any)

AssertTrue fails the test if condition is false.

func DrainChainUpdates

func DrainChainUpdates(t *testing.T, updates <-chan chain.ChainUpdate, timeout time.Duration)

DrainChainUpdates reads all updates from the channel until it closes or times out.

func GenerateANSILog

func GenerateANSILog() string

GenerateANSILog creates logs with ANSI color codes. Tests proper handling of terminal color escape sequences. Includes ##[group] markers for proper parsing.

func GenerateLargeLogFixture

func GenerateLargeLogFixture(lines int) string

GenerateLargeLogFixture creates a realistic log file with N lines. Uses GitHub Actions log format patterns for authenticity.

func GenerateLargeLogWithErrors

func GenerateLargeLogWithErrors(lines int, errorRate float64) string

GenerateLargeLogWithErrors creates a log with error patterns. The errorRate is a float between 0 and 1 indicating percentage of lines that should be errors.

func GenerateLogWithPatterns

func GenerateLogWithPatterns(lines int, patterns []string) string

GenerateLogWithPatterns creates a log with specific searchable patterns. Useful for testing search and filter functionality.

func GenerateLogWithTimestamps

func GenerateLogWithTimestamps(lines int) string

GenerateLogWithTimestamps creates log lines with timestamp prefixes. Tests timestamp parsing and display.

func GenerateMixedLog

func GenerateMixedLog(lines int) string

GenerateMixedLog creates a log with various patterns for comprehensive testing. Includes errors, warnings, unicode, ANSI codes, and normal logs.

func GenerateMultiStepLog

func GenerateMultiStepLog(numSteps, linesPerStep int) string

GenerateMultiStepLog creates a log output with multiple GitHub Actions steps. Simulates a real workflow run with step grouping.

func GenerateUnicodeLog

func GenerateUnicodeLog() string

GenerateUnicodeLog creates logs with unicode characters. Tests proper handling of international characters and emoji.

func LatestRunPath added in v1.9.0

func LatestRunPath(owner, repo, workflow string) string

LatestRunPath is the gh api path a latest-run read asks for.

func LoadFixture

func LoadFixture(tb testing.TB, filename string) string

LoadFixture loads a test fixture file from testdata. Helper function for tests and benchmarks.

func MustMarshalJSON

func MustMarshalJSON(t *testing.T, v any) string

MustMarshalJSON marshals v to JSON, failing the test if an error occurs.

func NewTestHistory

func NewTestHistory(repo string, records []struct {
	Inputs   map[string]string
	Workflow string
	Branch   string
},
) *frecency.Store

NewTestHistory creates a history store with test data.

func SimpleWorkflow

func SimpleWorkflow(name, filename string) workflow.File

SimpleWorkflow creates a basic workflow with no inputs.

func WorkflowFixture

func WorkflowFixture(name, filename string, inputs map[string]workflow.Input) workflow.File

WorkflowFixture creates a test workflow with specified properties.

func WorkflowWithBoolean

func WorkflowWithBoolean(name, filename, inputName string, defaultVal bool) workflow.File

WorkflowWithBoolean creates a workflow with a boolean input.

func WorkflowWithChoice

func WorkflowWithChoice(name, filename, inputName string, options []string, defaultVal string) workflow.File

WorkflowWithChoice creates a workflow with a choice input.

func WorkflowWithString

func WorkflowWithString(name, filename, inputName, defaultVal, description string) workflow.File

WorkflowWithString creates a workflow with a string input.

Types

type APIRun added in v1.9.0

type APIRun struct {
	CreatedAt  time.Time `json:"created_at,omitzero"`
	UpdatedAt  time.Time `json:"updated_at,omitzero"`
	Name       string    `json:"name"`
	Status     string    `json:"status"`
	Conclusion string    `json:"conclusion,omitempty"`
	HTMLURL    string    `json:"html_url,omitempty"`
	HeadBranch string    `json:"head_branch,omitempty"`
	Event      string    `json:"event,omitempty"`
	Path       string    `json:"path,omitempty"`
	ID         int64     `json:"id"`
}

APIRun is one run as the Actions API spells it. A fixture built from github.WorkflowRun would carry Go field names, which gh never emits, so the parser under test would be reading a shape that does not exist.

type CommandResult added in v1.9.0

type CommandResult struct {
	Error  error
	Stdout string
	Stderr string
}

CommandResult represents the result of a command execution.

type ExecutedCommand added in v1.9.0

type ExecutedCommand struct {
	Name string
	Args []string
}

ExecutedCommand tracks a command that was executed.

type MockExecutor added in v1.9.0

type MockExecutor struct {
	// Commands maps command patterns to responses.
	// Key format: "command arg1 arg2"
	Commands map[string]*CommandResult

	// DefaultResult is returned when no specific command matches.
	DefaultResult *CommandResult

	// ExecutedCommands tracks all commands that were executed.
	ExecutedCommands []ExecutedCommand
}

MockExecutor simulates command execution for testing.

func NewMockExecutor added in v1.9.0

func NewMockExecutor() *MockExecutor

NewMockExecutor creates a new mock executor.

func (*MockExecutor) AddCommand added in v1.9.0

func (m *MockExecutor) AddCommand(name string, args []string, stdout, stderr string, err error)

AddCommand registers a command response.

func (*MockExecutor) AddGHAPIJobs added in v1.9.0

func (m *MockExecutor) AddGHAPIJobs(owner, repo string, runID int64, jobs string)

AddGHAPIJobs mocks a gh api call for workflow run jobs.

func (*MockExecutor) AddGHAPILatestRun added in v1.9.0

func (m *MockExecutor) AddGHAPILatestRun(owner, repo, workflow string, runID int64, status string)

AddGHAPILatestRun mocks a gh api call for the latest run of a workflow file. A workflow is filtered on its own endpoint rather than a query parameter, which the runs collection has none of.

func (*MockExecutor) AddGHAPIRun added in v1.9.0

func (m *MockExecutor) AddGHAPIRun(owner, repo string, runID int64, status, conclusion string)

AddGHAPIRun mocks a gh api call for workflow run data.

func (*MockExecutor) AddGHAuthStatus added in v1.9.0

func (m *MockExecutor) AddGHAuthStatus(authenticated bool, username string)

AddGHAuthStatus mocks the gh auth status command.

func (*MockExecutor) AddGHRunView added in v1.9.0

func (m *MockExecutor) AddGHRunView(runID, jobID int64, logOutput string)

AddGHRunView is a convenience method for adding gh run view commands.

func (*MockExecutor) AddGHRunViewError added in v1.9.0

func (m *MockExecutor) AddGHRunViewError(runID, jobID int64, stderr string, err error)

AddGHRunViewError is a convenience method for adding failing gh run view commands.

func (*MockExecutor) AddGHVersion added in v1.9.0

func (m *MockExecutor) AddGHVersion(version string)

AddGHVersion mocks the gh --version command.

func (*MockExecutor) AddGHWorkflowRun added in v1.9.0

func (m *MockExecutor) AddGHWorkflowRun(workflow, branch string, inputs map[string]string)

AddGHWorkflowRun mocks a successful gh workflow run command.

func (*MockExecutor) AddGHWorkflowRunError added in v1.9.0

func (m *MockExecutor) AddGHWorkflowRunError(workflow, branch, stderr string, err error)

AddGHWorkflowRunError mocks a failing gh workflow run command.

func (*MockExecutor) Execute added in v1.9.0

func (m *MockExecutor) Execute(name string, args ...string) (string, string, error)

Execute simulates command execution by looking up the command in the Commands map.

func (*MockExecutor) Reset added in v1.9.0

func (m *MockExecutor) Reset()

Reset clears all command history and configurations.

type MockGitHubClient

type MockGitHubClient struct {
	Err              error
	Runs             map[int64]*github.WorkflowRun
	Jobs             map[int64][]github.Job
	LatestByWorkflow map[string]int64

	LatestID int64
	// contains filtered or unexported fields
}

MockGitHubClient implements both chain.GitHubClient and watcher.GitHubClient interfaces.

func NewMockGitHubClient

func NewMockGitHubClient() *MockGitHubClient

NewMockGitHubClient creates a MockGitHubClient with sensible defaults.

func (*MockGitHubClient) GetLatestRun

func (m *MockGitHubClient) GetLatestRun(workflow string) (*github.WorkflowRun, error)

GetLatestRun returns the mocked latest run for workflow.

func (*MockGitHubClient) GetWorkflowRun

func (m *MockGitHubClient) GetWorkflowRun(runID int64) (*github.WorkflowRun, error)

GetWorkflowRun returns the mocked run for runID, or a queued stub if none is configured.

func (*MockGitHubClient) GetWorkflowRunJobs

func (m *MockGitHubClient) GetWorkflowRunJobs(runID int64) ([]github.Job, error)

GetWorkflowRunJobs returns the mocked jobs for runID.

func (*MockGitHubClient) Owner

func (m *MockGitHubClient) Owner() string

Owner returns the mocked repository owner.

func (*MockGitHubClient) Repo

func (m *MockGitHubClient) Repo() string

Repo returns the mocked repository name.

func (*MockGitHubClient) WithError

func (m *MockGitHubClient) WithError(err error) *MockGitHubClient

WithError sets the error to return from all methods.

func (*MockGitHubClient) WithJobs

func (m *MockGitHubClient) WithJobs(runID int64, jobs []github.Job) *MockGitHubClient

WithJobs adds jobs for a run to the mock.

func (*MockGitHubClient) WithOwnerRepo

func (m *MockGitHubClient) WithOwnerRepo(owner, repo string) *MockGitHubClient

WithOwnerRepo sets the owner and repo for the mock client.

func (*MockGitHubClient) WithRun

WithRun adds a workflow run to the mock.

type MockRunWatcher

type MockRunWatcher struct {
	Watched map[int64]string
	// contains filtered or unexported fields
}

MockRunWatcher implements chain.RunWatcher interface.

func NewMockRunWatcher

func NewMockRunWatcher() *MockRunWatcher

NewMockRunWatcher creates a new MockRunWatcher.

func (*MockRunWatcher) Close

func (m *MockRunWatcher) Close()

Close closes the updates channel.

func (*MockRunWatcher) SendUpdate

func (m *MockRunWatcher) SendUpdate(update watcher.RunUpdate)

SendUpdate sends an update to the mock watcher's channel (for testing).

func (*MockRunWatcher) Unwatch

func (m *MockRunWatcher) Unwatch(runID int64)

Unwatch removes runID from the watched set.

func (*MockRunWatcher) Updates

func (m *MockRunWatcher) Updates() <-chan watcher.RunUpdate

Updates returns the mocked run update channel.

func (*MockRunWatcher) Watch

func (m *MockRunWatcher) Watch(runID int64, workflowName string)

Watch records runID as watched for workflowName.

Jump to

Keyboard shortcuts

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