Python:在doctests中处理sys.exit()

时间:2015-07-21 23:55:38

标签: python doctest systemexit

我正在尝试使用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

任何人都可以帮助我在运行doctests时如何处理sys.exit(1)吗?

2 个答案:

答案 0 :(得分:0)

Mock库用于monkey patch sys.exit

答案 1 :(得分:0)

正如我所寻找的那样,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)