我有一个函数可以捕获uncaught例外情况,如下。有没有办法编写一个单元测试来执行uncaught_exception_handler()
功能正常,但测试正常退出?
import logging
def config_logger():
# logger setup here
def init_uncaught_exception_logger(logger):
'''Setup an exception handler to log uncaught exceptions.
This is typically called once per main executable.
This function only exists to provide a logger context to the nested function.
Args:
logger (Logger): The logger object to log uncaught exceptions with.
'''
def uncaught_exception_handler(*exc_args):
'''Log uncaught exceptions with logger.
Args:
exc_args: exception type, value, and traceback
'''
print("Triggered uncaught_exception_handler")
logger.error("uncaught: {}: {}\n{}".format(*exc_args))
sys.excepthook = uncaught_exception_handler
if __name__ == '__main__':
LOGGER = config_logger()
init_uncaught_exception_logger(LOGGER)
raise Exception("This is an intentional uncaught exception")
最好不要测试您的函数是否因未捕获的异常而被调用,而是测试excepthook
已安装,并且当您手动调用该函数时,该函数会执行正确的操作。这给了你很好的证据excepthook
在实际使用中会表现正常。你会想要移动你的uncaught_exception_handler
在外面init_uncaught_exception_logger
这样您的测试就可以更轻松地访问它。
assert sys.excepthook is uncaught_exception_handler
with your_preferred_output_capture_mechanism:
try:
1/0
except ZeroDivisionError:
uncaught_exception_handler(*sys.exc_info())
assert_something_about_captured_output()
如果你想实际调用excepthook
通过未捕获的异常,那么您需要启动一个子进程并检查其输出。这subprocess module https://docs.python.org/3/library/subprocess.html是实现这一目标的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)