How do you test a click or argparse CLI?
IntermediateConceptTesting, services & metrics
Answer
For click, use CliRunner, which invokes the command in-process and captures output and exit code:
from click.testing import CliRunner
def test_cli_fails_on_high(aws):
r = CliRunner().invoke(main, ["--region", "us-east-1", "--format", "json"])
assert r.exit_code == 2
assert '"HIGH"' in r.output
For argparse, structure main(argv=None) to accept a list and return an exit code, then call main(["--dry-run"]) directly and use capsys. Assert on exit codes explicitly; they are the contract with CI.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat are pytest fixtures, and what scopes exist?IntermediateWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?Beginner