我想使用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
会导致{
这是
test_argparse.py
文件中的ArgumentTypeError
测试(可在开发存储库中找到)ErrorRaisingAgumentParser
是在文件开头定义的子类,它重新定义了parser.error
方法,因此它不会退出,并将错误消息放在stderr
上。那部分有点复杂。在由于我描述了注释的重定向,它不能直接测试
ArgumentTypeError
。相反,它必须测试它的信息。在问题是,如果参数的类型转换器引发异常
ArgumentTypeError
agrparse
exits,则退出意味着引发内置异常SystemExit
。因此,您必须捕获该异常并验证原始异常的类型是否正确:相关问题 更多 >
编程相关推荐