testhelpers

package
v1.201.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

Test Helpers

This package provides helper utilities for writing tests in the Atmos codebase.

Cobra Command Helpers

Create mock Cobra commands for testing:

import "github.com/cloudposse/atmos/tests/testhelpers"

// Create command with string flags
cmd := testhelpers.NewMockCommand("test", map[string]string{
    "stack":  "dev",
    "format": "yaml",
})

// Create command with boolean flags
cmd := testhelpers.NewMockCommandWithBool("test", map[string]bool{
    "verbose": true,
    "dry-run": false,
})

// Create command with mixed flags
cmd := testhelpers.NewMockCommandWithMixed(
    "test",
    map[string]string{"stack": "dev"},
    map[string]bool{"verbose": true},
)

Filesystem Mock Builder

Fluent interface for building filesystem mocks:

import (
    "go.uber.org/mock/gomock"
    "github.com/cloudposse/atmos/tests/testhelpers"
)

func TestMyFunction(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    // Build a mock filesystem with expected operations
    mockFS := testhelpers.NewMockFS(ctrl).
        WithTempDir("/tmp/test-12345").
        WithFile("/tmp/test-12345/config.yaml", []byte("test: data")).
        WithWriteFile("/tmp/test-12345/output.txt", []byte("result"), 0644).
        WithRemoveAll("/tmp/test-12345", nil).
        Build()

    // Use the mock in your test
    result := myFunctionUsingFS(mockFS)
    assert.NoError(t, result)
}
Available Builder Methods
  • WithTempDir(path) - Expect MkdirTemp to succeed
  • WithTempDirError(err) - Expect MkdirTemp to fail
  • WithFile(path, content) - Expect ReadFile to return content
  • WithFileError(path, err) - Expect ReadFile to fail
  • WithWriteFile(path, content, perm) - Expect WriteFile to succeed
  • WithWriteFileError(path, content, perm, err) - Expect WriteFile to fail
  • WithMkdirAll(path, perm) - Expect MkdirAll to succeed
  • WithMkdirAllError(path, perm, err) - Expect MkdirAll to fail
  • WithRemoveAll(path, err) - Expect RemoveAll with optional error
  • WithStat(path, info, err) - Expect Stat to return FileInfo

Usage Example

func TestProcessOciImage_TempDirFailure(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    // Setup: temp dir creation fails
    mockFS := testhelpers.NewMockFS(ctrl).
        WithTempDirError(fmt.Errorf("permission denied")).
        Build()

    // Execute
    err := processOciImageWithFS(nil, "test/image", "/dest", mockFS)

    // Verify
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "permission denied")
}

Best Practices

  1. Use builders for complex mocks - They make test setup more readable
  2. Chain methods - The fluent interface improves readability
  3. Call Build() last - Always call Build() to get the final mock
  4. One builder per test - Create a new builder for each test case
  5. Document expectations - Add comments explaining why you expect each operation

Adding New Helpers

When adding new helper functions:

  1. Keep them focused and single-purpose
  2. Use fluent interfaces where appropriate
  3. Add comprehensive documentation
  4. Include usage examples
  5. Write tests for the helpers themselves

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindRepoRoot added in v1.196.0

func FindRepoRoot() (string, error)

FindRepoRoot finds the root of the git repository.

func NewMockCommand added in v1.195.0

func NewMockCommand(name string, flags map[string]string) *cobra.Command

NewMockCommand creates a mock Cobra command with the specified flags for testing. This helper simplifies test setup by providing a fluent interface for creating commands.

Example:

cmd := NewMockCommand("test", map[string]string{
    "stack": "dev",
    "format": "yaml",
})

func NewMockCommandWithBool added in v1.195.0

func NewMockCommandWithBool(name string, boolFlags map[string]bool) *cobra.Command

NewMockCommandWithBool creates a mock Cobra command with boolean flags.

func NewMockCommandWithMixed added in v1.195.0

func NewMockCommandWithMixed(name string, stringFlags map[string]string, boolFlags map[string]bool) *cobra.Command

NewMockCommandWithMixed creates a mock Cobra command with both string and boolean flags.

Types

type AtmosRunner

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

AtmosRunner manages running Atmos with optional coverage collection.

func NewAtmosRunner

func NewAtmosRunner(coverDir string) *AtmosRunner

NewAtmosRunner creates a runner that always builds Atmos, with or without coverage instrumentation.

func (*AtmosRunner) BinaryPath

func (r *AtmosRunner) BinaryPath() string

BinaryPath returns the path to the binary being used.

func (*AtmosRunner) Build

func (r *AtmosRunner) Build() error

Build always builds Atmos, with or without coverage instrumentation.

func (*AtmosRunner) Cleanup

func (r *AtmosRunner) Cleanup()

Cleanup removes temporary binary and its directory.

func (*AtmosRunner) Command

func (r *AtmosRunner) Command(args ...string) *exec.Cmd

Command creates an exec.Cmd with GOCOVERDIR and PATH set for nested atmos calls.

func (*AtmosRunner) CommandContext

func (r *AtmosRunner) CommandContext(ctx context.Context, args ...string) *exec.Cmd

CommandContext creates an exec.Cmd with context, GOCOVERDIR and PATH set for nested atmos calls.

type MockFSBuilder added in v1.195.0

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

MockFSBuilder provides a fluent interface for building mock filesystem expectations. This simplifies test setup by allowing method chaining for common filesystem operations.

Example:

mockFS := NewMockFS(ctrl).
    WithTempDir("/tmp/test-12345").
    WithFile("/tmp/test-12345/config.yaml", []byte("test: data")).
    WithRemoveAll("/tmp/test-12345", nil).
    Build()

func NewMockFS added in v1.195.0

func NewMockFS(ctrl *gomock.Controller) *MockFSBuilder

NewMockFS creates a new MockFSBuilder.

func (*MockFSBuilder) Build added in v1.195.0

Build returns the configured MockFileSystem.

func (*MockFSBuilder) WithFile added in v1.195.0

func (b *MockFSBuilder) WithFile(path string, content []byte) *MockFSBuilder

WithFile sets up an expectation for ReadFile to return the specified content.

func (*MockFSBuilder) WithFileError added in v1.195.0

func (b *MockFSBuilder) WithFileError(path string, err error) *MockFSBuilder

WithFileError sets up an expectation for ReadFile to return an error.

func (*MockFSBuilder) WithMkdirAll added in v1.195.0

func (b *MockFSBuilder) WithMkdirAll(path string, perm os.FileMode) *MockFSBuilder

WithMkdirAll sets up an expectation for MkdirAll to succeed.

func (*MockFSBuilder) WithMkdirAllError added in v1.195.0

func (b *MockFSBuilder) WithMkdirAllError(path string, perm os.FileMode, err error) *MockFSBuilder

WithMkdirAllError sets up an expectation for MkdirAll to return an error.

func (*MockFSBuilder) WithRemoveAll added in v1.195.0

func (b *MockFSBuilder) WithRemoveAll(path string, err error) *MockFSBuilder

WithRemoveAll sets up an expectation for RemoveAll to succeed or fail.

func (*MockFSBuilder) WithStat added in v1.195.0

func (b *MockFSBuilder) WithStat(path string, info os.FileInfo, err error) *MockFSBuilder

WithStat sets up an expectation for Stat to return the specified FileInfo.

func (*MockFSBuilder) WithTempDir added in v1.195.0

func (b *MockFSBuilder) WithTempDir(path string) *MockFSBuilder

WithTempDir sets up an expectation for MkdirTemp to return the specified path.

func (*MockFSBuilder) WithTempDirError added in v1.195.0

func (b *MockFSBuilder) WithTempDirError(err error) *MockFSBuilder

WithTempDirError sets up an expectation for MkdirTemp to return an error.

func (*MockFSBuilder) WithWriteFile added in v1.195.0

func (b *MockFSBuilder) WithWriteFile(path string, content []byte, perm os.FileMode) *MockFSBuilder

WithWriteFile sets up an expectation for WriteFile to succeed.

func (*MockFSBuilder) WithWriteFileError added in v1.195.0

func (b *MockFSBuilder) WithWriteFileError(path string, content []byte, perm os.FileMode, err error) *MockFSBuilder

WithWriteFileError sets up an expectation for WriteFile to return an error.

type SandboxEnvironment

type SandboxEnvironment struct {
	TempDir         string
	ComponentsPath  string
	OriginalWorkdir string
}

SandboxEnvironment holds the state for a sandboxed test.

func SetupSandbox

func SetupSandbox(t *testing.T, workdir string) (*SandboxEnvironment, error)

SetupSandbox creates an isolated test environment with copied components.

func (*SandboxEnvironment) Cleanup

func (s *SandboxEnvironment) Cleanup()

Cleanup removes the sandbox directory.

func (*SandboxEnvironment) GetEnvironmentVariables

func (s *SandboxEnvironment) GetEnvironmentVariables() map[string]string

GetEnvironmentVariables returns environment variables for sandbox execution.

Jump to

Keyboard shortcuts

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