gpt4 book ai didi

python - 检查 argparse.ArgumentTypeError

转载 作者:行者123 更新时间:2023-12-04 18:21:16 24 4
gpt4 key购买 nike

我想用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'])

但是,正在运行 pytestDuring handling of the above exception, another exception occurred:因此测试失败。我究竟做错了什么?

最佳答案

问题是如果参数的类型转换器引发异常 ArgumentTypeError agrparse exits错误代码为 2,退出意味着引发内置异常 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")

关于python - 检查 argparse.ArgumentTypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49323496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com