Testing Flask login and authentication?

The problem is that the test_client.get() call causes a new request context to be pushed, so the one you pushed in your the setUp() method of your test case is not the one that the /user handler sees.

I think the approach shown in the Logging In and Out and Test Adding Messages sections of the documentation is the best approach for testing logins. The idea is to send the login request through the application, like a regular client would. This will take care of registering the logged in user in the user session of the test client.


The problem is different request contexts.

In your normal Flask application, each request creates a new context which will be reused through the whole chain until creating the final response and sending it back to the browser.

When you create and run Flask tests and execute a request (e.g. self.client.post(...)) the context is discarded after receiving the response. Therefore, the current_user is always an AnonymousUser.

To fix this, we have to tell Flask to reuse the same context for the whole test. You can do that by simply wrapping your code with:

with self.client:

You can read more about this topic in the following wonderful article: https://realpython.com/blog/python/python-web-applications-with-flask-part-iii/

Example

Before:

def test_that_something_works():
    response = self.client.post('login', { username: 'James', password: '007' })

    # this will fail, because current_user is an AnonymousUser
    assertEquals(current_user.username, 'James')

After:

def test_that_something_works():
    with self.client:
        response = self.client.post('login', { username: 'James', password: '007' })

        # success
        assertEquals(current_user.username, 'James')