Python › Command-Line Interfaces (argparse)

How would you write integration tests for an argparse-based CLI tool using pytest, verifying both successful parsing and expected error behavior?

Advanced

Answer

Call your parser's parse_args() directly with an explicit list of strings (bypassing sys.argv entirely) to test parsing logic in isolation; to test error behavior (which normally calls sys.exit()), wrap the call in pytest.raises(SystemExit) and optionally capture stderr with the 'capsys' fixture to assert on the error message.
import pytest

def test_valid_args():
    args = parser.parse_args(["--count", "5"])
    assert args.count == 5

def test_invalid_choice(capsys):
    with pytest.raises(SystemExit):
        parser.parse_args(["--log-level", "invalid"])
    captured = capsys.readouterr()
    assert "invalid choice" in captured.err
Real-world example Writing a reliable pytest suite verifying a CLI tool's argument parsing behaves correctly for both valid and invalid inputs.

Common follow-ups: Why does argparse call sys.exit() on a parsing error instead of raising a normal, catchable exception?