首页 > 解决方案 > 让 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按预期工作。

标签: pythonflaskpython-unittestflask-login

解决方案


原来我的问题是由于测试没有使用相同的上下文,所以我的解决方案类似于这里这里描述的内容。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并不重要 - 两者都可以删除。


推荐阅读