Sub topic 13
Testing your command-line tool
This chapter assumes you can write an argparse parser, that you structure programs around a main(argv) function that returns an exit code, and that you have used pytest at a basic level (test functions, assert, fixtures). It uses the greet tool from the earlier chapters.
Why the main(argv) pattern makes testing easy
A command-line program reads three things from its environment: the argument list, the standard streams, and the process state. It reports results through two other channels: output on stdout and stderr, and an exit code. To test it, you need to control the inputs and observe the outputs.
Calling the program through a subprocess works, but it is slow and hard to debug. A better approach is to call main directly with an explicit list. This works because parse_args(argv) uses the list you pass. It falls back to sys.argv[1:] only when argv is None.
Here is the tool under test. Save it as greet.py.
import argparse
import sys
def build_parser():
parser = argparse.ArgumentParser(prog="greet", description="Print a greeting.")
parser.add_argument("name", help="who to greet")
parser.add_argument("-c", "--count", type=int, default=1,
help="number of times to greet (default: %(default)s)")
parser.add_argument("-v", "--verbose", action="store_true",
help="print extra information to stderr")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
if args.verbose:
print(f"Greeting {args.name} {args.count} time(s)", file=sys.stderr)
for _ in range(args.count):
print(f"Hello, {args.name}!")
return 0
if __name__ == "__main__":
raise SystemExit(main())The diagram shows what a test controls and what it observes.
Testing the success path
The capsys fixture captures anything written to sys.stdout and sys.stderr during a test. Calling capsys.readouterr() returns an object with out and err attributes. It also clears the buffers, so a second call returns only what was written since the first.
import pytest
from greet import main
def test_greets_twice(capsys):
assert main(["Ada", "--count", "2"]) == 0
assert capsys.readouterr().out == "Hello, Ada!\nHello, Ada!\n"The test checks two things: the return value (the exit code) and the exact text on stdout. Comparing the whole string catches stray output, such as debug prints.
Test the stream separation too. The verbose message belongs on stderr, so a script that pipes stdout into another program receives only the greetings.
def test_verbose_goes_to_stderr(capsys):
assert main(["Ada", "-v"]) == 0
captured = capsys.readouterr()
assert captured.out == "Hello, Ada!\n"
assert captured.err == "Greeting Ada 1 time(s)\n"Testing parser errors
When argparse rejects input, it prints a usage message and an error to stderr, then calls sys.exit(2). That raises SystemExit, which pytest.raises can catch. The exit code is in the exception's code attribute.
def test_invalid_count_exits_with_2(capsys):
with pytest.raises(SystemExit) as excinfo:
main(["Ada", "--count", "many"])
assert excinfo.value.code == 2
assert "invalid int value" in capsys.readouterr().errAssert on a stable fragment of the message, not the full text. The wording of built-in argparse messages can change between Python versions. Messages from your own ArgumentTypeError are under your control, so you can match those more strictly.
Missing required arguments take the same route:
def test_missing_name_exits_with_2(capsys):
with pytest.raises(SystemExit) as excinfo:
main([])
assert excinfo.value.code == 2
assert "usage: greet" in capsys.readouterr().errThe --help and --version actions exit with code 0 after printing to stdout. You can test those the same way and check that code is 0.
def test_help_exits_with_0(capsys):
with pytest.raises(SystemExit) as excinfo:
main(["--help"])
assert excinfo.value.code == 0
assert "Print a greeting." in capsys.readouterr().outParametrizing similar cases
Many parser tests differ only in their input and expected result. pytest.mark.parametrize keeps them compact.
@pytest.mark.parametrize("argv, expected", [
(["Ada"], "Hello, Ada!\n"),
(["Ada", "-c", "1"], "Hello, Ada!\n"),
(["Ada", "-c", "0"], ""),
(["Grace", "--count", "2"], "Hello, Grace!\nHello, Grace!\n"),
])
def test_output(argv, expected, capsys):
assert main(argv) == 0
assert capsys.readouterr().out == expected
@pytest.mark.parametrize("argv", [
["Ada", "--count"],
["Ada", "--count", "1.5"],
["Ada", "--unknown"],
[],
])
def test_rejected_input(argv):
with pytest.raises(SystemExit) as excinfo:
main(argv)
assert excinfo.value.code == 2Each tuple becomes its own test case, so a failure names the exact input that broke.
Testing the parser separately
Because build_parser() returns the parser, you can test parsing without running any program logic. This is useful when main has side effects such as writing files or making network calls.
from greet import build_parser
def test_defaults():
args = build_parser().parse_args(["Ada"])
assert args.name == "Ada"
assert args.count == 1
assert args.verbose is FalseCompare this with testing through main. Parser tests are fast and precise, and they show which option produced which value. main tests prove that the parsed values reach the logic. A tool usually needs both, with most of the detail in the parser tests.
Keeping logic out of main
The easiest code to test takes plain values and returns plain values. If main grows past parsing, dispatching and error handling, move the work into functions.
def greeting(name, count):
return [f"Hello, {name}!" for _ in range(count)]You can then test greeting("Ada", 2) with no capsys and no SystemExit. The main tests shrink to a few that confirm the wiring.
Testing exit codes you return
Errors that argparse cannot detect, such as a missing file, belong in main. Catch the exception, print a message to stderr, and return a nonzero code. Return the code instead of calling sys.exit inside helper functions, and tests can read it with a plain assert.
import sys
def read_lines(path):
with open(path) as handle:
return handle.read().splitlines()
def run(argv=None):
parser = __import__("argparse").ArgumentParser(prog="count")
parser.add_argument("path")
args = parser.parse_args(argv)
try:
lines = read_lines(args.path)
except FileNotFoundError:
print(f"count: no such file: {args.path}", file=sys.stderr)
return 1
print(len(lines))
return 0The matching tests use the tmp_path fixture, which gives each test its own temporary directory:
def test_counts_lines(tmp_path, capsys):
path = tmp_path / "data.txt"
path.write_text("a\nb\nc\n")
assert run([str(path)]) == 0
assert capsys.readouterr().out == "3\n"
def test_missing_file_returns_1(tmp_path, capsys):
assert run([str(tmp_path / "absent.txt")]) == 1
assert "no such file" in capsys.readouterr().errNeither test needs pytest.raises, because run returns the code instead of exiting.
Testing subcommands
With subcommands, test each one through the same main. The todo tool from the earlier chapter works like this:
from todo import main
def test_add(capsys):
assert main(["add", "buy milk"]) == 0
assert capsys.readouterr().out == "adding buy milk\n"
def test_list_all(capsys):
assert main(["list", "--all"]) == 0
assert "all" in capsys.readouterr().out
def test_no_subcommand_is_an_error():
with pytest.raises(SystemExit) as excinfo:
main([])
assert excinfo.value.code == 2The last test passes only because the subparsers were created with required=True. Without it, args.func would not exist and main would fail with an AttributeError. A test like this protects that setting.
Environment, input and the filesystem
Some tools read environment variables or standard input. Pytest provides fixtures for both.
monkeypatch.setenv("NAME", "value")sets an environment variable for one test and restores it afterward.monkeypatch.setattr("sys.stdin", io.StringIO("text"))replaces standard input with a string.tmp_pathandmonkeypatch.chdir(tmp_path)isolate file work and relative paths.
import io
def test_reads_stdin(monkeypatch, capsys):
monkeypatch.setattr("sys.stdin", io.StringIO("one\ntwo\n"))
lines = sys.stdin.read().splitlines()
assert lines == ["one", "two"]Use monkeypatch instead of assigning to os.environ or sys.stdin directly. It undoes the change even when the test fails, so one test cannot leak state into the next.
An end-to-end check with subprocess
Calling main directly does not test the installed command or the if __name__ == "__main__" block. One or two slow tests can cover that. Run the module with the same interpreter that runs the tests:
import subprocess
import sys
def test_runs_as_script():
result = subprocess.run(
[sys.executable, "greet.py", "Ada"],
capture_output=True, text=True, check=False,
)
assert result.returncode == 0
assert result.stdout == "Hello, Ada!\n"Here result.returncode is the real process exit status, so this is the only test style that confirms what a shell sees. Keep these tests few. They start a new interpreter each time, and the path to greet.py depends on the directory where pytest runs.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `parse_args()` with no list inside a test | Reads pytest's own arguments and fails with confusing errors | Always pass a list to `main` |
| Forgetting `pytest.raises(SystemExit)` | The test errors out when `argparse` exits | Wrap calls that should fail |
| Asserting the full text of a built-in error | Breaks on a Python upgrade | Match a short stable fragment |
| Calling `sys.exit` deep in helpers | Tests must catch `SystemExit` everywhere | Return codes from `main` |
| Reading `capsys` twice and expecting the same text | The second read is empty | Store the result of one `readouterr()` call |
Summary of the approach
- Make
main(argv=None)return an integer. - Test the success path with
capsysand an equality check on the output. - Test every rejected input with
pytest.raises(SystemExit)andcode == 2. - Parametrize inputs that differ only in value.
- Move real work into plain functions and test those directly.
- Add one subprocess test for the script entry point.
Exercise
A test calls main(["Ada", "--count", "many"]) and the test itself crashes with SystemExit instead of passing. What is happening, and how do you write the test so it checks the failure?
Show answer
argparse fails to convert "many" to int, prints an error to stderr and calls sys.exit(2), which raises SystemExit and ends the test. Wrap the call in with pytest.raises(SystemExit) as excinfo:, then assert excinfo.value.code == 2 and check capsys.readouterr().err for "invalid int value".
Exercise
Write a test for greet that confirms --verbose output appears on stderr and not on stdout.
Show answer
def testverbosestream(capsys): assert main(["Ada", "--verbose"]) == 0 captured = capsys.readouterr() assert "Greeting Ada" in captured.err assert "Greeting" not in captured.out