Files
mtusi2026lab3/student-tests/test_sessions.py
T
Alexey BodanyukandClaude Opus 5.5 78b95acabf test: строгие тесты lab3 — идемпотентность, балансировка, отказы реплик
- test_idempotency: точные коды и тела повторов через разные реплики, 24
  одновременных запроса с одним ключом -> ровно одно сообщение и одна строка
  ключа в БД, 409 при другом body, scope user+chat+key, 404 постороннему,
  откат после сбоя на втором INSERT (триггер, n_tup_ins), неопределённый
  POST (клиентский timeout) и lock_timeout с повтором тем же ключом.
- test_balancing: X-Instance-Id = реальные контейнеры, нет sticky,
  LB исключает живую, но неготовую реплику (pg_hba reject), graceful stop
  каждой реплики под нагрузкой без единой ошибки, SIGKILL — ограниченные
  ошибки и восстановление, полный restart и scale up/down без рестарта LB,
  политика compose (лимиты, порты, secrets, digest), миграции один раз.
- Входы из замечаний к чужим PR: курсоры с []/{}/числами/пустые/пробел,
  байт FF, TEXT/text, дубли ключей, Bearer é, UUID в разном регистре, тело
  при входе, пароль "я:"*64. Тесты lab2 переведены на Idempotency-Key и LB;
  все отказы восстанавливаются в finally и ждут UP всех реплик в HAProxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:32:13 +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"])