[英]Python: handle sys.exit() in doctests
我正在尝试使用python doctests来测试正在函数中打印的错误消息。 下面是我的代码
import sys
def get_values(vals=[]):
"""
Should split key:val and give values
>>> get_values(["abc"])
Error: could not get the values
"""
values = []
for val in vals:
try:
kv = val.split(':')
k = kv[0]
v = kv[1]
values.append(v)
except Exception:
print_msg("Error: could not get the values")
return values
def print_msg(msg):
print msg
sys.exit(1)
def main():
import doctest
try:
doctest.testmod()
except doctest.DocTestFailure, failure:
print 'DocTestFailure:'
sys.exit(1)
print "doctests complete"
if __name__ == "__main__":
main()
当我运行doctest时,得到以下信息:
**********************************************************************
File "abc.py", line 7, in __main__.get_values
Failed example:
get_values(["abc"])
Exception raised:
Traceback (most recent call last):
File "/depot/python/lib/python2.7/doctest.py", line 1254, in __run
compileflags, 1) in test.globs
File "<doctest __main__.get_values[0]>", line 1, in <module>
get_values(["abc"])
File "abc.py", line 18, in get_values
print_msg("Error: could not get the values")
File "abc.py", line 23, in print_msg
sys.exit(1)
SystemExit: 1
**********************************************************************
1 items had failures:
1 of 1 in __main__.get_values
***Test Failed*** 1 failures.
doctests complete
谁能在运行doctest时帮助我如何处理sys.exit(1)?
正如我所寻找的那样,doctest对此毫无帮助。 我使用这种模式来捕获SystemExit(以及其他异常)以及stdout消息:
>>> def function_with_exception():
... print >>sys.stdout, 'something into stdout'
... print >>sys.stderr, 'something into stderr'
... sys.exit(1)
... # raise Exception('xxx')
>>> def test_function_with_exception(**kwargs):
... try:
... function_with_exception(**kwargs)
... except BaseException as e:
... print '{0.__class__.__name__}({0})'.format(e)
>>> test_function_with_exception()
something into stdout
SystemExit(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.