title: Testing Flask login and authentication?
body: <p>I'm developing a Flask application and using Flask-security for user authentication (which in turn uses Flask-login underneath).</p>
  
  <p>I have a route which requires authentication, <code>/user</code>. I'm trying to write a unit test which tests that, for an authenticated user, this returns the appropriate response.</p>
  
  <p>In my unittest I'm creating a user and logging as that user like so:</p>
  
  <pre><code>from unittest import TestCase
  from app import app, db
  from models import User
  from flask_security.utils import login_user
  
  class UserTest(TestCase):
     def setUp(self):
         self.app = app
         self.client = self.app.test_client()
         self._ctx = self.app.test_request_context()
         self._ctx.push()
  
         db.create_all()
  
     def tearDown(self):
         if self._ctx is not None:
             self._ctx.pop()
  
         db.session.remove()
         db.drop_all()
  
     def test_user_authentication():
         # (the test case is within a test request context)
         user = User(active=True)
         db.session.add(user)
         db.session.commit()
         login_user(user)
  
         # current_user here is the user
         print(current_user)
  
         # current_user within this request is an anonymous user
         r = test_client.get('/user')
  </code></pre>
  
  <p>Within the test <code>current_user</code> returns the correct user. However, the requested view always returns an <code>AnonymousUser</code> as the <code>current_user</code>.</p>
  
  <p>The <code>/user</code> route is defined as:</p>
  
  <pre><code>class CurrentUser(Resource):
      def get(self):
          return current_user  # returns an AnonymousUser
  </code></pre>
  
  <p>I'm fairly certain I'm just not fully understanding how testing Flask request contexts work. I've read this Flask <a href="http://flask.pocoo.org/docs/reqcontext/" rel="noreferrer">Request Context documentation</a> a bunch but am still not understanding how to approach this particular unit test.</p>