如何测试自定义 excepthook 是否已正确安装?
How to test that a custom excepthook is installed correctly?
我的应用记录了未处理的异常。
# 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
?
pytest
可以查看异常信息。你可以这样做:
>>> import pytest
>>> def foo():
... raise ValueError('Unhandled Exception')
...
>>> with pytest.raises(ValueError) as exc:
... foo()
...
>>> 'Unhandled Exception' in str(exc)
True
>>> str(exc)
'<stdin>:2: ValueError: Unhandled Exception'
>>>
您实际上可以在一次测试中测试全部内容。无需多个测试功能。
Python 不会调用 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...\nUnhandled exception')
我的应用记录了未处理的异常。
# 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
?
pytest
可以查看异常信息。你可以这样做:
>>> import pytest
>>> def foo():
... raise ValueError('Unhandled Exception')
...
>>> with pytest.raises(ValueError) as exc:
... foo()
...
>>> 'Unhandled Exception' in str(exc)
True
>>> str(exc)
'<stdin>:2: ValueError: Unhandled Exception'
>>>
您实际上可以在一次测试中测试全部内容。无需多个测试功能。
Python 不会调用 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...\nUnhandled exception')