|
| 1 | +import pytest |
| 2 | +from fastapi import FastAPI |
| 3 | +from fastapi.testclient import TestClient |
| 4 | +from starlette.middleware.sessions import SessionMiddleware |
| 5 | + |
| 6 | +from carbonserver.api.routers import authenticate |
| 7 | +from carbonserver.container import ServerContainer |
| 8 | + |
| 9 | +SESSION_COOKIE_NAME = "user_session" |
| 10 | + |
| 11 | + |
| 12 | +@pytest.fixture |
| 13 | +def custom_test_server(): |
| 14 | + container = ServerContainer() |
| 15 | + container.wire(modules=[authenticate]) |
| 16 | + app = FastAPI() |
| 17 | + app.container = container |
| 18 | + app.add_middleware(SessionMiddleware, secret_key="test-secret-key") |
| 19 | + app.include_router(authenticate.router) |
| 20 | + yield app |
| 21 | + |
| 22 | + |
| 23 | +@pytest.fixture |
| 24 | +def client(custom_test_server): |
| 25 | + yield TestClient(custom_test_server) |
| 26 | + |
| 27 | + |
| 28 | +def test_logout_clears_cookie_and_session(client, monkeypatch): |
| 29 | + class DummySession(dict): |
| 30 | + def clear(self): |
| 31 | + self["cleared"] = True |
| 32 | + |
| 33 | + dummy_session = DummySession() |
| 34 | + |
| 35 | + def fake_request(): |
| 36 | + class FakeRequest: |
| 37 | + base_url = "http://testserver/" |
| 38 | + session = dummy_session |
| 39 | + |
| 40 | + return FakeRequest() |
| 41 | + |
| 42 | + monkeypatch.setattr("carbonserver.api.routers.authenticate.Request", fake_request) |
| 43 | + |
| 44 | + # Set cookie and session in request |
| 45 | + cookies = {SESSION_COOKIE_NAME: "dummy_token"} |
| 46 | + with client as c: |
| 47 | + # Set session data by making a request that sets session |
| 48 | + c.cookies.set(SESSION_COOKIE_NAME, "dummy_token") |
| 49 | + # There is no direct way to set session data before logout, so just call logout |
| 50 | + response = c.get("/auth/logout", cookies=cookies) |
| 51 | + assert response.status_code == 200 |
| 52 | + assert ( |
| 53 | + SESSION_COOKIE_NAME not in response.cookies |
| 54 | + or response.cookies.get(SESSION_COOKIE_NAME) == "" |
| 55 | + ) |
| 56 | + # We cannot directly check session cleared, but can check that logout returns redirect |
| 57 | + assert "window.location.href" in response.text |
0 commit comments