Ans*_*mar 4 python unit-testing argparse
我正在为argparse实现编写测试用例.我打算测试'-h'功能.以下代码执行此操作.但它也输出脚本的用法.有没有办法压制那个?
self.assertRaises(SystemExit, arg_parse_obj.parse_known_args, ['-h'])
Run Code Online (Sandbox Code Playgroud)
另外,我们可以检查抛出的异常号码吗?例如'-h'抛出SystemExit:0,而无效或不足的args抛出SystemExit:2.有没有办法检查数字代码?
Mar*_*ers 15
在测试异常代码时,请self.assertRaises()用作上下文管理器 ; 这使您可以访问引发的异常,让您测试.code属性:
with self.assertRaises(SystemExit) as cm:
arg_parse_obj.parse_known_args(['-h'])
self.assertEqual(cm.exception.code, 0)
Run Code Online (Sandbox Code Playgroud)
要"抑制"或测试输出,您必须捕获sys.stdout或者sys.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
Run Code Online (Sandbox Code Playgroud)
并使用这些:
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')
Run Code Online (Sandbox Code Playgroud)
我在这里嵌套了上下文管理器,但是在Python 2.7和更新版本中你也可以将它们组合成一行; 这有点匆忙超过推荐的79个字符限制.