testutil

package
v0.16.2 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package testutil provides test helpers and fixtures for nbc testing.

Package testutil provides test helpers and fixtures for nbc testing.

This file imports test infrastructure dependencies to ensure they are tracked in go.mod. These will be used by the Incus fixture and golden file helpers in subsequent plans.

Package testutil provides test helpers and fixtures for nbc testing.

Package testutil provides test helpers and fixtures for nbc testing.

Index

Constants

View Source
const (
	// TimeoutUnit is for unit tests (no I/O, no external dependencies)
	TimeoutUnit = 30 * time.Second

	// TimeoutIntegration is for integration tests (disk operations, container builds)
	TimeoutIntegration = 2 * time.Minute

	// TimeoutVM is the overall timeout for VM-based tests
	TimeoutVM = 10 * time.Minute

	// TimeoutVMBoot is specifically for waiting for VM boot completion
	TimeoutVMBoot = 2 * time.Minute

	// TimeoutVMInstall is for nbc install operations inside VM
	TimeoutVMInstall = 15 * time.Minute

	// TimeoutOperation is the default timeout for individual Incus operations
	TimeoutOperation = 60 * time.Second
)

Test timeout constants by test type. Use these with context.WithTimeout for consistent, explicit timeouts.

Variables

This section is empty.

Functions

func AssertGolden added in v0.15.0

func AssertGolden(t *testing.T, name string, actual []byte)

AssertGolden is a convenience wrapper that normalizes output and asserts against golden file. It combines NormalizeOutput and goldie assertion in one call.

Usage:

func TestCLI_Status(t *testing.T) {
    output := runCommand("nbc", "status")
    testutil.AssertGolden(t, "status-output", []byte(output))
}

func AssertGoldenString added in v0.15.0

func AssertGoldenString(t *testing.T, name string, actual string)

AssertGoldenString is like AssertGolden but takes a string instead of bytes.

func BuildContainerFromDir

func BuildContainerFromDir(t *testing.T, rootDir, imageName string) error

BuildContainerFromDir builds a container image from a directory

func CheckToolExists

func CheckToolExists(t *testing.T, tool string)

CheckToolExists checks if a required tool is available

func CleanupAllNbcTestResources added in v0.15.0

func CleanupAllNbcTestResources() error

CleanupAllNbcTestResources removes all nbc-test-* instances and volumes. This is the non-test version for use in TestMain where *testing.T is not available. Returns error only if cannot connect to Incus; cleanup failures are silent.

Example TestMain usage:

func TestMain(m *testing.M) {
    testutil.CleanupAllNbcTestResources() // Clean slate
    code := m.Run()
    testutil.CleanupAllNbcTestResources() // Final cleanup
    os.Exit(code)
}

func CleanupMounts

func CleanupMounts(t *testing.T, mountPoint string)

CleanupMounts unmounts any mounts under a directory

func CleanupOrphanedMounts added in v0.15.0

func CleanupOrphanedMounts(pattern string)

CleanupOrphanedMounts force unmounts any mounts matching the given pattern. This is useful for cleaning up mounts from failed tests. All errors are silently ignored.

Example:

CleanupOrphanedMounts("/mnt/nbc-test-*")

func CleanupOrphanedResources added in v0.15.0

func CleanupOrphanedResources(t *testing.T)

CleanupOrphanedResources removes any orphaned nbc-test-* instances and volumes. This should be called at the start of test suites to ensure a clean slate. All cleanup errors are silently ignored per CONTEXT.md decisions.

Usage:

func TestMain(m *testing.M) {
    testutil.CleanupAllNbcTestResources()
    code := m.Run()
    testutil.CleanupAllNbcTestResources()
    os.Exit(code)
}

func CreateMockContainer

func CreateMockContainer(t *testing.T, imageName string) error

CreateMockContainer creates a minimal container image for testing

func NewGolden added in v0.15.0

func NewGolden(t *testing.T) *goldie.Goldie

NewGolden creates a configured goldie instance for golden file testing. Uses testdata directory with .golden suffix and colored diff output.

Usage:

func TestCLI_List(t *testing.T) {
    output := runCommand("nbc", "list")
    g := testutil.NewGolden(t)
    g.Assert(t, "list-output", []byte(output))
}

Update golden files: go test -update ./...

func NormalizeOutput added in v0.15.0

func NormalizeOutput(s string) string

NormalizeOutput normalizes dynamic content in output before golden file comparison. This ensures tests are deterministic despite timestamps, UUIDs, and paths.

Normalizations applied:

  • ISO timestamps (2024-01-15T10:30:45Z) -> TIMESTAMP
  • UUIDs (8-4-4-4-12 format) -> UUID
  • Loop devices (/dev/loop0) -> /dev/loopN
  • Temp paths (/tmp/...) -> /tmp/...

Structure and ordering are preserved.

func RequireRoot

func RequireRoot(t *testing.T)

RequireRoot skips the test if not running as root

func RequireTools

func RequireTools(t *testing.T, tools ...string)

RequireTools checks for required tools and skips if any are missing

func WaitForDevice

func WaitForDevice(device string) error

WaitForDevice waits for a device to appear (useful after partitioning)

Types

type IncusFixture added in v0.15.0

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

IncusFixture wraps an Incus client with test-specific helpers for VM management. It provides a clean interface for creating, managing, and cleaning up VMs during integration tests.

func NewIncusFixture added in v0.15.0

func NewIncusFixture(t *testing.T) *IncusFixture

NewIncusFixture creates a new Incus test fixture connected to the local socket. It registers cleanup handlers via t.Cleanup() before creating any resources, ensuring cleanup runs even on test failure.

If Incus is not available (socket doesn't exist or connection fails), the test is skipped rather than failed.

func (*IncusFixture) AttachDisk added in v0.15.0

func (f *IncusFixture) AttachDisk(volumeName string, size string) error

AttachDisk creates and attaches a block storage volume to the VM. The volume name is automatically made unique per test. The volume is tracked for cleanup.

func (*IncusFixture) Cleanup added in v0.15.0

func (f *IncusFixture) Cleanup()

Cleanup performs best-effort cleanup of all resources created by this fixture. It silently ignores errors per CONTEXT.md decisions - cleanup failures should not mask test failures.

func (*IncusFixture) Client added in v0.15.0

func (f *IncusFixture) Client() incus.InstanceServer

Client returns the underlying Incus client for advanced operations.

func (*IncusFixture) CreateBaselineSnapshot added in v0.15.0

func (f *IncusFixture) CreateBaselineSnapshot(name string) error

CreateBaselineSnapshot creates a snapshot named "baseline" of the current VM state. This should be called immediately after VM boot, before any test operations. If name is empty, defaults to "baseline".

func (*IncusFixture) CreateSnapshot added in v0.15.0

func (f *IncusFixture) CreateSnapshot(name string) error

CreateSnapshot creates a snapshot of the VM with the given name.

func (*IncusFixture) CreateVM added in v0.15.0

func (f *IncusFixture) CreateVM(image string) error

CreateVM launches a new VM with the specified image. Uses standard test configuration: 4 CPU, 16GiB RAM, secureboot disabled.

func (*IncusFixture) DumpDiagnostics added in v0.15.0

func (f *IncusFixture) DumpDiagnostics(reason string)

DumpDiagnostics captures diagnostic information on test failure. It writes to test-failures/{testName}_{timestamp}.log and logs a summary inline. The reason parameter is included in the log (e.g., "timeout after 60s waiting for VM boot").

func (*IncusFixture) ExecCommand added in v0.15.0

func (f *IncusFixture) ExecCommand(command ...string) (string, error)

ExecCommand executes a command inside the VM and returns stdout. Returns an error if the command fails or returns non-zero exit code.

func (*IncusFixture) PushFile added in v0.15.0

func (f *IncusFixture) PushFile(localPath, remotePath string) error

PushFile uploads a local file to the VM.

func (*IncusFixture) ResetToSnapshot added in v0.15.0

func (f *IncusFixture) ResetToSnapshot(ctx context.Context, name string) error

ResetToSnapshot restores the VM to a snapshot and waits for it to be ready. This is intended for per-test reset to ensure isolation. Uses the provided context for timeout during the ready wait.

func (*IncusFixture) RestoreSnapshot added in v0.15.0

func (f *IncusFixture) RestoreSnapshot(name string) error

RestoreSnapshot restores the VM to a previously created snapshot. The VM will be stopped before restoring and started after.

func (*IncusFixture) VMName added in v0.15.0

func (f *IncusFixture) VMName() string

VMName returns the unique VM name for this fixture.

func (*IncusFixture) VolumeName added in v0.15.0

func (f *IncusFixture) VolumeName() string

VolumeName returns the storage volume name created by AttachDisk. Returns empty string if no volume has been attached.

func (*IncusFixture) WaitForReady added in v0.15.0

func (f *IncusFixture) WaitForReady(ctx context.Context) error

WaitForReady polls the VM until systemd reports system is running. Uses the provided context for timeout/cancellation. On timeout, returns an error including the last action and duration waited.

type TestDisk

type TestDisk struct {
	ImagePath  string
	LoopDevice string
	Size       int64 // Size in bytes
	Mounted    bool
	// contains filtered or unexported fields
}

TestDisk represents a test disk image with loop device

func CreateTestDisk

func CreateTestDisk(t *testing.T, sizeGB int) (*TestDisk, error)

CreateTestDisk creates a disk image file and attaches it to a loop device

func (*TestDisk) Cleanup

func (d *TestDisk) Cleanup()

Cleanup detaches the loop device and removes the image file

func (*TestDisk) GetDevice

func (d *TestDisk) GetDevice() string

GetDevice returns the loop device path (e.g., /dev/loop0)

Jump to

Keyboard shortcuts

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