Python:引发 argparse.ArgumentError 后,argparse 引发一般错误

标签 python regex assert argparse

我为需要遵循特定格式的参数定义了自定义正则表达式类型。我使用了另一篇文章 ( regex custom type ) 中的代码,它非常有用。我的问题是我正在编写单元测试,我希望正则表达式失败并尝试断言 argparse.ArgumentError 被引发( assertRaises(argparse.ArgumentError, parser.parse_args(inargs .split())))。问题是 argparse 似乎正在捕捉 ArgumentError 并抛出一个一般错误,阻止我验证失败的原因。我错过了什么吗?

这是回溯:

Error
Traceback (most recent call last):
  File "/Users/markebbert/PyCharmProjects/newproject/unittests.py", line 203, in test_set_operation_parameter
    self.assertRaises(argparse.ArgumentError, parser.parse_args(inargs.split()))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1688, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1727, in parse_known_args
self.error(str(err))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 2347, in error
    self.exit(2, _('%s: error: %s\n') % (self.prog, message))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 2335, in exit
    _sys.exit(status)
SystemExit: 2

这是我定义的自定义类型和解析器代码:

class RegexValidator(object):
    """
    Performs regular expression match on value.
    If match fails an ArgumentError is raised
    """

    def __init__(self, pattern, statement=None):
        self.pattern = re.compile(pattern)
        self.statement = statement
        if not self.statement:
            self.statement = "must match pattern %s" % self.pattern

    def __call__(self, string):
        match = self.pattern.search(string)
        if not match:
            raise argparse.ArgumentError(None, self.statement)
        return string


operatorRV = RegexValidator(
    "^((\w+)=)?[iIuUcC]\[(\w+(\[\w+(,\w+)*\])?)(:\w+(\[\w+(,\w+)*\])?)*\]$",
    "Set operations must conform to...")

parser = argparse.ArgumentParser(
    description='Compare variants across individuals',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

group.add_argument('-s', '--set-operation', dest='operation', nargs='+',
                   type=operatorRV,
                   help="blah.")

这是单元测试:

    # Fail for ending colon
    inargs = "-s out=i[one[id1]:]"
    self.assertRaises(argparse.ArgumentError, parser.parse_args(inargs.split()))

最佳答案

Argparse 是一个命令行解析器,错误总是以调用 argparse.exit() 结束,后者又调用带有错误代码的 sys.exit()。这是设计使然。

对于单元测试,您必须对解析器的 .error().exit() 方法进行猴子修补(也许使用模拟)。 .error() 被调用并显示错误消息并打印用法消息,然后调用 .exit() 并返回退出代码和错误消息。

他们当前的实现:

# ===============
# Exiting methods
# ===============
def exit(self, status=0, message=None):
    if message:
        self._print_message(message, _sys.stderr)
    _sys.exit(status)

def error(self, message):
    """error(message: string)

    Prints a usage message incorporating the message to stderr and
    exits.

    If you override this in a subclass, it should not return -- it
    should either exit or raise an exception.
    """
    self.print_usage(_sys.stderr)
    self.exit(2, _('%s: error: %s\n') % (self.prog, message))

关于Python:引发 argparse.ArgumentError 后,argparse 引发一般错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15691762/

相关文章:

python - 具有 Statsmodel ValueError : zero-size array to reduction operation maximum which has no identity 的多重 OLS 回归

python - 通过opencv Python检测图像中是否存在灰色

python - 向 PyQt5 中的 Thread 函数发送信号导致装饰槽的 TypeError

c++ - 用 gcc 编译 std::regex_iterator

ios - 可折叠部分 : [Assert] Unable to determine new global row index for preReloadFirstVisibleRow (0)

用于搜索哈希值中特定字符串的Python程序(编码帮助)

php - 使用正则表达式从 HTML 文档中的链接中提取 URL

java - 正则表达式捕获组混淆

python - 为什么断言没有大量使用?

Python - 断言页面中不应存在的文本字段