paul j3 <[email protected]> added the comment:
The issue of testing a script that uses argparse has come up on StackOverFlow a
number of times.
As noted the unittesting framework(s) often use their own parsers (not
necessarily argparse). That means they are looking at the sys.argv
commandline. It is difficult then to provide arguments that apply both to the
framework, and your own script. If you try to your own options, the unittest
parser will complain about unrecognized arguments.
As a first step, your parser should only run when used as a script, not when
imported (by the unittester). In other words, only call `parse_args` in the
'if __name__' block.
If you do need to do unittesting of your parser, there are several
monkey-patching options:
use 'parser.parse_args(argv)' calls, where 'argv' can be None if used as
script, and a custom list when being tested. Some will modify the sys.argv
during testing. The test_argparse.py unittest file tests both ways.
testing parser output may also require patching. Help and errors are sent
to sys.stdout or sys.stderr. test_argparse.py uses an ArgumentParser subclass
that redefines the error() and exit() methods, and redirects stdout/err.
----------
nosy: +paul.j3
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue39283>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com