Python: обрабатывать sys.exit() в документах

Я пытаюсь использовать тесты Python для проверки сообщения об ошибке, которое печатается в функции. Ниже мой код

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

Может кто-нибудь помочь мне, как обрабатывать sys.exit(1) во время проведения doctests?

1 ответ

Использование библиотеки Mock для патча обезьяны sys.exit,

Как я искал, 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)
Другие вопросы по тегам