python - 让 Flask-Login 与 unittest 一起工作
问题描述
我知道在测试中默认禁用登录。我试图通过设置app.config['LOGIN_DISABLED']
为 False 让它们重新启动。这似乎不起作用,因为current_user
仍然返回None
,但会在测试文件之外的代码中返回一个用户。
下面是一些相关的代码。我的 Flask 应用程序对象最初是在我的应用程序的 main 中创建的__init__.py
,它是在测试期间导入并重新配置的。
===========
初始化.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app = Flask(__name__)
app.config[u'DEBUG'] = settings.debug
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
===========
测试/base.py
from my_app import app, db
import unittest
class BaseTest(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.config['LOGIN_DISABLED'] = False
#app.login_manager._login_disabled = False #doesn't help either
self.app = app.test_client()
db.create_all()
===========
测试/test_a.py
from flask_login import current_user
from my_app.tests.base import BaseTest
class MyTests(BaseTest):
def test_a(self):
#visit endpoint that calls `login_user(user)`
#printing `current_user` in that endpoint works, but the following line only returns `None`
print current_user
注意:用户一定要在打印语句之前登录。在端点中使用current_user
按预期工作。
解决方案
原来我的问题是由于测试没有使用相同的上下文,所以我的解决方案类似于这里和这里描述的内容。tests/test_a.py
现在看起来像:
from flask_login import current_user
from my_app.tests.base import BaseTest
class MyTests(BaseTest):
def test_a(self):
with self.app:
print current_user
奇怪的是,在此更改app.config['LOGIN_DISABLED'] = False
之后app.login_manager._login_disabled = False
并不重要 - 两者都可以删除。
推荐阅读
- html - 引导卡在 bootstrapemail 中不起作用
- python-3.x - 从生成器创建 numpy 数组,列表列表
- vue.js - nuxt如何生成动态路由
- android-studio - 使用切换按钮打开和关闭 TextToSpeech?
- for-loop - 遍历嵌套字典并将键值为 True 的实例合并到打印语句中
- c++ - 在 C++ 中找到二叉树中的最大高度路径
- django - 您可以通过 django rest 框架在 django 对象的部分更新时触发信号吗?
- laravel - 如何在谷歌云虚拟机上部署 Laravel 项目?
- android - 从 io.flutter.embedding.android.flutterview 截取屏幕截图
- graphql - 使用 GraphQL 是否可以用基于消息的方法(例如 MQ)替换用于订阅的 websocket