``` from flask import Flask,render_template,request,redirect,url_for,session import unittest app=Flask(__name__) #主页 @app.route('/') def index(): if "username" in session: return redirect(url_for("success",name = session["username"])) return redirect(url_for("login")) #登录成功页面 @app.route('/success/<name>') def success(name): return f"{name} login success!" @app.route('/login',methods = ["GET","POST"]) def login(): if request.method == "POST": session["username"] = request.form.get("username") return redirect(url_for("success",name = session["username"])) return render_template('login1.html') if __name__ == '__main__': app.run(debug=True)```E:\202312100217-Ljw\flask_web\envs\python.exe "D:/Program Files/JetBrains/PyCharm 2023.1/plugins/python/helpers/pycharm/_jb_pytest_runner.py" --target get_post.py::test Testing started at 8:29 ... D:/Program Files/JetBrains/PyCharm 2023.1/plugins/python/helpers/pycharm/_jb_pytest_runner.py:8: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html from pkg_resources import iter_entry_points Launching pytest with arguments get_post.py::test --no-header --no-summary -q in E:\202312100217-Ljw\路由 ============================= test session starts ============================= collecting ... collected 1 item get_post.py::test FAILED [100%] get_post.py:3 (test) @app.route('/',methods = ['GET','POST']) def test(): > if request.method == 'GET': get_post.py:6: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ..\flask_web\envs\lib\site-packages\werkzeug\local.py:432: in __get__ obj = instance._get_current_object() ..\flask_web\envs\lib\site-packages\werkzeug\local.py:554: in _get_current_object return self.__local() # type: ignore _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ name = 'request' def _lookup_req_object(name): top = _request_ctx_stack.top if top is None: > raise RuntimeError(_request_ctx_err_msg) E RuntimeError: Working outside of request context. E E This typically means that you attempted to use functionality that needed E an active HTTP request. Consult the documentation on testing for E information about how to avoid this problem. ..\flask_web\envs\lib\site-packages\flask\globals.py:33: RuntimeError ============================== 1 failed in 0.24s ============================== Process finished with exit code 1
时间: 2025-06-05 22:13:00 浏览: 14
从错误信息来看,`RuntimeError: Working outside of request context.` 表示你在测试代码中尝试访问 `request` 对象,但在当前环境中并没有激活的请求上下文。
### 原因分析
Flask 的 `request` 和其他全局变量(如 `session`)依赖于请求上下文的存在。当你直接运行单元测试时,并未模拟实际的 HTTP 请求环境,因此会出现上述错误。
### 解决方案
为了正确地对 Flask 应用程序进行单元测试,你需要创建一个虚拟的应用上下文并发送适当的请求数据到视图函数中。以下是修正后的代码:
#### 修改后的测试代码:
```python
import unittest
from my_flask_app import app # 确保导入的是你的主应用模块
class TestFlaskApp(unittest.TestCase):
def setUp(self):
"""初始化测试客户端"""
self.app = app.test_client()
def tearDown(self):
pass # 如果需要清理资源可以在这里添加逻辑
def test_index_not_logged_in(self):
"""测试用户未登录时的情况"""
response = self.app.get('/') # 模拟 GET 请求
self.assertEqual(response.status_code, 302) # 验证是否重定向
self.assertIn(b'/login', response.data)
def test_login_and_redirect(self):
"""测试登录流程及跳转情况"""
with app.test_client() as client:
with client.session_transaction() as sess:
sess['username'] = 'test_user' # 手动设置会话值
response = client.get('/') # 用户已登录,应该跳转至 success 页面
self.assertEqual(response.status_code, 302)
self.assertIn(b'/success/test_user', response.data)
if __name__ == '__main__':
unittest.main()
```
---
### 关键点说明:
1. **Test Client**
使用 `app.test_client()` 创建了一个测试客户端,用于向应用程序发出虚拟的 HTTP 请求。
2. **Session Simulation**
利用了 `client.session_transaction()` 来手动操作 session 数据,在某些场景下非常有用。
3. **Assertion Methods**
单元测试的核心部分在于验证返回的状态码 (`response.status_code`)、响应内容 (`response.data`) 是否符合预期。
---
阅读全文
相关推荐


















