什么时候该用 test_request_context 而不是 test_client?进入 with 之后哪些钩子执行了?url_for 在测试里为什么有时会报错?这篇逐项验证。
POST /items/5 q=hello ua=unit-test
with 里面,EV = [] | g.pre = None 退出 with 之后,EV = ['teardown_request', 'teardown_appcontext'] 手动调用 app.preprocess_request() 后 EV = ['before_request'] | g.pre = set by before_request | 返回值 None
响应: 200 {'i': 7} | 钩子顺序(退出前): ['before_request', 'after_request']
退出之后: ['before_request', 'after_request', 'teardown_request', 'teardown_appcontext'] 没有任何上下文时 url_for → Working outside of application context.
test_request_context 里 url_for("item", i=3) → /items/3 | _external=True → http://localhost/items/3
base_url='https://shop.example.test:8443' 时 _external → https://shop.example.test:8443/items/3
只有 app_context、没配 SERVER_NAME 时 _external → Unable to build URLs outside an active request without 'SERVER_NAME' configured. Also conf
配了 SERVER_NAME 后 app_context 里 _external → http://shop.example.test/items/3app_context: has_app_context = True | has_request_context = False test_request_context: has_app_context = True | has_request_context = True
request.get_json() → {'k': 'v'}
session 可以读写,session["x"] = 1