如何为未捕获的异常处理程序编写单元测试 [英] How to write a unit test for uncaught exception handler
问题描述
我在下面具有捕获未捕获异常的功能.有什么方法可以编写执行 uncaught_exception_handler()
函数但正常退出测试的单元测试?
I have a function to catch uncaught exceptions, below. Is there any way to write a unit test that will execute the uncaught_exception_handler()
function, but exit the test normally?
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
之外,以便您的测试可以更轻松地访问它.
Instead of testing that your function is called for uncaught exceptions, it's probably best to instead test that the excepthook
is installed, and that the function does the right thing when you call it manually. That gives you pretty good evidence that the excepthook
will behave properly in real usage. You'll want to move your uncaught_exception_handler
outside of init_uncaught_exception_logger
so your tests can access it more easily.
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
模块是实现这一目标的方法那个.
If you want to actually invoke excepthook
through an uncaught exception, then you'll need to launch a subprocess and examine its output. The subprocess
module is the way to go for that.
这篇关于如何为未捕获的异常处理程序编写单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!