Python:控制柄系统出口()博士

2024-04-25 01:28:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用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时,我得到了以下结果:

^{pr2}$

谁能帮我处理一下系统出口(1) 在做医生的时候?在


Tags: importgetmaindefsysmsgerrorval
2条回答

使用Mock库来monkey patchsys.exit。在

正如我所寻找的,医生没有这方面的能力。 我使用此模式捕捉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)

相关问题 更多 >