Search code examples
pythonpytestargparse

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?


Solution

  • 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")