async def test_session_middleware_handling_of_expired_signature(): app = FakeApplication() app.middlewares.append(SessionMiddleware("LOREM_IPSUM", session_max_age=1)) @app.router.get("/") def home(request: Request): session = request.session assert isinstance(session, Session) session["foo"] = "Some value" return text("Hello, World") @app.router.get("/second") def second(request: Request): session = request.session assert "foo" not in session return text("Hello, World") await app.start() await app( get_example_scope( "GET", "/", ), MockReceive(), MockSend(), ) response = app.response assert response.status == 200 session_set_cookie = response.headers.get_single(b"Set-Cookie") assert session_set_cookie is not None cookie = parse_cookie(session_set_cookie) time.sleep(2) await app( get_example_scope( "GET", "/second", [ [b"cookie", b"session=" + cookie.value.encode()], ], ), MockReceive(), MockSend(), ) response = app.response assert response.status == 200 session_set_cookie = response.headers.get_first(b"Set-Cookie") assert session_set_cookie is None
async def test_session_middleware_with_encryptor(app, mock_receive, mock_send): app.middlewares.append( SessionMiddleware("LOREM_IPSUM", encryptor=FernetEncryptor(Fernet.generate_key()))) @app.router.get("/") def home(request: Request): session = request.session assert isinstance(session, Session) session["foo"] = "Some value" return text("Hello, World") @app.router.get("/second") def second(request: Request): session = request.session assert "foo" in session assert session["foo"] == "Some value" return text("Hello, World") await app.start() await app( get_example_scope( "GET", "/", ), mock_receive(), mock_send, ) response = app.response assert response.status == 200 session_set_cookie = response.headers.get_single(b"Set-Cookie") assert session_set_cookie is not None cookie = parse_cookie(session_set_cookie) await app( get_example_scope( "GET", "/second", [ [b"cookie", b"session=" + cookie.value.encode()], ], ), mock_receive(), mock_send, ) response = app.response assert response.status == 200 session_set_cookie = response.headers.get_first(b"Set-Cookie") assert session_set_cookie is None