How do I unit test my script for incorrect command line arguments?
For example,
my_script.py -t
should give an error since -t flag is not present, as shown in the code below:
parser = OptionParser()
parser.add_option("-d",
action="callback",
callback=get_bios_difference,
help="Check difference between two files"
)
(options, args) = parser.parse_args()
if len(sys.argv) == 1: # if only 1 argument, it's the script name
parser.print_help()
exit()
First, you need a unit to test:
Note that we explicitly pass
argstoparse_args, rather than let it assumesys.argvis to be parsed.In production, you can call
parse_options()and it will work as before. For testing, you can callparse_options([])orparse_options(["-t"])or whatever other combination of arguments you want to test.All that said, you should be using
argparseinstead ofoptparse(which has been deprecated for years) in new code.