如何测试是否正确安装了自定义的Exepthook? [英] How to test that a custom excepthook is installed correctly?

查看:27
本文介绍了如何测试是否正确安装了自定义的Exepthook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序记录未处理的异常。

# app.py
import logging
import sys

logger = logging.getLogger(__name__)

def excepthook(exc_type, exc_value, traceback):
    exc_info = exc_type, exc_value, traceback
    if not issubclass(exc_type, (KeyboardInterrupt, SystemExit)):
        logger.error('Unhandled exception', exc_info=exc_info)
    sys.__excepthook__(*exc_info)

sys.excepthook = excepthook

def potato():
    logger.warning('about to die...')
    errorerrorerror

if __name__ == '__main__':
    potato()

这些测试通过正常:

# test_app.py
import app
import pytest
import sys
from logging import WARNING, ERROR

def test_potato_raises():
    with pytest.raises(NameError):
        app.potato()

def test_excepthook_is_set():
    assert sys.excepthook is app.excepthook

# for caplog plugin: pip install pytest-catchlog
def test_excepthook_logs(caplog):  
    try:
        whatever
    except NameError as err:
        exc_info = type(err), err, err.__traceback__
    app.excepthook(*exc_info)
    assert caplog.record_tuples == [('app', ERROR, 'Unhandled exception')]
    [record] = caplog.records
    assert record.exc_info == exc_info

但我无法测试未处理的异常日志记录:

def test_unhandled_exceptions_logged(caplog):
    try:
        app.potato()
    finally:
        assert caplog.record_tuples == [
            ('app', WARNING, 'about to die...'),
            ('app', ERROR, 'Unhandled exception'),
        ]
        return  # return eats exception

这里出了什么问题?我们如何才能在测试中实际触发app.excepthook

推荐答案

在异常实际传播到整个堆栈并且没有其他代码有机会捕获它之前,它不会调用sys.excepthook。这是在Python为响应异常而关闭之前发生的最后一件事之一。

只要您的测试代码仍在堆栈上,sys.excepthook就不会触发。在sys.excepthook之后实际可以运行的少量代码可能不会很好地与您的测试框架配合使用。例如,atexit处理程序仍然可以运行,但到那时测试已经结束。此外,如果您不这样做,您的测试框架可能会捕获异常本身,因此sys.excepthook无论如何都不会触发。

如果您不想自己调用sys.excepthook,最好的办法可能是启动安装了excepthook的整个子进程,并验证子进程的行为。

from subprocess import Popen, PIPE

def test_app():
    proc = Popen([sys.executable, 'app.py'], stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()
    assert proc.returncode == 1
    assert stdout == b''
    assert stderr.startswith(b'about to die...
Unhandled exception')

这篇关于如何测试是否正确安装了自定义的Exepthook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆