Files
mtusi2026lab4/student-tests/test_sessions.py
T
Alexey BodanyukandClaude Opus 5.5 d916d09f7b перенос: реализация lab3 без изменений (API, миграции 0001-0003, HAProxy, Valkey, тесты)
Исходники, Dockerfile, compose.yaml, скрипты и собственные тесты скопированы из
mtusi2026lab3 (ветка solution/bvt2302-bodanyuk, b6847e2) как есть; изменения lab4 —
отдельными коммитами.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 12:55:58 +03:00

66 lines
3.0 KiB
Python

"""Session lifetime: expiry with a short SESSION_TTL_SECONDS, no extension by restarts,
and the alternative SESSION_STORE=postgres. The api container is recreated with the
override and ALWAYS recreated back with the normal configuration (api_with_env)."""
from __future__ import annotations
import datetime as dt
import time
import pytest
from conftest import api_env, api_with_env, restart_services, service_down
pytestmark = pytest.mark.stack
def seconds_left(expires_at: str) -> float:
moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds()
def login_session(api, actor) -> dict:
from conftest import basic
return api.call("POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": basic(actor["username"], actor["password"])}, schema="Session").json()
@pytest.mark.parametrize("store", ["valkey", "postgres"])
def test_short_ttl_expires(api, store):
with api_with_env(SESSION_TTL_SECONDS="2", SESSION_STORE=store):
assert api_env("SESSION_TTL_SECONDS") == "2" # the contract variable reaches the container
actor = api.register("ttl")
session = login_session(api, actor)
assert 1.0 < seconds_left(session["expires_at"]) <= 2.1
api.call("GET", "/api/v1/users/me", 200, token=session["token"])
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 0.3)
api.call("GET", "/api/v1/users/me", 401, token=session["token"])
api.call("DELETE", "/api/v1/auth/sessions/current", 401, token=session["token"])
def test_restart_does_not_extend_ttl(api):
with api_with_env(SESSION_TTL_SECONDS="12"):
actor = api.register("ttlrestart")
session = login_session(api, actor)
restart_services("valkey", "api")
assert seconds_left(session["expires_at"]) > 0, "restart took longer than the TTL; increase it"
api.call("GET", "/api/v1/users/me", 200, token=session["token"])
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 0.3)
api.call("GET", "/api/v1/users/me", 401, token=session["token"])
def test_postgres_session_store(api):
"""SESSION_STORE=postgres: sessions survive an API restart, logout revokes, and a DB outage
is 503 for a valid token (not 401 and not anonymous access)."""
with api_with_env(SESSION_STORE="postgres"):
assert api_env("SESSION_STORE") == "postgres"
actor = api.user("pgstore")
restart_services("api")
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
with service_down("postgres", "stop"):
assert api.call("GET", "/api/v1/users/me", 503, token=actor["token"],
lb_error_ok=True).json()["error"]["code"] == "unavailable"
api.call("GET", "/api/v1/users/me", (401, 503), lb_error_ok=True)
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=actor["token"])
api.call("GET", "/api/v1/users/me", 401, token=actor["token"])