Flask与Pytest中重定向函数测试失败问题求助
解决Flask重定向函数的Pytest测试问题
问题根源
- 第一个错误是
url_for生成URL时需要Flask应用上下文,你已经通过test_request_context解决了这个问题。 - 第二个错误是因为**
redirect返回的是独立的Response对象实例**——哪怕两个实例的重定向目标、状态码完全一致,Python默认会比较对象内存地址,直接用==判断必然失败。
正确测试方案
不要直接比较Response对象,转而验证它们的核心属性:
- 状态码(
status_code):重定向请求应返回302 - 重定向目标地址(
location):确认指向正确的登录页面
修改后的测试代码
from flask import redirect, url_for def redirect_function(): return redirect(url_for('auth.login')) def redirect_function2(): return redirect(url_for('auth.login')) def test_login_functions(test_app): # test_app为你预先配置好的Flask测试应用实例 with test_app.test_request_context(): resp1 = redirect_function() resp2 = redirect_function2() # 验证状态码一致且符合重定向要求 assert resp1.status_code == resp2.status_code == 302 # 验证重定向的目标URL完全相同 assert resp1.location == resp2.location
进阶写法(适配视图函数场景)
如果你的重定向函数是路由对应的视图函数,用Flask测试客户端发起请求会更贴合实际场景:
def test_login_redirects(test_app): client = test_app.test_client() # 假设两个重定向函数分别对应以下路由 resp1 = client.get('/path-to-redirect-function') resp2 = client.get('/path-to-redirect-function2') assert resp1.status_code == resp2.status_code == 302 assert resp1.location == resp2.location
内容的提问来源于stack exchange,提问作者trewbth
相关产品推荐
相关产品推荐

