python-cli-test-helpers
python-cli-test-helpers copied to clipboard
Suggest Anthony's solution for testing `argparse`
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.
- Pass an
argvvariable to the argument parser'sparse_args()function. - Use Pytest's
capsysfixture to evaluatestdoutandstderr.
Suggested Changes
- [ ] It might be helpful to mention this alternative approach in our documentation.
- [ ] Alternatively, or in addition, the
argparseexample project template could be adjusted to incorporate this idea. - [x] Optionally, investigate if a similar approach is also possible with Docopt.
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.