import asyncio import os import time import uuid import base64 import httpx from sqlalchemy import text from src.database import engine from src.auth.tokens import generate_token, hash_token from src.auth.password import hash_password from src.services.session_cache import invalidate_session, cache_session os.environ["DATABASE_URL"] = "postgresql+asyncpg://mtusi:1878@127.0.0.1:5433/mtusi-messenger" from sqlalchemy import text from src.database import engine BASE_URL = "http://localhost:8080" async def create_user(username: str, password: str = "SecurePassword123!") -> dict: async with httpx.AsyncClient() as client: response = await client.post(f"{BASE_URL}/api/v1/users", json={ "username": username, "display_name": f"Test {username}", "password": password}) response.raise_for_status() return response.json() async def login(username: str, password: str = "SecurePassword123!") -> str: credentials = base64.b64encode(f"{username}:{password}".encode()).decode() async with httpx.AsyncClient() as client: response = await client.post(f"{BASE_URL}/api/v1/auth/sessions", headers={"Authorization": f"Basic {credentials}"}) response.raise_for_status() return response.json()["token"] async def test_stale_read(): print("Stale Read при Logout") username = f"test_stale_{uuid.uuid4().hex[:8]}" user = await create_user(username) token = await login(username) async with httpx.AsyncClient() as client: response = await client.get(f"{BASE_URL}/api/v1/users/me", headers={"Authorization": f"Bearer {token}"}) assert response.status_code == 200, "Token should work before logout" print("Token works before logout") async with httpx.AsyncClient() as client: response = await client.delete( f"{BASE_URL}/api/v1/auth/sessions/current", headers={"Authorization": f"Bearer {token}"} ) assert response.status_code == 204, f"Logout failed: {response.status_code}" print("Logout successful") async with httpx.AsyncClient() as client: response = await client.get( f"{BASE_URL}/api/v1/users/me", headers={"Authorization": f"Bearer {token}"} ) if response.status_code == 401: print("Token correctly rejected after logout (no stale cache read)") return True else: print(f"stale read detected: token still works after logout (status={response.status_code})") return False async def test_cache_stampede(): print("Cache Stampede (массовый miss кэша)") username = f"test_stampede_{uuid.uuid4().hex[:8]}" await create_user(username) tokens = [await login(username) for _ in range(100)] print(f"Created {len(tokens)} sessions") print("Waiting for TTL expiration (11s)...") await asyncio.sleep(11) print("Sending 100 parallel requests...") start_time = time.time() async with httpx.AsyncClient(timeout=30.0) as client: async def make_request(token: str): response = await client.get( f"{BASE_URL}/api/v1/users/me", headers={"Authorization": f"Bearer {token}"} ) return response.status_code tasks = [make_request(token) for token in tokens] results = await asyncio.gather(*tasks) elapsed = time.time() - start_time success_count = sum(1 for r in results if r == 200) print(f"Completed in {elapsed:.2f}s") print(f"Successful authentications: {success_count}/{len(tokens)}") return elapsed, success_count async def test_redis_restart(): print("Восстановление после рестарта Redis") username = f"test_restart_{uuid.uuid4().hex[:8]}" user = await create_user(username) token = await login(username) async with httpx.AsyncClient() as client: response = await client.get(f"{BASE_URL}/api/v1/users/me", headers={"Authorization": f"Bearer {token}"}) assert response.status_code == 200 print("Token works before Redis restart") print("Stopping Redis container") proc = await asyncio.create_subprocess_exec("docker", "compose", "stop", "redis") await proc.wait() await asyncio.sleep(5) async with httpx.AsyncClient() as client: response = await client.get(f"{BASE_URL}/api/v1/users/me", headers={"Authorization": f"Bearer {token}"} ) if response.status_code == 200: print("Fallback to DB works (Redis down)") else: print(f"Fallback failed: {response.status_code}") print("Starting Redis container") proc = await asyncio.create_subprocess_exec("docker", "compose", "start", "redis") await proc.wait() await asyncio.sleep(5) async with httpx.AsyncClient() as client: response = await client.get(f"{BASE_URL}/api/v1/users/me", headers={"Authorization": f"Bearer {token}"} ) if response.status_code == 200: print("Token works after Redis restart") else: print(f"Recovery failed: {response.status_code}") async def main(): print("Запуск 3 тестов для Редиса. Stale Read, Cache Stampede, Redis Restart") stale_read_passed = await test_stale_read() stampede_time, stampede_success = await test_cache_stampede() await test_redis_restart() print("SUMMARY") print(f"Stale read protection: {'PASS' if stale_read_passed else 'FAIL'}") print(f"Cache stampede: {stampede_success}/100 successful, {stampede_time:.2f}s") if __name__ == "__main__": asyncio.run(main())