# RuntimeError: 在应用程序上下文之外工作。

- **ID:** `python/pytest-flask-app-context-missing`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

测试尝试访问 Flask 的 current_app 或其他上下文局部对象，但没有活动的应用程序上下文。这通常发生在测试使用 Flask 全局变量的代码时，不在请求或应用上下文中。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (98% 成功率)
   ```
   def test_something(app):
    with app.app_context():
        # code that uses current_app
        ...
   ```
2. **** (95% 成功率)
   ```
   def test_something(app):
    with app.app_context():
        ...
   ```
3. **** (90% 成功率)
   ```
   def test_request(client):
    response = client.get('/')
    ...
   ```

## 无效尝试

- **** — This enables testing mode but does not create an application context. (90% 失败率)
- **** — The context must be pushed (with app.test_request_context():) to be active. (85% 失败率)
- **** — This still requires an active context; it just returns the object if one exists. (95% 失败率)
