Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check argparse.ArgumentTypeError

I want to use pytest to check if the argparse.ArgumentTypeError exception is raised for an incorrect argument:

import argparse
import os
import pytest


def main(argsIn):

    def configFile_validation(configFile):
        if not os.path.exists(configFile):
            msg = 'Configuration file "{}" not found!'.format(configFile)
            raise argparse.ArgumentTypeError(msg)
        return configFile

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--configFile', help='Path to configuration file', dest='configFile', required=True, type=configFile_validation)
    args = parser.parse_args(argsIn)


def test_non_existing_config_file():
    with pytest.raises(argparse.ArgumentTypeError):
        main(['--configFile', 'non_existing_config_file.json'])

However, running pytest says During handling of the above exception, another exception occurred: and consequently the test fails. What am I doing wrong?

like image 851
pipppoo Avatar asked Mar 16 '18 14:03

pipppoo


People also ask

What does parse_args return?

parse_args() returns two values: options, an object containing values for all of your options— e.g. if "--file" takes a single string argument, then options. file will be the filename supplied by the user, or None if the user did not supply that option.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.


1 Answers

The problem is that if argument's type converter raises exception ArgumentTypeError agrparse exits with error code 2, and exiting means raising builtin exception SystemExit. So you have to catch that exception and verify that the original exception is of a proper type:

def test_non_existing_config_file():
    try:
        main(['--configFile', 'non_existing_config_file.json'])
    except SystemExit as e:
        assert isinstance(e.__context__, argparse.ArgumentError)
    else:
        raise ValueError("Exception not raised")
like image 108
phd Avatar answered Sep 28 '22 01:09

phd