简体   繁体   中英

Testing Flask Sessions with Pytest

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM