This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author paul.j3
Recipients atb00ker, paul.j3, xtreak
Date 2020-01-18.01:46:58
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1579312019.2.0.624443405211.issue39283@roundup.psfhosted.org>
In-reply-to
Content
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.
History
Date User Action Args
2020-01-18 01:46:59paul.j3setrecipients: + paul.j3, xtreak, atb00ker
2020-01-18 01:46:59paul.j3setmessageid: <1579312019.2.0.624443405211.issue39283@roundup.psfhosted.org>
2020-01-18 01:46:59paul.j3linkissue39283 messages
2020-01-18 01:46:58paul.j3create