Documentation
¶
Overview ¶
Package testutil holds the helpers and fakes the test suites share: a fresh database, 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, 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
- Variables
- func AgentHome(t testing.TB, dirs ...string) string
- func ClaudeHome(t testing.TB, dirs ...string) string
- func ClosedDB(t testing.TB) *sql.DB
- func Commit(t testing.TB, dir, name, content string) string
- func DB(t testing.TB) *sql.DB
- func DBAt(t testing.TB, path string) *sql.DB
- func ErrOf[T any](_ T, err error) error
- func Exec(t testing.TB, db *sql.DB, query string, args ...any)
- func FakeTool(t testing.TB, name string, run FakeRun) (path, env string)
- func FakeToolMain()
- func Git(t testing.TB) []string
- func GitEnv(home string) []string
- func InitRepo(t testing.TB, dir string)
- func LoadRecording[T Recorded](t testing.TB, dir, name string) T
- func MakeAgentDirs(t testing.TB, home string, dirs ...string)
- func MakeClaudeDirs(t testing.TB, home string, dirs ...string)
- func RealTempDir(t testing.TB) string
- func RecordingNames(t testing.TB, dir, prefix string) []string
- func RequireGit(t testing.TB) string
- func RunGit(t testing.TB, dir string, args ...string) string
- func SkipAsRoot(t testing.TB)
- func WriteExecutable(t testing.TB, path, content string)
- func WriteFile(t testing.TB, path, content string)
- func WriteFileMode(t testing.TB, path, content string, mode os.FileMode)
- type Clock
- type Events
- type FakeFile
- type FakeGrandchild
- type FakeRun
- type Finder
- type GitBuild
- type GitTemplate
- type GitTemplates
- type Logs
- type Planter
- type Planting
- type Recorded
- type RecordedLine
- type Recording
- type Runner
Constants ¶
const ( GitName = "Octo User" GitEmail = "octo-user@example.com" )
GitName and GitEmail are the identity every isolated git command commits as.
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.
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 ¶
var ErrNotFound = errors.New("testutil: program not found")
ErrNotFound is what Finder fails with for a name it does not resolve.
Functions ¶
func AgentHome ¶
AgentHome returns a fresh home directory holding dirs, made as MakeAgentDirs makes them.
func ClaudeHome ¶
ClaudeHome returns a fresh home directory holding dirs, as AgentHome does.
func ClosedDB ¶
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 Commit ¶
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 Git describes. It returns the new commit.
func DB ¶
DB opens a fresh, migrated database in a temporary directory and closes it when the test ends.
func DBAt ¶
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 ErrOf ¶
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 ¶
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 ¶
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. Call it first in TestMain.
func Git ¶
Git skips the test when git is not installed, and otherwise returns a GitEnv over a fresh home directory.
func GitEnv ¶
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 ¶
InitRepo creates dir, when it is missing, as a new git repository whose first branch is main.
func LoadRecording ¶
LoadRecording reads the recording called name from the folder dir, and fails the test unless it names itself name.
func MakeAgentDirs ¶
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 ¶
MakeClaudeDirs creates each of dirs under home, as MakeAgentDirs does.
func RealTempDir ¶
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 ¶
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 ¶
RequireGit skips the test when git is not installed and returns its path.
func RunGit ¶
RunGit runs git with args in dir, isolated as Git describes, and returns what it wrote to standard output. A failure fails the test with what git wrote to standard error.
func SkipAsRoot ¶
SkipAsRoot skips a test that relies on file permissions, which root ignores.
func WriteExecutable ¶
WriteExecutable writes content to path with mode 0700, creating its directory, so the test can run 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 NewSteppingClock ¶
NewSteppingClock returns a Clock whose first read is start and whose every read after is step later than the one before.
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.
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 FakeRun ¶
type FakeRun struct {
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
Exit int `json:"exit"`
// 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"`
}
FakeRun is what a fake tool does when it runs, in this order: 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).
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.
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 ¶
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.
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.
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.
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 ¶
NewPlanter returns a Planter whose git runs isolated over home.
func (*Planter) Marker ¶
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 ¶
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 ¶
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 ¶
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.
type Recorded ¶
type Recorded interface {
// contains filtered or unexported methods
}
Recorded is a Recording, or a type that embeds one.
type RecordedLine ¶
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.
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.