testutil

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package testutil holds the helpers and fakes the test suites share: a fresh database and readers of its rows (Query, Column, Map), an isolated git, git repositories built once per test binary and copied into each test (GitTemplate), programs planted in a clone's own config for the guard tests, temporary files and agent homes, listings of a folder's names and of every path under it (DirNames, Tree), recorded runs of real tools (Recording), fakes for the small interfaces services take (a program runner, a program finder, a clock, and an event sink), and an in-memory log.

It is test support only. Only _test.go files may import it, which a repoguard test enforces, so none of it reaches the app. It imports the store to open databases, so the store's own internal tests, and those of the packages the store imports, cannot use it.

Index

Constants

View Source
const (
	GitName  = "Octo User"
	GitEmail = "octo-user@example.com"
)

GitName and GitEmail are the identity every isolated git command commits as.

View Source
const AlternateRefs = "evil-alternate-refs"

AlternateRefs is the name of the planting of an alternate refs command, which a fetch runs only in a clone with alternates, so Plant gives a clone it plants it in an alternate object store to ask about.

View Source
const TerminalScript = `` /* 216-byte string literal not displayed */

TerminalScript is what a fake terminal's shell runs for a run in the terminal, the command in its arguments: what the script the app writes for such a run does under script(1), in plain sh, so a test needs no pseudo-terminal. It records the shell's PID in $PID_FILE, runs the command with its output added to $LOG_FILE, and writes its exit status to $EXIT_FILE.tmp, then renames that into $EXIT_FILE: the files the runner follows the run through. With NO_EXIT_FILE set, the shell ends without the exit status, as a terminal closed just as the command ended leaves it.

Run it as /bin/sh -c TerminalScript sh <command> <arguments>....

Variables

View Source
var ErrNotFound = errors.New("testutil: program not found")

ErrNotFound is what Finder fails with for a name it does not resolve.

Functions

func AgentHome

func AgentHome(t testing.TB, dirs ...string) string

AgentHome returns a fresh home directory holding dirs, made as MakeAgentDirs makes them.

func ClaudeHome

func ClaudeHome(t testing.TB, dirs ...string) string

ClaudeHome returns a fresh home directory holding dirs, as AgentHome does.

func ClosedDB

func ClosedDB(t testing.TB) *sql.DB

ClosedDB returns a migrated database that is already closed, so every query on it fails, for testing how code reports a database it cannot use.

func Column

func Column[T any](t testing.TB, db *sql.DB, query string, args ...any) []T

Column runs query on db with args, which selects one column, and returns its values in order, as Query does: an empty list, never nil, for none.

func Commit

func Commit(t testing.TB, dir, name, content string) string

Commit writes content to the file name in the repository at dir, creating its directory, adds it, and commits it with name as the message, isolated as RunGit describes. It returns the new commit.

func DB

func DB(t testing.TB) *sql.DB

DB opens a fresh, migrated database in a temporary directory and closes it when the test ends.

func DBAt

func DBAt(t testing.TB, path string) *sql.DB

DBAt opens the database at path, creating and migrating it when needed, and closes it when the test ends. A test of what survives a restart opens the same path twice. The test fails if the database at path could not be used and was set aside.

A database that does not exist yet starts as a copy of one migrated once per test binary, which store.Open then opens as it would any migrated database, checking its migration history; an existing file is opened as it is.

func DBFile added in v0.6.0

func DBFile(t testing.TB, path string)

DBFile creates the database file at path, which does not exist yet, and its folder, as store.Open would, holding a copy of a database migrated once per test binary. Code that opens the database itself, such as a whole app's start, then finds it migrated rather than running every migration again.

func DirNames

func DirNames(t testing.TB, dir string) []string

DirNames returns the names of what dir holds, sorted, as os.ReadDir lists them: an empty list, never nil, for an empty folder. It fails the test when dir can't be read, a missing one included.

func ErrOf

func ErrOf[T any](_ T, err error) error

ErrOf returns err and drops the value that came with it, for a call a test makes only for its effect, as in require.NoError(t, testutil.ErrOf(svc.SetTheme(ctx, theme))).

func Exec

func Exec(t testing.TB, db *sql.DB, query string, args ...any)

Exec runs a statement on db that the code under test has no call for, such as a row written by hand or a trigger that makes a write fail, and fails the test, naming the statement, when it fails.

func FakeTool

func FakeTool(t testing.TB, name string, run FakeRun) (path, env string)

FakeTool makes a fake tool called name: a symbolic link in a new temporary folder that points at this test binary, which plays run when started under that name. It returns the link's path and the environment entry the code under test must pass to it, so tests stay parallel; the package's TestMain must call FakeToolMain first. No script is written, and no executable either, so parallel tests never meet ETXTBSY.

func FakeToolMain

func FakeToolMain()

FakeToolMain plays a fake tool and exits when this test binary was started as one; otherwise it returns at once, once it has made the fakes the tests start skip the race detector's pause at exit. Call it first in TestMain.

func Git

func Git(t testing.TB) []string

Git skips the test when git is not installed, and otherwise returns a GitEnv over a fresh home directory.

func GitEnv

func GitEnv(home string) []string

GitEnv returns an environment for git that reads none of the user's or the system's configuration: home is HOME, and XDG_CONFIG_HOME is under it, so no personal ignore or attributes file applies either, and commits are made as GitName and GitEmail. Every GIT_ variable inherited from the test process is dropped, so a test run from a git hook, which sets GIT_DIR and GIT_INDEX_FILE, cannot reach the repository the hook runs in.

It is meant for cmd.Env, or execpath.Exec's Env when the code under test runs git, so a test can isolate git without changing the process environment and still run in parallel.

func InitRepo

func InitRepo(t testing.TB, dir string)

InitRepo creates dir, when it is missing, as a new git repository whose first branch is main.

func LoadRecording

func LoadRecording[T Recorded](t testing.TB, dir, name string) T

LoadRecording reads the recording called name from the folder dir, and fails the test unless it names itself name.

func MakeAgentDirs

func MakeAgentDirs(t testing.TB, home string, dirs ...string)

MakeAgentDirs creates each of dirs, with its parents, under home. A top-level one named like a named profile's config directory of some coding agent, such as .claude_<name>, .claude-<name>, or .codex_<name>, also holds the agent's first config marker (Claude's state file, or Codex's sign-in), as the agent writes it on its first run with the directory, so profile discovery lists it.

func MakeClaudeDirs

func MakeClaudeDirs(t testing.TB, home string, dirs ...string)

MakeClaudeDirs creates each of dirs under home, as MakeAgentDirs does.

func Map

func Map[K comparable, V any](t testing.TB, db *sql.DB, query string, args ...any) map[K]V

Map runs query on db with args, which selects two columns, and returns the second keyed by the first, as Query reads them: a key a later row repeats holds that row's value, and none is an empty map, never nil.

func Query

func Query[T any](t testing.TB, db *sql.DB, fields func(*T) []any, query string, args ...any) []T

Query runs query on db with args, for a check of what the code under test stored, and returns its rows in order, each scanned into a T through the destinations fields gives for it:

testutil.Query(t, db, func(r *row) []any { return []any{&r.id, &r.label} }, `SELECT id, label FROM ...`)

fields may also hand Scan a destination of its own for a column the test doesn't keep. Query fails the test, naming the query, when the query, a row's scan, or reading the rows fails; it closes the rows, and returns an empty list, never nil, for none.

func RealTempDir

func RealTempDir(t testing.TB) string

RealTempDir returns a new temporary directory with its symbolic links resolved. On macOS the temporary directory sits under one, and code that resolves a path, as an agent does with its working directory, sees the resolved form.

func RecordingNames

func RecordingNames(t testing.TB, dir, prefix string) []string

RecordingNames lists the names of the recordings in the folder dir whose names start with prefix, in order, and fails the test when there are none.

func RequireGit

func RequireGit(t testing.TB) string

RequireGit skips the test when git is not installed and returns its path.

func RunGit

func RunGit(t testing.TB, dir string, args ...string) string

RunGit runs git with args in dir, isolated as GitEnv describes over an empty home every call shares, and returns what it wrote to standard output. It skips the test when git is not installed, and a failure fails the test with what git wrote to standard error.

func SkipAsRoot

func SkipAsRoot(t testing.TB)

SkipAsRoot skips a test that relies on file permissions, which root ignores.

func SocketDir added in v0.7.0

func SocketDir(t testing.TB) string

SocketDir returns a new temporary directory with a short path, removed when the test ends, to hold a Unix socket: macOS caps a socket's path at 104 bytes, which a folder t.TempDir names for a long test name can pass on its own.

func Tree

func Tree(t testing.TB, root string) []string

Tree returns every path under root, root first, each as filepath.WalkDir names it (root joined with its path there) and in the order it walks them: lexical, a folder before what it holds. A link is listed, never followed, so what it points to is left out. It fails the test when any of it can't be read, a missing root included.

A test takes a Tree before and after the code it checks to show what that code wrote.

func WriteExecutable

func WriteExecutable(t testing.TB, path, content string)

WriteExecutable writes content to path with mode 0700, creating its directory, so the test can run it.

func WriteFile

func WriteFile(t testing.TB, path, content string)

WriteFile writes content to path with mode 0600, creating its directory.

func WriteFileMode

func WriteFileMode(t testing.TB, path, content string, mode os.FileMode)

WriteFileMode writes content to path, creating its directory, and leaves the file with exactly mode: it is set again after the write, so neither the umask nor the mode of a file already at path changes it.

Types

type Clock

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

Clock is a fake clock that is safe for concurrent use. It stands still until the test moves it, unless it was made with a step, when every read moves it on by that step.

func NewClock

func NewClock(now time.Time) *Clock

NewClock returns a Clock that reads now until the test moves it.

func NewSteppingClock

func NewSteppingClock(start time.Time, step time.Duration) *Clock

NewSteppingClock returns a Clock whose first read is start and whose every read after is step later than the one before.

func (*Clock) Advance

func (c *Clock) Advance(d time.Duration) time.Time

Advance moves the clock on by d and returns the new time.

func (*Clock) Now

func (c *Clock) Now() time.Time

Now returns the clock's time, then moves the clock on by its step.

func (*Clock) Set

func (c *Clock) Set(now time.Time)

Set moves the clock to now.

type Events

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

Events is an event.Sink that records every event a service emits, in order. It is safe for concurrent use.

func (*Events) All

func (s *Events) All() []event.Event

All returns a copy of the events so far, in order.

func (*Events) Count

func (s *Events) Count() int

Count returns how many events have been emitted so far.

func (*Events) Emit

func (s *Events) Emit(e event.Event)

Emit records e.

type FakeFile

type FakeFile struct {
	Path    string      `json:"path"`
	Content string      `json:"content,omitempty"`
	Mode    os.FileMode `json:"mode,omitempty"`
	From    string      `json:"from,omitempty"`
	Remove  bool        `json:"remove,omitempty"`
}

FakeFile is one change a fake tool makes to the file at Path, absolute or relative to the folder the tool runs in, such as the clone a run starts in: it renames From to Path when From is set, removes Path when Remove is set, and otherwise writes Content to Path with Mode (0o644 when zero), keeping the mode of a file already there, as os.WriteFile does.

type FakeGrandchild

type FakeGrandchild struct {
	PIDFile string        `json:"pidFile"`
	Sleep   time.Duration `json:"sleep"`

	// Setsid starts it in a session of its own, outside the fake's process group, as
	// an agent or daemon does.
	Setsid bool `json:"setsid,omitempty"`

	// IgnoreSignals makes it ignore SIGINT, SIGTERM, and SIGHUP.
	IgnoreSignals bool `json:"ignoreSignals,omitempty"`
}

FakeGrandchild is a process a fake tool leaves behind: it writes its PID to PIDFile, then sleeps, holding the fake's output open.

type FakeInterrupt added in v0.4.0

type FakeInterrupt struct {
	Stdout string `json:"stdout"`
	Exit   int    `json:"exit"`
}

FakeInterrupt is what a fake tool does when SIGINT or SIGTERM comes.

type FakeRun

type FakeRun struct {
	Stdout string `json:"stdout"`
	Stderr string `json:"stderr"`
	Exit   int    `json:"exit"`

	// WantArgs, when set, are the arguments it must be started with. Started with any
	// others, it does nothing else: it names both on stderr and exits with status 2, as a
	// tool given a flag it doesn't know does.
	WantArgs []string `json:"wantArgs,omitempty"`

	// Files are changed in order before it writes, as a tool that writes, moves, or
	// removes files does: go-pre-commit installing a hook, or fixing a file.
	Files []FakeFile `json:"files,omitempty"`

	// Sleep is how long it waits after writing, before it exits.
	Sleep time.Duration `json:"sleep,omitempty"`

	// WaitFor, when set, names a file that ends the Sleep early: it exits as soon as the
	// file appears, so a test that must see it running decides when it ends, rather than
	// guessing how long it takes to start. Sleep still bounds the wait; with no Sleep, a
	// minute does, so a fake whose file never appears doesn't outlive its test for long.
	WaitFor string `json:"waitFor,omitempty"`

	// IgnoreSignals makes it ignore SIGINT, SIGTERM, and SIGHUP, so only SIGKILL ends it.
	IgnoreSignals bool `json:"ignoreSignals,omitempty"`

	// Grandchild, when set, is started first, sharing the fake's output.
	Grandchild *FakeGrandchild `json:"grandchild,omitempty"`

	// ReportStdin writes "stdin: <n> bytes, devnull: <bool>" to stdout: what it read
	// from stdin, and whether stdin is /dev/null.
	ReportStdin bool `json:"reportStdin,omitempty"`

	// ReportFDs writes "fds: 0,1,2" to stdout: every descriptor open in it.
	ReportFDs bool `json:"reportFds,omitempty"`

	// ReportEnv writes "NAME=value" to stdout for each variable it names, in order, a line
	// each: the variable as the fake reads it from its environment, or empty when unset.
	ReportEnv []string `json:"reportEnv,omitempty"`

	// StdinTo, when set, names a file it copies its whole stdin into before it writes, as
	// an agent that reads its prompt there does.
	StdinTo string `json:"stdinTo,omitempty"`

	// OnInterrupt, when set, is what it does on SIGINT or SIGTERM: write its Stdout and
	// exit with its Exit, as an agent that reports how it ended does when it is stopped.
	// Only SIGKILL then ends it otherwise.
	OnInterrupt *FakeInterrupt `json:"onInterrupt,omitempty"`
}

FakeRun is what a fake tool does when it runs, in this order: check its arguments, ignore signals, start a grandchild, report its stdin, open descriptors, or environment, change Files, write Stdout and Stderr, sleep (until WaitFor appears, when set), and exit with Exit. A recorded fixture's {"stdout", "stderr", "exit"} reads straight into it (see LoadFakeRun).

func LoadFakeRun

func LoadFakeRun(t testing.TB, path string) FakeRun

LoadFakeRun reads a recorded fixture, {"stdout", "stderr", "exit"} with any other fields ignored, as a FakeRun.

type Finder

type Finder struct {
	// Path is what every name resolves to when Paths is nil.
	Path string

	// Paths, when set, maps the only names Finder resolves to their paths; any other
	// name fails with ErrNotFound.
	Paths map[string]string

	// Err, when set, is what every lookup fails with.
	Err error
}

Finder is a fake execpath.Finder: it resolves names without looking at the disk.

func (Finder) Find

func (f Finder) Find(name string) (string, error)

Find resolves name.

type GitBuild

type GitBuild struct {
	// Root is the template: everything under it is copied.
	Root string
	// contains filtered or unexported fields
}

GitBuild is where a template is built: Root, a fresh folder with its symbolic links resolved, which each copy's folder takes the place of, and a git isolated as GitEnv describes, which dates every commit and tag alike, at 2026-01-02 03:04:05 UTC. A build is its steps in order: once one fails, the rest do nothing, and the build fails with that first failure.

What a build may leave has limits, as a copy works without git but for refreshing an index, and the build fails, naming the file, past any of them. Root holds only folders and regular files, no link. Only text, UTF-8 with no NUL byte, names Root, since a copy writes its own folder's path in place of Root's: never an index, a pack, or another file whose length or checksum a rewrite would break. And every index belongs to a work tree inside Root, a clone's own (<work tree>/.git/index) or a linked worktree's (<git folder>/worktrees/<name>/index), never a submodule's.

func (*GitBuild) Commit

func (b *GitBuild) Commit(dir, name, content string) string

Commit writes content to the file name in the repository at dir, relative to Root, adds it, and commits it with name as the message, as Commit does in a test, and returns the new commit, or "" after a failed step.

func (*GitBuild) Git

func (b *GitBuild) Git(dir string, args ...string) string

Git runs git with args in dir, relative to Root, and returns what it wrote to standard output, with its surrounding space trimmed, as a commit ID is read. After a failed step it runs nothing and returns "".

func (*GitBuild) WriteFile

func (b *GitBuild) WriteFile(name, content string)

WriteFile writes content to the file at name, relative to Root, with mode 0600, making the folders it needs. After a failed step it writes nothing.

type GitTemplate

type GitTemplate[V any] struct {
	// contains filtered or unexported fields
}

GitTemplate is a folder of git repositories, such as an origin and its clone, built once per test binary, the first time a test asks for a copy, and copied whole into each test that does. A suite whose rigs start from the same repositories pays for git's commands once, and each test still gets repositories of its own to commit to, push to, or break. Its value is what the build returned, such as the commit IDs it made, which every copy shares: the copies hold the same commits.

func NewGitTemplate

func NewGitTemplate[V any](build func(b *GitBuild) V) *GitTemplate[V]

NewGitTemplate returns the template build makes. build runs at most once, outside any test: a step of it that fails (see GitBuild) fails every test that asks for a copy.

func (*GitTemplate[V]) Copy

func (g *GitTemplate[V]) Copy(t testing.TB, dir string) V

Copy copies the template into dir, which may already exist but must hold none of the template's files, and returns what its build returned. Every file that named the folder the template was built in, such as a clone's config naming its origin, names dir in its place, and each work tree's index, a linked worktree's included, is refreshed, as the copy gave every file new times. It skips the test without git.

type GitTemplates

type GitTemplates[K comparable, V any] struct {
	// contains filtered or unexported fields
}

GitTemplates is a GitTemplate for each key a suite asks for, such as each name its clones take, each built the first time a test asks for a copy of it.

func NewGitTemplates

func NewGitTemplates[K comparable, V any](build func(b *GitBuild, key K) V) *GitTemplates[K, V]

NewGitTemplates returns the templates build makes, one for each key.

func (*GitTemplates[K, V]) Copy

func (s *GitTemplates[K, V]) Copy(t testing.TB, key K, dir string) V

Copy copies the template for key into dir, as GitTemplate.Copy does, and returns what its build returned.

type Lister added in v0.6.0

type Lister[P any] struct {
	List []P
	Err  error
	// contains filtered or unexported fields
}

Lister is a fake lister of running processes, a procs.Lister as Lister[procs.Process]: Processes answers List, or fails with Err, and counts its calls. A test sets List and Err before the code under test asks, or between its asks. It takes the process type as a parameter so testutil needs no import of procs, whose own tests import testutil.

func (*Lister[P]) Calls added in v0.6.0

func (l *Lister[P]) Calls() int

Calls returns how often Processes was asked so far.

func (*Lister[P]) Processes added in v0.6.0

func (l *Lister[P]) Processes(context.Context) ([]P, error)

Processes answers List and Err.

type Logs

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

Logs collects a logger's records, or any other text written to it, in memory for a test to read. It is safe for concurrent use.

func (*Logs) Logger

func (l *Logs) Logger() *slog.Logger

Logger returns a logger that writes every record, Debug and up, into l.

func (*Logs) String

func (l *Logs) String() string

String returns every record written so far.

func (*Logs) Write

func (l *Logs) Write(p []byte) (int, error)

Write appends p.

type Planter

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

Planter plants programs in the config of clones a test made, the way a clone's own config could make git run one, for a guard test to show they never run. Each program is a fake (FakeTool) that writes a marker file, named after it, in the folder ran under home when it runs. The Planter keeps the environment git runs with, an isolated git's over home (GitEnv) with every fake's entry added, which a fake needs to run as one. It is safe for concurrent use.

func NewPlanter

func NewPlanter(t testing.TB, home string) *Planter

NewPlanter returns a Planter whose git runs isolated over home.

func (*Planter) AddEnv

func (p *Planter) AddEnv(entry string)

AddEnv adds entry, a KEY=value, to the environment git runs with.

func (*Planter) Environ

func (p *Planter) Environ() []string

Environ returns a copy of the environment git runs with.

func (*Planter) Marker

func (p *Planter) Marker(name string) (program, marker string)

Marker makes a fake program called name that writes ran/<name> under home when it runs, and returns its path and that file's.

func (*Planter) Plant

func (p *Planter) Plant(dir string, planting Planting) string

Plant sets planting in the clone at dir's own config, pointing at a Marker fake, and returns its marker file. The planting of AlternateRefs comes with an alternate object store, an empty repository's, for a fetch to ask it about.

func (*Planter) PlantHooks

func (p *Planter) PlantHooks(dir, hook string) string

PlantHooks points the clone at dir's own core.hooksPath at a folder whose hook called hook is a Marker fake, and returns its marker file.

type Planting

type Planting struct {
	Name     string
	Settings [][2]string
}

Planting is one way a clone's own config could make git run a program of the clone's: the name of the fake program planted, and the settings that name it, each a key and a value in which %s stands for the fake's path.

func (Planting) Keys

func (p Planting) Keys() []string

Keys returns the keys of p's settings as git lists them: the section and the name lowercased, a subsection as written.

type Recorded

type Recorded interface {
	// contains filtered or unexported methods
}

Recorded is a Recording, or a type that embeds one.

type RecordedLine

type RecordedLine struct {
	Stream string `json:"stream"`
	Text   string `json:"text"`
}

RecordedLine is one line a recorded run wrote: its stream, "out" or "err", and its text without the newline.

type Recording

type Recording struct {
	Name   string         `json:"name"`
	Argv   []string       `json:"argv"`
	Stdout string         `json:"stdout"`
	Stderr string         `json:"stderr"`
	Exit   int            `json:"exit"`
	Lines  []RecordedLine `json:"lines"`
}

Recording is one recorded run of a real tool, as the recorder writes it to a file <name>.json in a suite's testdata: its name, its arguments, what it wrote to stdout and stderr, its exit status, and its lines in the order they arrived. A suite whose recorder writes more embeds it in a type of its own, which LoadRecording reads too.

func (Recording) Log

func (r Recording) Log(eol string) string

Log returns the run's output as one log holds it, stdout and stderr in the order they arrived, each line ended by eol.

type Runner

type Runner struct {
	// Stdout, Stderr, and Err answer every call when Script is nil.
	Stdout string
	Stderr string
	Err    error

	// Script, when set, answers each call instead. It gets the call's context, so it can
	// check a deadline, and the argv: the program name followed by its arguments. It
	// runs outside the Runner's lock, so it guards any state of its own.
	Script func(ctx context.Context, argv []string) (stdout, stderr []byte, err error)
	// contains filtered or unexported fields
}

Runner is a fake execpath.Runner: it records each argv it is asked to run, runs nothing, and answers with Stdout, Stderr, and Err, or with Script when that is set. It is safe for concurrent use.

func (*Runner) Calls

func (r *Runner) Calls() [][]string

Calls returns a copy of every argv run so far, in order.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, name string, args ...string) (stdout, stderr []byte, err error)

Run records the argv and answers it.

Jump to

Keyboard shortcuts

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