Files
mtusi2026lab2/student-tests/failures/test_expiry.py
T

55 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Истечение сессии. Проверяется на втором экземпляре API с SESSION_TTL_SECONDS=2 (порт 8081)."""
import datetime
import time
import unittest
from stand import call, compose, wait_ready
from api import login, new_user
SHORT_TTL_URL = "http://localhost:8081"
class SessionExpiryTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compose("--profile", "test", "up", "-d", "api-short-ttl")
cls.addClassCleanup(compose, "--profile", "test", "rm", "-sf", "api-short-ttl")
wait_ready(SHORT_TTL_URL)
def test_session_expires(self):
user = new_user("ttl", base_url=SHORT_TTL_URL)
self.assertEqual(call("GET", "/api/v1/users/me", user=user, base_url=SHORT_TTL_URL)[0], 200)
time.sleep(3)
status, body, headers = call("GET", "/api/v1/users/me", user=user, base_url=SHORT_TTL_URL)
self.assertEqual(status, 401)
self.assertEqual(body["error"]["code"], "unauthorized")
self.assertTrue(headers["WWW-Authenticate"].startswith("Bearer "))
# logout с истёкшим токеном тоже 401
self.assertEqual(call("DELETE", "/api/v1/auth/sessions/current", user=user, base_url=SHORT_TTL_URL)[0], 401)
def test_expires_at_matches_ttl(self):
user = new_user("ttl", base_url=SHORT_TTL_URL)
_, session, _ = login(user["username"], user["password"], base_url=SHORT_TTL_URL)
expires_at = datetime.datetime.fromisoformat(session["expires_at"][:-1] + "+00:00")
left = (expires_at - datetime.datetime.now(datetime.timezone.utc)).total_seconds()
self.assertTrue(0 < left <= 2.5, left)
def test_requests_do_not_extend_session(self):
user = new_user("ttl", base_url=SHORT_TTL_URL)
deadline = time.monotonic() + 3
while time.monotonic() < deadline:
call("GET", "/api/v1/users/me", user=user, base_url=SHORT_TTL_URL)
time.sleep(0.2)
self.assertEqual(call("GET", "/api/v1/users/me", user=user, base_url=SHORT_TTL_URL)[0], 401)
def test_login_after_expiry(self):
user = new_user("ttl", base_url=SHORT_TTL_URL)
time.sleep(3)
status, session, _ = login(user["username"], user["password"], base_url=SHORT_TTL_URL)
self.assertEqual(status, 201)
self.assertEqual(call("GET", "/api/v1/users/me", user=session, base_url=SHORT_TTL_URL)[0], 200)
if __name__ == "__main__":
unittest.main()