Disabling @login_required while unit-testing flask with flask-login
This because Flask-Login
caching TESTING
or LOGIN_DISABLED
on init_app
(https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L164).
So if you create application and then set something in config then you config changes will ignored.
Better way use application factory with separated configs for production and tests, it also decrease probability get errors with not cleaned application state in tests.
The easiest way reinit login_manager
:
class TestCase(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.login_manager.init_app(app) self.client = webtest.TestApp(app)
from flask login documentation it's said that :
It can be convenient to globally turn off authentication when unit testing. To enable this, if the application configuration variable LOGIN_DISABLED is set to True, this decorator will be ignored.
if you are using application factory design pattern add this to your testing config :
LOGIN_DISABLED = True
or you can add it while creating the app like this :
class TestCase(unittest.TestCase): def setUp(self): app.config['LOGIN_DISABLED'] = True self.client = webtest.TestApp(app)
Hope this will help the others who will have the same problem
I'm not sure if this will help, but:
in my old flaskr project file, I had the configurations in my "flaskr.py" file, and they looked like this:
# configurationDATABASE = 'flaskr.db'DEBUG = TrueSECRET_KEY = 'development key'USERNAME = 'admin'PASSWORD = 'default'
So maybe you would have
TESTING = True
?