bigywater.tech
Flask · 158

测试异常处理器

怎么测试 errorhandler?为什么测试里 500 处理器有时不执行?异常什么时候抛进测试、什么时候变成 500?蓝图里的处理器管到哪里?这篇用一组真实运行的 pytest 用例把规则一条条验证。

8 passed
本篇真实运行的异常处理器测试数
pytest.raises
TESTING=True 时接住视图里未处理异常的写法
PROPAGATE_EXCEPTIONS
设成 False 后未处理的异常走 500 处理器的开关

一组真实运行的异常处理器测试

实测 · 本机执行输出
  test_custom_exception_handler RESULT custom 402 {'code': 'card_declined', 'error': 'payment'}
  test_404_handler RESULT 404 404 {'error': 'not found'}
  test_abort_403_no_handler RESULT abort403 403 text/html; charset=utf-8
  test_unhandled_exception_propagates_in_testing RESULT propagate raised RuntimeError in the test
  test_500_handler_runs_when_not_testing RESULT 500handler 500 {'error': 'server error'}
  test_override_propagation_inside_testing RESULT propagate-off 500 {'error': 'server error'}
  test_blueprint_handler_scope RESULT bp-inside 400 {'error': 'bp value error'}
  RESULT bp-outside raised ValueError (blueprint handler does not apply)
  test_handler_error_format_contract RESULT contract ['code', 'error']
  ============================== 8 passed in 0.06s ===============================

上一篇:测试文件上传;下一篇:测试 Blueprint。

第 102 篇讲过统一错误格式的写法,这一篇讲怎么测试它。

分步演示

测试异常处理器
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Python 3.14.7 / Flask 3.1.3 / Werkzeug 3.1.9 / Jinja2 3.1.6 / SQLAlchemy 2.1.1 / gunicorn 26.2.0(都装在自己的虚拟环境里);大多数实验用 Flask 的 test_client(直接调用 WSGI 应用,不经过网络),需要真实 HTTP 时另起 gunicorn 或开发服务器(端口 9600 以上,本机 127.0.0.1);计时用 time.perf_counter,数字每次运行会有小幅抖动。pytest 9.1.1
    • 没有验证:异步视图里的异常、处理器本身抛出异常时的行为、Sentry 等错误上报与处理器的配合、abort 带自定义 description 的 JSON 化、before_request 里抛出的异常走哪个处理器
    京ICP备2026067502号-1京公网安备11010502063487号