Sub topic 13
Testing your command-line tool
This chapter assumes you can write and run pytest tests, and that you have built a parser and a main(argv) function as in the earlier chapters. Here you will test a tool without launching a subprocess.
Why main(argv) makes testing easy
parse_args(None) reads sys.argv. If main accepts an optional list, a test can pass its own arguments and call the function directly. No shell, no process, and no changes to global state are needed.
The test in this chapter targets the greet tool from the earlier chapter. It lives in greet.py.
Checking output and exit codes
Two things are worth checking on every command: what it prints and what it returns. The capsys fixture captures everything written to sys.stdout and sys.stderr. Call readouterr() to get both as strings.
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"Compare out exactly. That makes the test fail if extra text leaks into standard output, which would break anyone piping the tool into another program.
Testing invalid input
When argparse rejects input, it prints a usage message to stderr and calls sys.exit(2). That raises SystemExit. Your test must catch it with pytest.raises, then check the 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().errCheck the error text in err, not out. Also check that out is empty if the tool must not print partial results on failure.
Testing stderr messages from your own code
Verbose messages go to stderr, so test them separately from normal output.
def test_verbose_writes_to_stderr(capsys):
assert main(["Ada", "--verbose"]) == 0
captured = capsys.readouterr()
assert captured.out == "Hello, Ada!\n"
assert "Greeting Ada 1 time(s)" in captured.errThis confirms the stream split: results on stdout, diagnostics on stderr.
Running many cases at once
Parametrized tests keep a list of argument sets compact.
@pytest.mark.parametrize("argv", [
["Ada", "--count", "x"],
["--count", "2"],
[],
])
def test_bad_arguments_exit_2(argv):
with pytest.raises(SystemExit) as excinfo:
main(argv)
assert excinfo.value.code == 2The second case omits the required name. The third omits all arguments.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `main()` with no list in a test | argparse reads pytest's own arguments and errors | Always pass an explicit list |
| Forgetting `readouterr()` | Assertions run against nothing | Call it after `main` returns |
| Comparing `out` loosely | Stray prints go unnoticed | Compare the full string |
| Testing `--help` as a normal return | `SystemExit` with code 0 is raised | Wrap it in `pytest.raises` and check `code == 0` |
Exercise
Write a test that confirms main(["--help"]) prints a usage line to stdout and exits with code 0.
Show answer
with pytest.raises(SystemExit) as excinfo: main(["--help"]) is followed by assert excinfo.value.code == 0 and assert "usage:" in capsys.readouterr().out. Help is written to stdout, and argparse exits with 0 because asking for help is not an error.
Exercise
A test calls main(["Ada", "--count", "0"]) and expects exit code 2, but the test fails. Why?
Show answer
argparse accepts 0 as a valid int, so no error is raised and main returns 0. To reject it, add a custom type function that raises ArgumentTypeError for values below 1. Then the test passes.