Argparse单元测试:禁止显示帮助消息 [英] Argparse unit tests: Suppress the help message
问题描述
我正在为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?
推荐答案
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)
要抑制"或测试输出,必须捕获sys.stdout
或sys.stderr
,具体取决于argparse
输出(帮助文本进入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屋!