python-cli-test-helpers icon indicating copy to clipboard operation
python-cli-test-helpers copied to clipboard

Suggest Anthony's solution for testing `argparse`

Open bittner opened this issue 2 years ago • 1 comments

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

  • [ ] It might be helpful to mention this alternative approach in our documentation.
  • [ ] Alternatively, or in addition, the argparse example project template could be adjusted to incorporate this idea.
  • [x] Optionally, investigate if a similar approach is also possible with Docopt.

bittner avatar May 29 '23 15:05 bittner

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.

bittner avatar May 29 '23 15:05 bittner