Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Flask Sessions with Pytest

Tags:

python

flask

Currently I'm working on a Flask project and need to make some tests.

The test I'm struggling is about Flask Sessions.

I have this view:

@blue_blueprint.route('/dashboard')
"""Invoke dashboard view."""
if 'expires' in session:
    if session['expires'] > time.time():
        pass
    else:
        refresh_token()
        pass
    total_day = revenues_day()
    total_month = revenues_month()
    total_year = revenues_year()
    total_stock_size = stock_size()
    total_stock_value = stock_value()
    mean_cost = total_stock_value/total_stock_size
    return render_template('dashboard.html.j2', total_day=total_day, <br> total_month=total_month, total_year=total_year, total_stock_size=total_stock_size, total_stock_value=total_stock_value, mean_cost=mean_cost)
else:
    return redirect(url_for('blue._authorization'))

And have this test:

def test_dashboard(client):
    with client.session_transaction(subdomain='blue') as session:
        session['expires'] = time.time() + 10000
        response = client.get('/dashboard', subdomain='blue')
        assert response.status_code == 200

My currently conftest.py is:

@pytest.fixture
def app():
    app = create_app('config_testing.py')

    yield app


@pytest.fixture
def client(app):
    return app.test_client(allow_subdomain_redirects=True)


@pytest.fixture
def runner(app):
    return app.test_cli_runner(allow_subdomain_redirects=True)

However, when I execute the test, I'm getting a 302 status code instead of the expected 200 status code.

So my question is how I can pass properly the session value?

OBS: Running normally the application the if statement for session is working properly.

like image 843
Rafael Oliveira Avatar asked Oct 08 '18 19:10

Rafael Oliveira


People also ask

How many sessions are in a Flask?

The series was renewed for a ninth and final season in March 2022. As of June 29, 2022, 171 episodes of The Flash have aired, concluding the eighth season.


1 Answers

I find the solution and I want to share with you the answer.

In the API documentation Test Client says:

When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.

We should put the assert after with statement not in, for this work, so the code should be:

def test_dashboard(client):
    with client.session_transaction(subdomain='blue') as session:
        session['expires'] = time.time() + 10000
    response = client.get('/dashboard', subdomain='blue')
    assert response.status_code == 200

This simple indent solves my problem.

like image 176
Rafael Oliveira Avatar answered Nov 16 '22 02:11

Rafael Oliveira