我想使用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时表示During handling of the above exception, another exception occurred:,因此测试失败。我做错了什么?
发布于 2018-03-16 15:35:11
问题是,如果参数的类型转换器使用错误代码2引发异常ArgumentTypeError agrparse 出口,则退出意味着提高内置异常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")发布于 2018-03-16 20:57:58
下面是ArgumentTypeError文件中的test_argparse.py测试(可在开发存储库中找到)
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)发布于 2021-04-15 11:30:11
使用pytest,您可以执行以下操作,以检查是否引发了argparse.ArugmentError。此外,您还可以检查错误消息。
with pytest.raises(SystemExit) as e:
main(['--configFile', 'non_existing_config_file.json'])
assert isinstance(e.value.__context__, argparse.ArgumentError)
assert 'expected err msg' in e.value.__context__.messagehttps://stackoverflow.com/questions/49323496
复制相似问题