Argparse 单元测试:禁止显示帮助消息 [英] Argparse unit tests: Suppress the help message

查看:29
本文介绍了Argparse 单元测试:禁止显示帮助消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 argparse 实现编写测试用例.我打算测试-h"功能.下面的代码做到了.但它也输出脚本的用法.有没有办法抑制它?

I'm writing test cases for argparse implementation. I intend to test '-h' feature. The following code does it. But it also outputs the usage for the script. Is there a way to suppress that?

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

另外,我们可以检查抛出的异常号吗?例如,'-h' 会抛出 SystemExit: 0,而无效或不足的 args 会抛出 SystemExit: 2.有没有办法检查数字代码?

Also, can we check for the exception number thrown? For example '-h' throws SystemExit: 0, while invalid or insufficient args throw SystemExit: 2. Is there a way to check the numeric code?

推荐答案

测试异常代码时,使用 self.assertRaises() 作为上下文管理器;这使您可以访问引发的异常,让您测试 .code 属性:

When testing for exception codes, use self.assertRaises() as a context manager; this gives you access to the raised exception, letting you test the .code attribute:

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

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

要抑制"或测试输出,您必须根据 argparsesys.stderr 捕获sys.stdoutsys.stderrcode> 输出(帮助文本转到 stdout).您可以为此使用上下文管理器:

To 'suppress' or test the output, you'll have to capture either sys.stdout or sys.stderr, depending on the argparse output (help text goes to stdout). You could use a context manager for that:

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 个字符限制.

I nested the context managers here, but in Python 2.7 and newer you can also combine them into one line; this tends to get beyond the recommended 79 character limit in a hurry though.

这篇关于Argparse 单元测试:禁止显示帮助消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆