Flask session from session_transaction is not modified by request when testing

Viewed 56

I try to test my little Flask application, in which I want to set a value in session as starting point, then sending request to change that value.

Here's an example code that describe the problem:

app.py:

from flask import Flask, request, session

app = Flask(__name__)
app.secret_key = "yek_terces"

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        session["key"] = "value"
        return "value"
    else:
        session["key"] = request.form.get("key")
        return f"{session['key']}"

test_app.py:

import pytest
from flask import session
from app import app

@pytest.fixture
def client():
    app.config["TESTING"] = True
    return app.test_client()

def test_index(client):
    with client:
        client.get("/")
        assert session["key"] == "value"
        client.post("/", data={"key": "eulav"})
        assert session["key"] == "eulav"

def test_get_after_transaction(client):
    with client.session_transaction() as session:
        session["key"] = "transaction"
    assert session["key"] == "transaction"

    response = client.get("/")
    assert response.data == b"value"
    assert session["key"] == "value" # AssertionError: assert 'transaction' == 'value'

def test_post_after_transaction(client):
    with client.session_transaction() as session:
        session["key"] = "transaction"
    assert session["key"] == "transaction"

    response = client.post("/", data={"key": "eulav"})
    assert response.data == b"eulav"
    assert session["key"] == "eulav" # AssertionError: assert 'transaction' == 'eulav'

In test_index(), setting value in session with request is fine if I don't need a starting value.

However, if I set a value in session using session_transaction() according to Testing Flask Applications and later send a request, value is modified in response but not in session.

What is the correct way to test the session in this case?

0 Answers
Related