'Flask-login pytest how to test logout

I am building a test suite for a flask app's auth blueprint.

I've successfully built tests for user registering and login in, but I am having some trouble to test my logout route.

This is my logout route in the flask app:

@auth_blueprint.route("/logout", methods=["GET"])
def logout_route():
    if current_user.is_authenticated:
        logout_user()
        
    return redirect(url_for("auth.login_page"))

When the user GETs the /users/logout endpoint, he is first logged out, if he is authenticated and then redirected to a different page.

I am currently utilizing the following fixtures for the test:

import pytest
import os
from decimal import *
import hashlib

from mongoengine import connect
os.environ["CONFIG_TYPE"] = "config.TestingConfig"

from app import create_app, socketio
from app.utilities import get_utc_now_func
from app.models import *

@pytest.fixture(scope='module')
def create_flask_app():
    #drop all records in testDatabase before strting new test module
    db = connect(host=os.environ["MONGODB_SETTINGS_TEST"], alias="testConnect")
    for collection in db["testDatabase"].list_collection_names():
        db["testDatabase"].drop_collection(collection)
    db.close()
    
    # Create a test client using the Flask application configured for testing
    flask_app = create_app()
    return flask_app

@pytest.fixture(scope='function')
def test_client(create_flask_app):
    """
    Establish a test client for use within each test module
    """
    with create_flask_app.test_client() as testing_client:
        with create_flask_app.app_context():
            yield testing_client 

And running the following test:

def test_logout_page_get(create_flask_app, test_client):
    """
    GIVEN a logout_route view function
    WHEN a user submits GET to '/users/logout'
    THEN check that the user is logged out and redirected correctly if logged in
    """
    @create_flask_app.login_manager.request_loader
    def load_user_from_request(request):
        return User.objects(username="test_register_user")[0]
    assert isinstance(current_user, User)

    response = test_client.get('/users/logout', follow_redirects=True)
    assert response.status_code == 200
    assert not isinstance(current_user, User)

The test first logs in a user and asserts that such user is logged in. Then the test calls the logout endpoint and asserts a 200 HTTP response and that no user is logged in anymore.

But I'm receiving the following error:

_________________________________________________________________ test_logout_page_get _________________________________________________________________

create_flask_app = <Flask 'app'>, test_client = <FlaskClient <Flask 'app'>>

    def test_logout_page_get(create_flask_app, test_client):
        """
        GIVEN a logout_route view function
        WHEN a user submits GET to '/users/logout'
        THEN check that the user is logged out and redirected correctly if logged in
        """
        @create_flask_app.login_manager.request_loader
        def load_user_from_request(request):
            return User.objects(username="test_register_user")[0]
>       assert isinstance(current_user, User)
E       assert False
E        +  where False = isinstance(current_user, User)

tests/functional/test_auth.py:116: AssertionError

The current_user object is still referencing the user that I had logged in, meaning that the route didn't execute the logout command.

Any idea why that is happening?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source