Skip to content

Lesson 8 of 9 · 25m

Testing CLI Behavior, Not Just Functions

Test parsing, streams, exit codes, filesystem effects, and subprocess integration — the contract users actually experience.

Unit tests for internal functions are necessary but insufficient for a CLI. Users do not call normalize_row; they type a command, pipe output, mis-set an environment variable, hit Ctrl+C, or run the tool from a directory you did not expect. Test the boundary where those things happen.

click and typer provide command runners

from click.testing import CliRunner
from fleetctl.cli import cli


def test_status_json():
    result = CliRunner().invoke(cli, ["status", "--json"])
    assert result.exit_code == 0
    assert '"summary"' in result.output

CliRunner captures output and exceptions in-process, making it ideal for parser behavior, validation, and common command flows. It is not a perfect terminal — no real TTY, no shell expansion, no signals — so treat it as one layer rather than the whole test strategy.

Assert the contract explicitly

assert result.exit_code == 2
assert result.stdout == ""
assert "invalid value for '--timeout'" in result.stderr

Use temporary directories for filesystem effects

def test_writes_report(tmp_path):
    output = tmp_path / "report.json"
    result = runner.invoke(cli, ["report", "--output", str(output)])
    assert result.exit_code == 0
    data = json.loads(output.read_text())
    assert data["items"] == []

Never write into the repository during tests. Temporary directories make tests parallel-safe and prevent one failed assertion from poisoning the next run.

Some behavior needs a real subprocess

proc = subprocess.run(["python", "-m", "fleetctl", "--version"], text=True, capture_output=True, timeout=10)
assert proc.returncode == 0
assert proc.stdout.startswith("fleetctl ")

This catches packaging mistakes: missing entry points, import-time failures, absent package data. These are precisely the errors in-process tests often miss because the source tree is importable in a way the installed wheel is not.

Test hostile inputs

Empty config, unknown keys, non-UTF8 input, closed pipes, missing files, expired credentials, and slow networks. The point is not paralysis; it is that failures should be intentional, concise, and correctly coded.

Field notes

  • Set environment variables inside tests with monkeypatch.setenv; leaks between tests create order dependence.
  • A tmp_path test that mutates the real home directory is worse than no test because it teaches false confidence.
  • Do not mock the entire filesystem when the real one in a temporary directory is simpler and more honest.
  • Include one end-to-end invocation in CI after building the wheel, not only after installing editable source.

Was this lesson helpful?

Sign in to rate