检查argparse.ArgumentTypeE

2024-06-25 22:53:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用pytest来检查是否因为错误的参数而引发了argparse.ArgumentTypeError异常:

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'])

但是,运行pytest会导致{},因此测试失败。我做错什么了?在


Tags: importparserpytestosmaindefnotargparse
2条回答

这是test_argparse.py文件中的ArgumentTypeError测试(可在开发存储库中找到)

ErrorRaisingAgumentParser是在文件开头定义的子类,它重新定义了parser.error方法,因此它不会退出,并将错误消息放在stderr上。那部分有点复杂。在

由于我描述了注释的重定向,它不能直接测试ArgumentTypeError。相反,它必须测试它的信息。在

# =======================
# ArgumentTypeError tests
# =======================

class TestArgumentTypeError(TestCase):

    def test_argument_type_error(self):

        def spam(string):
            raise argparse.ArgumentTypeError('spam!')

        parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
        parser.add_argument('x', type=spam)
        with self.assertRaises(ArgumentParserError) as cm:
            parser.parse_args(['XXX'])
        self.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n',
                         cm.exception.stderr)

问题是,如果参数的类型转换器引发异常ArgumentTypeErroragrparseexits,则退出意味着引发内置异常SystemExit。因此,您必须捕获该异常并验证原始异常的类型是否正确:

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

相关问题 更多 >