Testability and injection
Why every effect is a field on App, and what that buys the tests.
Why does internal/cli route every effectful operation through one struct
instead of calling git, exec, or os.Getenv where needed? Because a
CLI's hard parts are its edges — the terminal, the filesystem, the network
— and tests become trivial when the edges are swappable.
The pattern
App (in internal/cli/root.go) is the process's dependency surface:
| Field | Stands in for |
|---|---|
Out, ErrOut | stdout / stderr writers (captured in tests) |
Getenv | environment lookups (GITHUB_TOKEN) |
LookPath | PATH searches (agore-eval, gh) |
RunCommand | process execution (the eval passthrough) |
ChangedFiles | git diff --name-only <base>...HEAD merged with git status --porcelain |
DescribeTag | git tag --points-at HEAD first, then git describe --tags --exact-match HEAD |
WorkingTreeClean | git status --porcelain cleanliness |
RemoteURL | git remote get-url origin |
PromptInit, PromptCreate | huh interactive forms |
PublishGitHub | the GitHub publisher |
NewApp() wires the real implementations; a test constructs an App with
fakes and drives the cobra command tree through it. No command reaches for
os or exec directly — that discipline is what keeps the pattern
meaningful.
What this buys
Command tests are end-to-end but hermetic. cli_test.go runs real
commands (init, create, inspect, lint, release) against fake git state and
captured output, asserting on exact messages and exit paths. The failure
modes a user would hit — dirty tree, missing tag, unknown target — are
exercised in milliseconds.
The effectful seam is small and explicit. A reviewer can enumerate
everything a command can touch by reading the App struct. No command can
secretly spawn a process or hit the network.
Error paths are first-class. Because exit codes map from returned errors, tests assert the error value, not the process exit — which keeps the tests in-process and the behavior contract explicit.
The boundary holds for future work. A new command (see
How to add a CLI command) starts
testable by construction: it closes over App, not over the world.
The trade-off
Wiring is more verbose than grabbing a global, and the fakes must track the
real signatures (two layers of tests — *_test.go and *_more_test.go —
exist where the seams are widest, in internal/release). The payoff is
statement coverage above the 90.0% gate that runs in seconds with no
network, no TTY and no git fixtures.
Related
- Where each dependency is used: Packages reference
- The sibling principle for pure logic: Deterministic offline-first design