-
-
Notifications
You must be signed in to change notification settings - Fork 16.5k
Closed
Milestone
Description
Hello team.
During writing tests, I noticed a strange session behavior.
I want to verify that after a redirect, the target location sets valid session properties, and it seems like in tests, the session properties when following redirects are not saved/exposed to the test environment.
Here's an example:
import pytest
from flask import Flask, redirect, session
@pytest.fixture
def app():
app = Flask(__name__)
app.debug = True
app.secret_key = 'test_secret' # noqa: S105 – fake secret key for testing purposes
@app.get('/redirect')
def do_redirect():
print("Redirecting to target endpoint", flush=True)
session["redirected"] = "true"
return redirect('/target', 302)
@app.get('/target')
def target():
print("Target endpoint reached", flush=True)
session['foo'] = 'bar'
return 'Target', 200
return app
@pytest.fixture()
def client(app):
return app.test_client()
def test_session(client):
with client:
response = client.get("/redirect", follow_redirects=True)
print(f"Session after a redirect: {session.items()}", flush=True)
assert response.status_code == 200
assert response.data == b"Target"
assert session.get("redirected") == "true"
assert session.get('foo') == 'bar'
client.get("/target", follow_redirects=True)
assert session.get('foo') == 'bar'
assert response.data == b"Target"
print(f"Session after a direct request: {session.items()}", flush=True)
The test fails on the first assertion assert session.get('foo') == 'bar'
.
If I comment it out, the test output is the following:
Redirecting to the target endpoint
Target endpoint reached
Session after a redirect: dict_items([('redirected', 'true')])
Target endpoint reached
Session after a direct request: dict_items([('foo', 'bar'), ('redirected', 'true')])
IMPORTANT: The described behavior is not reproduced when running the application with the real HTTP requests.
Environment:
- Python version: 3.13
- Flask version: 3.10