bigywater.tech
Flask · 159

测试 Blueprint

蓝图怎么单独测?端点名与 url_for 有什么规则?蓝图的钩子会不会影响别的路由?同一个蓝图能注册两次吗?这篇用一组真实运行的 pytest 用例把这些行为逐项验证。

9 passed
本篇真实运行的 Blueprint 测试数
shop.items
request.endpoint 与 url_for 里蓝图视图的完整端点名
name=
同一个蓝图注册第二次必须提供的参数

最小应用里的蓝图

实测 · 本机执行输出
  test_route_and_prefix RESULT route 200 {'cfg': 'CNY', 'endpoint': 'shop.items', 'hook': 'ran', 'items': ['a', 'b'], 'self_url': '/shop/items'}
  test_endpoint_name_has_blueprint_prefix RESULT url_for /shop/items /shop/3
  test_hooks_only_for_blueprint RESULT hooks 1 None
  test_blueprint_uses_app_config RESULT cfg CNY
  test_register_with_other_prefix RESULT other-prefix 200 404
  test_register_twice_needs_different_names RESULT twice ValueError: The name 'shop' is already registered for this blueprint. Use 'name=' to provide a unique
  RESULT twice-named 200 200
  test_isolated_app_only_this_blueprint RESULT isolated ['shop'] ['/shop/<int:i>', '/shop/items']
  test_no_registration_means_404 RESULT unregistered 404
  test_hook_effect_visible_through_g RESULT g ran
  ============================== 9 passed in 0.02s ===============================

上一篇:测试异常处理器;下一篇:请求耗时统计(第 160 篇起是性能部分)。

分步演示

测试 Blueprint
本步的对象

    本文用到的工具与边界

    • 本机 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
    • 没有验证:蓝图嵌套(蓝图里注册蓝图)、蓝图的 template_folder 与 static_folder 在测试里的行为、蓝图级的 errorhandler(第 102、158 篇看过)、蓝图的 CLI 命令测试(test_cli_runner)
    京ICP备2026067502号-1京公网安备11010502063487号