python - Argparse 单元测试 : Suppress the help message

标签 python unit-testing argparse

我正在为 argparse 实现编写测试用例。我打算测试“-h”功能。下面的代码就是这样做的。但它也会输出脚本的用法。有没有办法抑制它?

self.assertRaises(SystemExit, arg_parse_obj.parse_known_args, ['-h'])

此外,我们可以检查抛出的异常编号吗?例如 '-h' 抛出 SystemExit: 0,而无效或不充分的参数抛出 SystemExit: 2。有没有办法检查数字代码?

最佳答案

测试异常代码时,使用 self.assertRaises() as a context manager ;这使您可以访问引发的异常,让您测试 .code 属性:

with self.assertRaises(SystemExit) as cm:
    arg_parse_obj.parse_known_args(['-h'])

self.assertEqual(cm.exception.code, 0)

要“抑制”或测试输出,您必须捕获 sys.stdoutsys.stderr,具体取决于 argparse 输出(帮助文本转到 stdout)。您可以为此使用上下文管理器:

from contextlib import contextmanager
from StringIO import StringIO

@contextmanager
def capture_sys_output():
    capture_out, capture_err = StringIO(), StringIO()
    current_out, current_err = sys.stdout, sys.stderr
    try:
        sys.stdout, sys.stderr = capture_out, capture_err
        yield capture_out, capture_err
    finally:
        sys.stdout, sys.stderr = current_out, current_err

并将它们用作:

with self.assertRaises(SystemExit) as cm:
    with capture_sys_output() as (stdout, stderr):
        arg_parse_obj.parse_known_args(['-h'])

self.assertEqual(cm.exception.code, 0)

self.assertEqual(stderr.getvalue(), '')
self.assertEqual(stdout.getvalue(), 'Some help value printed')

我在这里嵌套了上下文管理器,但在 Python 2.7 和更新版本中,您也可以将它们组合成一行;不过,这往往会很快超出建议的 79 个字符限制。

关于python - Argparse 单元测试 : Suppress the help message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651705/

相关文章:

python - 将多个 QSlider 连接到一个插槽

python - 如何在 Keras 中实现加权均方误差函数

unit-testing - Go 单元测试中的自定义命令行标志

ruby-on-rails - 如何防止加载 RSpec 助手

python:停止导入的模块解析命令行参数

python - ArgumentParser 结语和描述格式与 ArgumentDefaultsHelpFormatter 结合使用

python - 从亚马逊库存中提取产品/价格/类别/规范

python - 将字典列表从一种类型映射到另一种类型

c# - 我怎么 mock 这个?

Python argparse 检查标志是否存在,同时也允许参数