"""Cache consistency tests for Трек 1. - read-after-write: after POST, GET sees the new message. - cache recovers after Redis restart. """ import base64 import subprocess import time import uuid import httpx BASE = "http://localhost:8080" COMPOSE = ["docker", "compose", "--env-file", ".env"] def _register_and_login(client: httpx.Client) -> dict: username = "cch_" + uuid.uuid4().hex[:10] password = "Test-password-1234" r = client.post( f"{BASE}/api/v1/users", json={ "username": username, "display_name": "Cache Test", "password": password, }, ) assert r.status_code == 201, r.text user = r.json() credential = base64.b64encode( (username + ":" + password).encode("utf-8") ).decode("ascii") r = client.post( f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}, ) assert r.status_code == 201, r.text return {"id": user["id"], "token": r.json()["token"]} def _auth(actor: dict) -> dict: return {"Authorization": "Bearer " + actor["token"]} def test_read_after_write_sees_new_message(): with httpx.Client() as c: alice = _register_and_login(c) bob = _register_and_login(c) chat = c.post( f"{BASE}/api/v1/chats", json={"title": "raw", "member_ids": [alice["id"], bob["id"]]}, headers=_auth(alice), ).json() # Первый GET наполняет кэш r = c.get( f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50", headers=_auth(alice), ) assert r.status_code == 200 before = r.json()["items"] assert len(before) == 0 # POST нового сообщения text = "read-after-write-" + uuid.uuid4().hex[:8] r = c.post( f"{BASE}/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=_auth(alice), ) assert r.status_code == 201, r.text # Второй GET — должен увидеть новое сообщение (не старый кэш) r = c.get( f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50", headers=_auth(alice), ) assert r.status_code == 200 after = r.json()["items"] texts = [m["text"] for m in after] assert text in texts, f"read-after-write failed: {texts}" def test_cache_recovers_after_valkey_restart(): with httpx.Client() as c: alice = _register_and_login(c) bob = _register_and_login(c) chat = c.post( f"{BASE}/api/v1/chats", json={"title": "restart", "member_ids": [alice["id"], bob["id"]]}, headers=_auth(alice), ).json() for i in range(5): c.post( f"{BASE}/api/v1/chats/{chat['id']}/messages", json={"text": f"msg-{i}"}, headers=_auth(alice), ) # Прогрев кэша r = c.get( f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50", headers=_auth(alice), ) assert r.status_code == 200 before = r.json()["items"] assert len(before) == 5 # Перезапуск Valkey subprocess.run(COMPOSE + ["restart", "valkey"], check=True) time.sleep(3) # Подождём восстановление for _ in range(30): try: with httpx.Client(timeout=2) as c: r = c.get(f"{BASE}/health/ready") if r.status_code == 200: break except Exception: pass time.sleep(1) # Снова читаем — тот же результат (из кэша или из БД) with httpx.Client() as c: r = c.get( f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50", headers=_auth(alice), ) assert r.status_code == 200 after = r.json()["items"] assert len(after) == 5 assert [m["id"] for m in after] == [m["id"] for m in before]