2015-07-21 44 views
1

我正在尝试使用python doctests来测试打印在函数中的错误消息。下面是我的代码Python:在文档测试中处理sys.exit()

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() 

当我运行文档测试,我得到以下:

********************************************************************** 
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)在运行文档测试?

+0

代替'sys.exit',你可以做'raise KeyboardInterrupt'。 – refi64

+0

感谢您的回复。 – allDoubts

回答

0

使用Mock库到monkey patchsys.exit

+0

谢谢,但有没有办法做到这一点,而不使用外部库? – allDoubts