2

I know logins are disabled by default in testing. I'm trying to get them back on, by setting app.config['LOGIN_DISABLED'] to False. This doesn't seem to be working, since current_user still returns None, but will return a User in code outside a test file.

Some relevant bits of code are below. My Flask app object is originally created in my app's main __init__.py, which is imported and re-configured during testing.

===========

init.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)

===========

tests/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()

===========

tests/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

Note: The User should definitely be logged in before the print statement. Using current_user in the endpoint works as expected.

thekthuser
  • 706
  • 1
  • 12
  • 28

1 Answers1

3

Turns out my problem was due to testing not using the same context, so my solution is similar to what is described here and here. tests/test_a.py now looks like:

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

Strangely, app.config['LOGIN_DISABLED'] = False and app.login_manager._login_disabled = False don't matter after this change - both can be removed.

thekthuser
  • 706
  • 1
  • 12
  • 28