Skip to content

Lesson 6 of 9 · 28m

Testing CLIs: Unit, Golden, and End-to-End

Test argument parsing, filesystem effects, output bytes, exit codes, and failure paths using assert_cmd, predicates, tempdirs, and golden files.

CLI testing fails in a familiar way: the core logic has unit tests, but the actual binary is untested. Then a release changes help output, breaks exit codes, writes one directory higher than intended, and every user's wrapper script discovers it before you do. A professional CLI test strategy treats the process boundary as part of the product.

Separate logic from process plumbing

Keep parsing, filesystem access, network calls, and time behind narrow boundaries. Pure transformations can use ordinary unit tests:

fn render_lockfile_name(project: &str, version: &str) -> String {
    format!("{project}-{version}.lock.json")
}

#[test]
fn lockfile_name_is_stable() {
    assert_eq!(render_lockfile_name("deployctl", "1.4.0"), "deployctl-1.4.0.lock.json");
}

Do not make every test spawn the binary. Process tests are slower and noisier, but they prove behavior users actually observe.

Use assert_cmd for black-box behavior

use assert_cmd::Command;
use predicates::prelude::*;

#[test]
fn missing_config_is_a_usage_error() {
    Command::cargo_bin("deployctl").unwrap()
        .args(["publish", "--config", "missing.toml"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("failed to read config"));
}

Test stdout and stderr separately. Test exact output where stability matters; test predicates where exact wording is intentionally free to evolve.

Golden files catch accidental interface drift

Help output, JSON schemas, generated shell completions, manpages, and example config files are ideal golden artifacts. Store them in the repository and compare deterministic bytes. Regeneration must be an explicit developer action, not automatic test mutation.

cargo run -- --help > tests/golden/help.txt
cargo test --test golden

Golden tests are not a substitute for semantic tests. They answer a narrower question: did the user-visible interface change?

Control the filesystem with tempfile

Never run mutation tests in the repository or a shared home directory:

let dir = tempfile::tempdir().unwrap();
let artifact = dir.path().join("release.tar.gz");
std::fs::write(&artifact, b"fixture").unwrap();

Override every environment variable and configuration path that could make the host environment leak into the test. Unset variables that alter behavior, especially color, editor, proxy, and config-home settings.

Failure tests are the point

Anybody can test the happy path. Test missing files, malformed JSON, closed stdout, interrupted network operations, invalid permissions, partial writes, stale locks, and disk-full behavior where practical. A fake server that can return 401, 409, 429, malformed JSON, and truncated bodies is worth more than another ten parsing tests.

Test installation artifacts, not just cargo check

Before release, unpack the actual tarball into a clean directory or container and invoke the binary there. Validate linked libraries with ldd where relevant, run --help, execute a smoke command, and compare checksums. The artifact is the product.

Field notes

  • Snapshot tests are useful only when the review workflow makes diffs visible; otherwise developers rubber-stamp corruption.
  • Parallel tests can collide on fixed ports, fixed paths, or global environment mutations.
  • Do not depend on the user's shell unless shell integration itself is under test.
  • Flaky network tests are usually untested retry and timeout logic wearing a disguise.
  • Keep one fast suite for development and a slower artifact suite for release.

Was this lesson helpful?

Sign in to rate