Interview Prep/Python for DevOps/Testing, services & metrics

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.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics