Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy

This commit is contained in:
Artyom
2026-11-06 09:12:25 +03:00
parent ae9f60fe1f
commit 1217da5f5e
134 changed files with 8243 additions and 1409 deletions
+37 -6
View File
@@ -2,13 +2,18 @@ import asyncio
import time
from datetime import datetime
from hashlib import sha256
from uuid import UUID
import pytest
from redis.asyncio import Redis
from sqlalchemy import select
from conftest import actor, bearer, register, resolve, running_app, scalar
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
from messenger.identity.application.ports import SessionDirectory
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import PostgresSessionRepository, SessionRow
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.shared.application.errors import Unavailable
BEARER = 'Bearer realm="messenger"'
@@ -31,8 +36,9 @@ async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
key = key_of(token_of(alice))
stored = str(await cache.get(key))
sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid"
expires_at: datetime = await scalar(sql, alice["id"])
expires_at: datetime = await scalar(
select(SessionRow.expires_at).where(SessionRow.user_id == UUID(alice["id"]))
)
assert alice["id"] in stored and token_of(alice) not in stored
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
await cache.aclose()
@@ -53,6 +59,29 @@ async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -
await cache.aclose()
async def test_logout_rejected_by_database_changes_nothing(
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch
) -> None:
async def broken(self: PostgresSessionRepository, token_hash: bytes) -> None:
raise Unavailable("PostgreSQL недоступен")
cache = Redis.from_url(valkey["url"])
logout = "/api/v1/auth/sessions/current"
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
with monkeypatch.context() as patch:
patch.setattr(PostgresSessionRepository, "remove", broken)
failed = await http.delete(logout, headers=actor(alice))
assert failed.status_code == 503
assert failed.json()["error"]["code"] == "unavailable"
assert await cache.get(key_of(token_of(alice))) is None
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await http.delete(logout, headers=actor(alice))).status_code == 204
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
await cache.aclose()
async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None:
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
@@ -69,9 +98,6 @@ async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, s
await released.wait()
return stale[-1]
async def invalidate(self, session: Session) -> None:
await origin.invalidate(session)
directory._origin = SlowOrigin()
reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await entered.wait()
@@ -106,6 +132,10 @@ async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43))
elapsed = time.perf_counter() - started
ready = await http.get("/health/ready")
chat = await make_chat(http, alice)
posted = await http.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без кэша"}, headers=keyed(alice)
)
logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
still = await http.get("/api/v1/users/me", headers=actor(alice))
assert me.json() == alice
@@ -113,6 +143,7 @@ async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
assert stranger.headers["WWW-Authenticate"] == BEARER
assert elapsed < 1
assert ready.status_code == 200
assert posted.status_code == 201
assert logout.status_code == 503
assert logout.json()["error"]["code"] == "unavailable"
assert still.status_code == 200