How to test that a custom excepthook is installed correctly?(如何测试是否正确安装了自定义的Exepthook?)
本文介绍了如何测试是否正确安装了自定义的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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何测试是否正确安装了自定义的Exepthook?
基础教程推荐
猜你喜欢
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
