painless-software / python-cli-test-helpers

Useful helpers for writing tests for your Python CLI program.
https://python-cli-test-helpers.readthedocs.io
GNU General Public License v3.0
27 stars 4 forks source link

Suggest Anthony's solution for testing `argparse` #43

Open bittner opened 1 year ago

bittner commented 1 year ago

At PyCon 23 I was suggested :tv: a video by @asottile who shows how to easily get back the control that argparse takes away from you. Two tricks, which ultimately make it unnecessary to mock sys.argv and use the shell function this project provides.

  1. Pass an argv variable to the argument parser's parse_args() function.
  2. Use Pytest's capsys fixture to evaluate stdout and stderr.

Suggested Changes

bittner commented 1 year ago

For Docopt the identical approach seems to be possible. The docopt() function takes argv as a second argument and reads sys.argv when it is None. Unsurprisingly, this is also supported by Docopt-ng.