forked from mtusi2026/mtusi2026lab2
67 lines
2.7 KiB
Python
67 lines
2.7 KiB
Python
"""Истечение сессии при коротком SESSION_TTL_SECONDS. Запуск при запущенном стенде:
|
||
|
||
python student-tests/test_expiry.py
|
||
|
||
Тест сам пересоздаёт контейнер api с SESSION_TTL_SECONDS=2
|
||
(docker compose up -d --no-deps --wait api, переменная берётся из окружения вместо .env),
|
||
проверяет, что токен работает до срока и даёт 401 после, а в конце возвращает
|
||
обычный TTL из .env. PostgreSQL и Redis при этом не трогаются.
|
||
"""
|
||
import datetime as dt
|
||
import os
|
||
import time
|
||
|
||
from common import call, check, compose, login, new_user, redis_cli, run_tests, session_key, wait_ready
|
||
|
||
SHORT_TTL = 2
|
||
|
||
|
||
def restart_api(ttl=None):
|
||
env = dict(os.environ)
|
||
if ttl is None:
|
||
env.pop("SESSION_TTL_SECONDS", None) # значение снова из .env
|
||
else:
|
||
env["SESSION_TTL_SECONDS"] = str(ttl)
|
||
compose("up", "-d", "--no-deps", "--wait", "api", env=env)
|
||
wait_ready()
|
||
|
||
|
||
def seconds_left(expires_at):
|
||
moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
|
||
return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||
|
||
|
||
def test_session_expires():
|
||
print(f"recreating api with SESSION_TTL_SECONDS={SHORT_TTL}")
|
||
restart_api(SHORT_TTL)
|
||
try:
|
||
user = new_user("ttl")
|
||
session = login(user["username"], user["password"]).json
|
||
token = session["token"]
|
||
left = seconds_left(session["expires_at"])
|
||
print(f"session issued, expires in {left:.2f} s; Redis TTL of the key: "
|
||
f"{redis_cli('pttl', session_key(token))} ms")
|
||
check(0 < left <= SHORT_TTL + 0.5, "short TTL instance must issue ~2 second sessions")
|
||
|
||
call("GET", "/api/v1/users/me", 200, token=token)
|
||
print("before expiry: GET /users/me -> 200")
|
||
|
||
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 1.0)
|
||
call("GET", "/api/v1/users/me", 401, token=token)
|
||
exists = redis_cli("exists", session_key(token))
|
||
print(f"after expiry: GET /users/me -> 401; key exists in Redis: {exists}")
|
||
check(exists == "0", "Redis must delete the expired session key")
|
||
finally:
|
||
print("recreating api with SESSION_TTL_SECONDS from .env")
|
||
restart_api()
|
||
|
||
user = new_user("ttl_back")
|
||
left = seconds_left(login(user["username"], user["password"]).json["expires_at"])
|
||
print(f"normal API again: new session expires in {left:.0f} s")
|
||
check(left > 300, "normal TTL was not restored")
|
||
print("PASS: session expires after SESSION_TTL_SECONDS and is rejected with 401")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
run_tests([test_session_expires])
|