watch-this
watch-this

Reputation: 1

What type of error argparse.ArgumentParser raises for missing required args

I need to ensure an error is raised using pytest given the following:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-x', required=True)
parser.parse_args()

which without passing something to -x flag when called, will result in:

usage: my_script.py [-h] -x X
my_script.py: error: the following arguments are required: -x

Which if I intentionally tried to create an ambiguous type error, probably I won't be able to come up with a better one. I need to specify some error type to be checked like the following:

with pytest.raises(SomeError):
    test_condition()

Even wrapping things in try and except blocks won't work, and so far I tried KeyError, ValueError, SystemError, SystemExit, argparse.ArgumentError, KeyError, Exception ... and nothing seems to work.

Upvotes: 2

Views: 1446

Answers (1)

Balaïtous
Balaïtous

Reputation: 896

As default argparse doesn't throw an exception, but exit when an error occur. Since python 3.9, there is an exit_on_error argument, but it only raise exception when type checking fail. It still exit on unknown argument.

A better approach to not alter the behavior of the program, is to check the call to sys.exit:

>>> import argparse, mock
>>> parser = argparse.ArgumentParser()
>>> with mock.patch("sys.exit") as m:
...     parser.parse_args(("bad", "argument"))
...     print("sys.exit call count: %d" % m.call_count)
... 
usage: [-h]
: error: unrecognized arguments: bad argument
Namespace()
sys.exit call count: 1

Upvotes: 3

Related Questions