Добавить тесты отказов, истечения сессии и транзакций

This commit is contained in:
2026-10-08 18:54:35 +03:00
parent 996a8c5a97
commit ef24bc1635
4 changed files with 234 additions and 0 deletions
+54
View File
@@ -0,0 +1,54 @@
"""Истечение сессии. Проверяется на втором экземпляре 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()