forked from mtusi2026/mtusi2026lab6
created skeleton for lab 6
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
"""Фикстуры async-тестов на реальных PostgreSQL и Redis.
|
||||
|
||||
Перед запуском: `make test-stand-up` (тестовый стенд из compose.yaml + compose.test.yaml
|
||||
и база <DB_NAME>_test).
|
||||
Переменные:
|
||||
TEST_DATABASE_URL по умолчанию postgresql+asyncpg://messenger:messenger@localhost:5432/messenger_test
|
||||
TEST_USE_MIGRATIONS=1 строить схему через `alembic upgrade head` вместо Base.metadata.create_all
|
||||
TEST_REDIS_HOST/PORT/PASSWORD/DB по умолчанию localhost:6379, база 15
|
||||
DOCKER_TESTS=1 включить тесты, которые перезапускают контейнеры compose
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi import FastAPI
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.core.redis import create_redis_client
|
||||
from app.main import create_app
|
||||
from app.models import Base
|
||||
|
||||
DEFAULT_TEST_DATABASE_URL = (
|
||||
"postgresql+asyncpg://messenger:messenger@localhost:5432/messenger_test"
|
||||
)
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
return os.environ.get("TEST_DATABASE_URL", DEFAULT_TEST_DATABASE_URL)
|
||||
|
||||
|
||||
def _redis_settings() -> dict[str, object]:
|
||||
return {
|
||||
"redis_host": os.environ.get("TEST_REDIS_HOST", "localhost"),
|
||||
"redis_port": int(os.environ.get("TEST_REDIS_PORT", "6379")),
|
||||
"redis_password": os.environ.get("TEST_REDIS_PASSWORD") or None,
|
||||
"redis_db": int(os.environ.get("TEST_REDIS_DB", "15")),
|
||||
}
|
||||
|
||||
|
||||
def _alembic_config(url: str) -> Config:
|
||||
config = Config("alembic.ini")
|
||||
config.set_main_option("sqlalchemy.url", url.replace("%", "%%"))
|
||||
return config
|
||||
|
||||
|
||||
async def upgrade_head(url: str) -> None:
|
||||
"""alembic command.upgrade внутри вызывает asyncio.run, поэтому — в отдельном потоке."""
|
||||
await asyncio.to_thread(command.upgrade, _alembic_config(url), "head")
|
||||
|
||||
|
||||
async def reset_schema(engine: AsyncEngine) -> None:
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.drop_all)
|
||||
await connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
|
||||
|
||||
async def close_app(app: FastAPI) -> None:
|
||||
"""ASGITransport не запускает lifespan, поэтому ресурсы приложения закрываются явно."""
|
||||
await app.state.redis.aclose()
|
||||
await app.state.engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def database_url() -> str:
|
||||
return _database_url()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def db_engine(database_url: str) -> AsyncIterator[AsyncEngine]:
|
||||
engine = create_async_engine(database_url, poolclass=NullPool)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.execute(text("SELECT 1"))
|
||||
except (SQLAlchemyError, OSError) as error:
|
||||
pytest.exit(
|
||||
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
|
||||
f"{type(error).__name__}. Выполните `make test-stand-up`.",
|
||||
returncode=2,
|
||||
)
|
||||
|
||||
await reset_schema(engine)
|
||||
|
||||
if os.environ.get("TEST_USE_MIGRATIONS") == "1":
|
||||
await upgrade_head(database_url)
|
||||
else:
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
|
||||
yield engine
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def redis_client() -> AsyncIterator[Redis]:
|
||||
settings = build_settings(_database_url())
|
||||
if settings.redis_db == 0:
|
||||
pytest.exit("TEST_REDIS_DB=0 запрещён: тесты очищают базу Redis.", returncode=2)
|
||||
|
||||
client = create_redis_client(settings)
|
||||
try:
|
||||
await client.ping()
|
||||
except (RedisError, OSError) as error:
|
||||
pytest.exit(
|
||||
f"Redis недоступен: {type(error).__name__}. Выполните `make test-stand-up`.",
|
||||
returncode=2,
|
||||
)
|
||||
|
||||
yield client
|
||||
await client.flushdb()
|
||||
await client.aclose()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def clean_db(db_engine: AsyncEngine, redis_client: Redis) -> None:
|
||||
names = ", ".join(f'"{table.name}"' for table in Base.metadata.sorted_tables)
|
||||
if names:
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(text(f"TRUNCATE {names} RESTART IDENTITY CASCADE"))
|
||||
await redis_client.flushdb()
|
||||
|
||||
|
||||
def build_settings(database_url: str, **overrides: object) -> Settings:
|
||||
values: dict[str, object] = {
|
||||
# Регрессия проверяет PostgreSQL/Redis; MinIO подменяется отдельно.
|
||||
"s3_enabled": False,
|
||||
"app_host": "127.0.0.1",
|
||||
"app_port": 8080,
|
||||
"app_env": "test",
|
||||
"max_messages": 1000,
|
||||
"max_in_flight": 32,
|
||||
"log_level": "CRITICAL",
|
||||
"database_url": database_url,
|
||||
"session_ttl_seconds": 300,
|
||||
"db_pool_size": 10,
|
||||
"db_max_overflow": 10,
|
||||
**_redis_settings(),
|
||||
}
|
||||
values.update(overrides)
|
||||
return Settings(_env_file=None, **values) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def settings(database_url: str) -> Settings:
|
||||
return build_settings(database_url)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_settings(database_url: str) -> Callable[..., Settings]:
|
||||
def factory(**overrides: object) -> Settings:
|
||||
url = str(overrides.pop("database_url", database_url))
|
||||
return build_settings(url, **overrides)
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
def make_client(
|
||||
app, *, raise_app_exceptions: bool = True, timeout: float = 30
|
||||
) -> httpx.AsyncClient:
|
||||
"""ASGITransport не запускает lifespan, поэтому ресурсы закрывает вызывающий (close_app)."""
|
||||
return httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(
|
||||
app=app, raise_app_exceptions=raise_app_exceptions
|
||||
),
|
||||
base_url="http://testserver",
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(settings: Settings):
|
||||
application = create_app(settings)
|
||||
|
||||
@application.get("/__test__/explode", include_in_schema=False)
|
||||
async def explode() -> None:
|
||||
raise RuntimeError("test-secret")
|
||||
|
||||
return application
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client(app) -> AsyncIterator[httpx.AsyncClient]:
|
||||
async with make_client(app) as test_client:
|
||||
yield test_client
|
||||
await close_app(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client_no_raise(app) -> AsyncIterator[httpx.AsyncClient]:
|
||||
async with make_client(app, raise_app_exceptions=False) as test_client:
|
||||
yield test_client
|
||||
await close_app(app)
|
||||
@@ -0,0 +1,88 @@
|
||||
import base64
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
PASSWORD = "Correct-horse-battery-1"
|
||||
|
||||
|
||||
def basic_header(username: str, password: str) -> dict[str, str]:
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
||||
|
||||
|
||||
def bearer(actor: dict) -> dict[str, str]:
|
||||
return {"Authorization": "Bearer " + actor["token"]}
|
||||
|
||||
|
||||
async def register(
|
||||
client: AsyncClient,
|
||||
username: str | None = None,
|
||||
display_name: str = "Тестовый пользователь",
|
||||
password: str = PASSWORD,
|
||||
) -> dict:
|
||||
"""Регистрация без входа. Возвращает User + password (нужен для login)."""
|
||||
actual_username = username or "user_" + uuid4().hex[:12]
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": actual_username,
|
||||
"display_name": display_name,
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return {**response.json(), "password": password}
|
||||
|
||||
|
||||
async def login(client: AsyncClient, user: dict) -> dict:
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return {**user, "token": response.json()["token"]}
|
||||
|
||||
|
||||
async def create_user(client: AsyncClient, **kwargs) -> dict:
|
||||
"""Регистрация + вход: актор с полями id, username, token, ..."""
|
||||
return await login(client, await register(client, **kwargs))
|
||||
|
||||
|
||||
async def create_chat(
|
||||
client: AsyncClient,
|
||||
user: dict,
|
||||
*members: dict,
|
||||
title: str = "Тестовый чат",
|
||||
) -> dict:
|
||||
member_ids = [user["id"], *(member["id"] for member in members)]
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(user),
|
||||
json={"title": title, "member_ids": member_ids},
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def idempotency_header(key: str | None = None) -> dict[str, str]:
|
||||
return {"Idempotency-Key": key or uuid4().hex}
|
||||
|
||||
|
||||
async def send_message(
|
||||
client: AsyncClient, user: dict, chat: dict, text: str, key: str | None = None
|
||||
):
|
||||
"""POST сообщения требует Idempotency-Key; по умолчанию — новый ключ."""
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={**bearer(user), **idempotency_header(key)},
|
||||
json={"text": text},
|
||||
)
|
||||
|
||||
|
||||
def assert_request_id(response) -> str:
|
||||
header_id = response.headers.get("X-Request-Id")
|
||||
assert header_id
|
||||
if response.status_code >= 400:
|
||||
assert response.json()["error"]["request_id"] == header_id
|
||||
return header_id
|
||||
@@ -0,0 +1,483 @@
|
||||
"""API и транзакции с реальной БД; байты S3 подменены управляемым адаптером."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import struct
|
||||
from uuid import UUID, uuid4
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from app.core.s3 import S3Settings
|
||||
from app.core.jobs import JobSettings
|
||||
from app.domain.attachment_jobs import process_attachment_job
|
||||
from app.models.job import AttachmentJob
|
||||
from app.schemas.job import JobMessage
|
||||
from app.domain import attachments as domain
|
||||
from app.errors.exceptions import unavailable
|
||||
from app.models.attachment import Attachment, UploadIntent
|
||||
from app.storage import attachments as repository
|
||||
from app.storage.s3 import ObjectInfo
|
||||
from helpers import bearer, create_chat, create_user, idempotency_header
|
||||
|
||||
PNG = Path("tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
"""Только тестовый адаптер; production использует MinioStorage."""
|
||||
|
||||
def __init__(self):
|
||||
self.settings = S3Settings(_env_file=None)
|
||||
self.objects = {}
|
||||
self.fail_put = self.fail_delete = self.down = False
|
||||
|
||||
async def put_file(self, key, path, **metadata):
|
||||
self.objects[key] = (path.read_bytes(), metadata)
|
||||
if self.fail_put:
|
||||
raise unavailable()
|
||||
|
||||
async def delete_object(self, key):
|
||||
if self.fail_delete:
|
||||
raise unavailable()
|
||||
self.objects.pop(key, None)
|
||||
|
||||
async def stat_object(self, key):
|
||||
if self.down:
|
||||
raise unavailable()
|
||||
info = None
|
||||
if key in self.objects:
|
||||
data, metadata = self.objects[key]
|
||||
info = ObjectInfo(
|
||||
key, len(data), metadata["content_type"], datetime.now(timezone.utc)
|
||||
)
|
||||
return info
|
||||
|
||||
async def open_object(self, key):
|
||||
async def chunks():
|
||||
yield self.objects[key][0]
|
||||
|
||||
return chunks()
|
||||
|
||||
async def check_available(self):
|
||||
return not self.down
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def context(client, app):
|
||||
storage = MemoryStorage()
|
||||
app.state.s3 = storage
|
||||
alice, bob, eve = [await create_user(client) for _ in range(3)]
|
||||
chat = await create_chat(client, alice, bob)
|
||||
return storage, alice, bob, eve, chat
|
||||
|
||||
|
||||
async def upload(
|
||||
client, actor, chat, data=PNG, filename="фото.png", content_type="image/png"
|
||||
):
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": filename},
|
||||
headers={**bearer(actor), "Content-Type": content_type},
|
||||
content=data,
|
||||
)
|
||||
|
||||
|
||||
async def finish_attachment(client, storage, actor, attachment_id):
|
||||
engine = client._transport.app.state.engine
|
||||
async with AsyncSession(engine) as session:
|
||||
job = await session.scalar(
|
||||
select(AttachmentJob).where(
|
||||
AttachmentJob.attachment_id == UUID(attachment_id)
|
||||
)
|
||||
)
|
||||
message = JobMessage(
|
||||
job_id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version,
|
||||
attempt=job.attempt + 1,
|
||||
created_at=job.created_at,
|
||||
)
|
||||
await session.rollback()
|
||||
assert await process_attachment_job(
|
||||
session, storage, message, JobSettings(_env_file=None)
|
||||
)
|
||||
result = await client.get(
|
||||
f"/api/v1/attachments/{attachment_id}", headers=bearer(actor)
|
||||
)
|
||||
assert result.json()["status"] == "ready"
|
||||
return result.json()
|
||||
|
||||
|
||||
async def test_upload_download_and_attachment_only_message(client, context):
|
||||
storage, alice, bob, eve, chat = context
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
attachment = response.json()
|
||||
assert attachment["status"] == "queued"
|
||||
before = await client.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=bearer(alice)
|
||||
)
|
||||
assert before.status_code == 409
|
||||
attachment = await finish_attachment(client, storage, alice, attachment["id"])
|
||||
assert attachment["sha256"] == hashlib.sha256(PNG).hexdigest()
|
||||
assert {v["name"] for v in attachment["variants"]} == {
|
||||
"thumbnail",
|
||||
"crop",
|
||||
"optimized",
|
||||
}
|
||||
assert attachment["error_code"] is None
|
||||
assert "object_key" not in attachment
|
||||
id = attachment["id"]
|
||||
for actor in (alice, bob):
|
||||
content = await client.get(
|
||||
f"/api/v1/attachments/{id}/content", headers=bearer(actor)
|
||||
)
|
||||
assert content.status_code == 200 and content.content == PNG
|
||||
assert content.headers["content-type"] == "image/png"
|
||||
key = idempotency_header()
|
||||
body = {"text": "", "attachment_ids": [id]}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
message = await client.post(path, json=body, headers={**bearer(bob), **key})
|
||||
assert message.status_code == 201, message.text
|
||||
repeat = await client.post(path, json=body, headers={**bearer(bob), **key})
|
||||
assert repeat.json() == message.json()
|
||||
history = await client.get(path, headers=bearer(alice))
|
||||
assert history.json()["items"][0]["attachment_ids"] == [id]
|
||||
for suffix in ("", "/content"):
|
||||
denied = await client.get(
|
||||
f"/api/v1/attachments/{id}{suffix}", headers=bearer(eve)
|
||||
)
|
||||
assert denied.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"data,content_type",
|
||||
[
|
||||
(b"not an image", "image/png"),
|
||||
(PNG[:30], "image/png"),
|
||||
(PNG, "image/jpeg"),
|
||||
(PNG, "application/octet-stream"),
|
||||
],
|
||||
ids=["not-image", "truncated-png", "mime-spoofing", "unsupported-type"],
|
||||
)
|
||||
async def test_invalid_image_and_mime_are_415(client, context, data, content_type):
|
||||
storage, alice, _, _, chat = context
|
||||
response = await upload(client, alice, chat, data, content_type=content_type)
|
||||
assert response.status_code == 415, response.text
|
||||
assert not storage.objects
|
||||
|
||||
|
||||
async def test_jpeg_is_stored_without_reencoding(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
output = BytesIO()
|
||||
Image.new("RGB", (32, 32), "blue").save(output, format="JPEG")
|
||||
original = output.getvalue()
|
||||
response = await upload(client, alice, chat, original, content_type="image/jpeg")
|
||||
assert response.status_code == 202, response.text
|
||||
id = response.json()["id"]
|
||||
await finish_attachment(client, storage, alice, id)
|
||||
downloaded = await client.get(
|
||||
f"/api/v1/attachments/{id}/content", headers=bearer(alice)
|
||||
)
|
||||
assert downloaded.content == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"filename", ["../a.png", "a\\b.png", "a\x00.png", "a\n.png", "x" * 256]
|
||||
)
|
||||
async def test_unsafe_filename_is_400(client, context, filename):
|
||||
storage, alice, _, _, chat = context
|
||||
response = await upload(client, alice, chat, filename=filename)
|
||||
assert response.status_code == 400
|
||||
assert not storage.objects
|
||||
|
||||
|
||||
async def test_oversize_chunked_upload_is_413(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
|
||||
async def chunks():
|
||||
for _ in range(11):
|
||||
yield b"x" * 1048576
|
||||
|
||||
response = await upload(client, alice, chat, chunks())
|
||||
assert response.status_code == 413
|
||||
assert not storage.objects
|
||||
|
||||
|
||||
async def test_oversize_content_length_is_413(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png",
|
||||
headers={
|
||||
**bearer(alice),
|
||||
"Content-Type": "image/png",
|
||||
"Content-Length": "10485761",
|
||||
},
|
||||
content=PNG,
|
||||
)
|
||||
assert response.status_code == 413
|
||||
|
||||
|
||||
async def test_exact_byte_limit_accepts_valid_png(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
maximum = 10_485_760
|
||||
# Валидный ancillary chunk вместо данных после IEND.
|
||||
payload = bytes(maximum - len(PNG) - 12)
|
||||
kind = b"npAD"
|
||||
padding = (
|
||||
struct.pack("!I", len(payload))
|
||||
+ kind
|
||||
+ payload
|
||||
+ struct.pack("!I", zlib.crc32(kind + payload))
|
||||
)
|
||||
image = PNG[:-12] + padding + PNG[-12:]
|
||||
response = await upload(client, alice, chat, image)
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["size_bytes"] == maximum
|
||||
assert response.json()["sha256"] == hashlib.sha256(image).hexdigest()
|
||||
|
||||
|
||||
async def test_exact_pixel_limit_accepts_valid_png(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
output = BytesIO()
|
||||
with Image.new("RGB", (8000, 5000), "blue") as image:
|
||||
image.save(output, format="PNG")
|
||||
response = await upload(client, alice, chat, output.getvalue())
|
||||
assert response.status_code == 202, response.text
|
||||
|
||||
|
||||
async def test_pixel_limit_before_decoding(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
|
||||
def chunk(kind, data):
|
||||
return (
|
||||
struct.pack("!I", len(data))
|
||||
+ kind
|
||||
+ data
|
||||
+ struct.pack("!I", zlib.crc32(kind + data))
|
||||
)
|
||||
|
||||
header = struct.pack("!IIBBBBB", 8000, 5001, 8, 2, 0, 0, 0)
|
||||
image = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"IDAT", zlib.compress(b"\0"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
response = await upload(client, alice, chat, image)
|
||||
assert response.status_code == 413, response.text
|
||||
|
||||
|
||||
async def test_unknown_and_other_chat_attachment_are_404(client, context):
|
||||
_, alice, bob, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
other_chat = await create_chat(client, alice, bob)
|
||||
for id in (attachment["id"], str(uuid4())):
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{other_chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [id]},
|
||||
headers={**bearer(alice), **idempotency_header()},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_duplicate_ids_are_400(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
id = (await upload(client, alice, chat)).json()["id"]
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [id, id]},
|
||||
headers={**bearer(alice), **idempotency_header()},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
async def test_empty_ids_and_absent_ids_have_same_idempotency(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
headers = {**bearer(alice), **idempotency_header()}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
first = await client.post(path, json={"text": "same"}, headers=headers)
|
||||
second = await client.post(
|
||||
path, json={"text": "same", "attachment_ids": []}, headers=headers
|
||||
)
|
||||
assert first.status_code == second.status_code == 201
|
||||
assert first.json() == second.json()
|
||||
|
||||
|
||||
async def test_s3_outage_is_503(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
id = (await upload(client, alice, chat)).json()["id"]
|
||||
await finish_attachment(client, storage, alice, id)
|
||||
storage.down = True
|
||||
response = await client.get(
|
||||
f"/api/v1/attachments/{id}/content", headers=bearer(alice)
|
||||
)
|
||||
assert response.status_code == 503
|
||||
assert (await client.get("/health/ready")).status_code == 503
|
||||
|
||||
|
||||
async def test_uncertain_put_is_compensated(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
storage.fail_put = True
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 503
|
||||
assert not storage.objects
|
||||
async with AsyncSession(db_engine) as session:
|
||||
assert await session.scalar(select(func.count()).select_from(UploadIntent)) == 0
|
||||
|
||||
|
||||
async def test_failure_after_s3_write_compensates(client, context, monkeypatch):
|
||||
storage, alice, _, _, chat = context
|
||||
|
||||
async def fail(*args, **kwargs):
|
||||
raise OperationalError("injected", {}, None)
|
||||
|
||||
monkeypatch.setattr(repository, "create_attachment", fail)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 503
|
||||
assert not storage.objects
|
||||
|
||||
|
||||
async def test_ambiguous_successful_commit_keeps_original(
|
||||
client, context, db_engine, monkeypatch
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
original = AsyncSession.commit
|
||||
count = 0
|
||||
|
||||
async def uncertain(session):
|
||||
nonlocal count
|
||||
count += 1
|
||||
await original(session)
|
||||
if count == 2:
|
||||
raise OperationalError("lost commit acknowledgement", {}, None)
|
||||
|
||||
monkeypatch.setattr(AsyncSession, "commit", uncertain)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 503
|
||||
assert len(storage.objects) == 1
|
||||
async with AsyncSession(db_engine) as session:
|
||||
assert await session.scalar(select(func.count()).select_from(Attachment)) == 1
|
||||
assert await session.scalar(select(func.count()).select_from(UploadIntent)) == 0
|
||||
|
||||
|
||||
async def test_failed_compensation_then_dry_run_and_cleanup(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
storage.fail_put = storage.fail_delete = True
|
||||
assert (await upload(client, alice, chat)).status_code == 503
|
||||
assert len(storage.objects) == 1
|
||||
async with AsyncSession(db_engine) as session:
|
||||
intent = await session.scalar(select(UploadIntent))
|
||||
intent.created_at = datetime.now(timezone.utc) - timedelta(days=2)
|
||||
await session.commit()
|
||||
storage.fail_put = storage.fail_delete = False
|
||||
async with AsyncSession(db_engine) as session:
|
||||
dry_run = await domain.reconcile_attachments(session, storage)
|
||||
assert dry_run.candidates == 1 and dry_run.deleted == 0
|
||||
assert storage.objects
|
||||
applied = await domain.reconcile_attachments(session, storage, dry_run=False)
|
||||
assert applied.deleted == 1 and not storage.objects
|
||||
repeated = await domain.reconcile_attachments(session, storage, dry_run=False)
|
||||
assert repeated.deleted == 0
|
||||
|
||||
|
||||
async def test_cleanup_keeps_fresh_and_skips_locked_uploads(client, context, db_engine):
|
||||
storage, _, _, _, _ = context
|
||||
old_id, fresh_id = uuid4(), uuid4()
|
||||
async with AsyncSession(db_engine) as session:
|
||||
session.add_all(
|
||||
[
|
||||
UploadIntent(
|
||||
id=old_id,
|
||||
object_key="originals/old",
|
||||
created_at=datetime.now(timezone.utc) - timedelta(days=2),
|
||||
),
|
||||
UploadIntent(id=fresh_id, object_key="originals/fresh"),
|
||||
]
|
||||
)
|
||||
await session.commit()
|
||||
async with AsyncSession(db_engine) as uploader, AsyncSession(db_engine) as cleaner:
|
||||
await repository.lock_upload(uploader, old_id)
|
||||
result = await domain.reconcile_attachments(cleaner, storage, dry_run=False)
|
||||
assert result.examined == 0
|
||||
await uploader.rollback()
|
||||
result = await domain.reconcile_attachments(cleaner, storage, dry_run=False)
|
||||
assert result.examined == 1
|
||||
assert await cleaner.get(UploadIntent, fresh_id) is not None
|
||||
|
||||
|
||||
async def test_client_disconnect_before_put_has_no_side_effects(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
|
||||
async def interrupted():
|
||||
yield PNG[:16]
|
||||
raise ClientDisconnect()
|
||||
|
||||
response = await upload(client, alice, chat, interrupted())
|
||||
assert response.status_code == 400
|
||||
assert not storage.objects
|
||||
|
||||
|
||||
async def test_upload_deadline_cancels_validation(client, context, monkeypatch):
|
||||
storage, alice, _, _, chat = context
|
||||
storage.settings = storage.settings.model_copy(
|
||||
update={"upload_timeout_seconds": 0.02}
|
||||
)
|
||||
|
||||
async def stalled(*args):
|
||||
await asyncio.sleep(10)
|
||||
|
||||
monkeypatch.setattr(domain, "validate_image", stalled)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 400
|
||||
assert not storage.objects
|
||||
|
||||
|
||||
async def test_cancelled_put_is_compensated(client, context, db_engine, monkeypatch):
|
||||
storage, alice, _, _, chat = context
|
||||
entered = asyncio.Event()
|
||||
original = storage.put_file
|
||||
|
||||
async def interrupted(*args, **kwargs):
|
||||
await original(*args, **kwargs)
|
||||
entered.set()
|
||||
await asyncio.sleep(10)
|
||||
|
||||
monkeypatch.setattr(storage, "put_file", interrupted)
|
||||
task = asyncio.create_task(upload(client, alice, chat))
|
||||
await asyncio.wait_for(entered.wait(), timeout=10)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert not storage.objects
|
||||
async with AsyncSession(db_engine) as session:
|
||||
assert await session.scalar(select(func.count()).select_from(UploadIntent)) == 0
|
||||
|
||||
|
||||
async def test_cleanup_never_deletes_ready_attachment(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
id = (await upload(client, alice, chat)).json()["id"]
|
||||
await finish_attachment(client, storage, alice, id)
|
||||
async with AsyncSession(db_engine) as session:
|
||||
attachment = await session.get(Attachment, UUID(id))
|
||||
key = attachment.object_key
|
||||
# Искусственно оставляем старый журнал у уже подтверждённого объекта.
|
||||
session.add(
|
||||
UploadIntent(
|
||||
id=uuid4(),
|
||||
object_key=key,
|
||||
created_at=datetime.now(timezone.utc) - timedelta(days=2),
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
result = await domain.reconcile_attachments(session, storage, dry_run=False)
|
||||
assert result.examined == 1 and result.deleted == 0
|
||||
assert key in storage.objects
|
||||
@@ -0,0 +1,298 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import (
|
||||
PASSWORD,
|
||||
assert_request_id,
|
||||
basic_header,
|
||||
bearer,
|
||||
create_user,
|
||||
login,
|
||||
register,
|
||||
)
|
||||
|
||||
|
||||
async def test_login_returns_opaque_bearer_session(client: AsyncClient):
|
||||
user = await register(client)
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
body = response.json()
|
||||
assert set(body) == {"token", "token_type", "expires_at", "user"}
|
||||
assert body["token_type"] == "Bearer"
|
||||
assert len(body["token"]) >= 43
|
||||
assert body["token"] not in (user["id"], user["username"])
|
||||
assert body["user"]["id"] == user["id"]
|
||||
assert body["expires_at"].endswith("Z")
|
||||
assert datetime.fromisoformat(body["expires_at"])
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_each_login_issues_a_different_token(client: AsyncClient):
|
||||
user = await register(client)
|
||||
first = await login(client, user)
|
||||
second = await login(client, user)
|
||||
|
||||
assert first["token"] != second["token"]
|
||||
|
||||
|
||||
async def test_password_with_colon_works(client: AsyncClient):
|
||||
user = await register(client, password="pass:with:colons-123")
|
||||
|
||||
assert (await login(client, user))["token"]
|
||||
|
||||
|
||||
async def test_unicode_password_works(client: AsyncClient):
|
||||
user = await register(client, password="Пароль-с-юникодом-🔑-123")
|
||||
|
||||
assert (await login(client, user))["token"]
|
||||
|
||||
|
||||
async def test_wrong_password_and_unknown_user_look_identical(client: AsyncClient):
|
||||
user = await register(client)
|
||||
|
||||
wrong_password = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], "wrong-password-123"),
|
||||
)
|
||||
unknown_user = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header("no_such_user", "wrong-password-123"),
|
||||
)
|
||||
|
||||
for response in (wrong_password, unknown_user):
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert response.headers["WWW-Authenticate"].startswith(
|
||||
'Basic realm="messenger"'
|
||||
)
|
||||
assert_request_id(response)
|
||||
assert (
|
||||
wrong_password.json()["error"]["message"]
|
||||
== unknown_user.json()["error"]["message"]
|
||||
)
|
||||
|
||||
|
||||
async def test_login_requires_basic_scheme(client: AsyncClient):
|
||||
user = await register(client)
|
||||
session = await login(client, user)
|
||||
|
||||
for headers in ({}, bearer(session), {"Authorization": "Basic !!!not-base64"}):
|
||||
response = await client.post("/api/v1/auth/sessions", headers=headers)
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"].startswith("Basic")
|
||||
|
||||
|
||||
async def test_business_endpoints_require_bearer(client: AsyncClient):
|
||||
user = await register(client)
|
||||
|
||||
for headers in (
|
||||
{},
|
||||
basic_header(user["username"], user["password"]),
|
||||
{"Authorization": "Bearer "},
|
||||
{"Authorization": "Bearer unknown-token-value"},
|
||||
{"X-User-Id": user["id"]},
|
||||
):
|
||||
response = await client.get("/api/v1/users/me", headers=headers)
|
||||
assert response.status_code == 401, headers
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert response.headers["WWW-Authenticate"].startswith(
|
||||
'Bearer realm="messenger"'
|
||||
)
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_x_user_id_cannot_override_bearer_identity(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
eve = await create_user(client)
|
||||
|
||||
response = await client.get(
|
||||
"/api/v1/users/me",
|
||||
headers={**bearer(alice), "X-User-Id": eve["id"]},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == alice["id"]
|
||||
|
||||
|
||||
async def test_logout_revokes_only_current_session(client: AsyncClient):
|
||||
user = await register(client)
|
||||
first = await login(client, user)
|
||||
second = await login(client, user)
|
||||
|
||||
assert (
|
||||
await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))
|
||||
).status_code == 204
|
||||
|
||||
assert (
|
||||
await client.get("/api/v1/users/me", headers=bearer(first))
|
||||
).status_code == 401
|
||||
assert (
|
||||
await client.get("/api/v1/users/me", headers=bearer(second))
|
||||
).status_code == 200
|
||||
|
||||
|
||||
async def test_logout_twice_returns_401(client: AsyncClient):
|
||||
session = await create_user(client)
|
||||
|
||||
first = await client.delete(
|
||||
"/api/v1/auth/sessions/current", headers=bearer(session)
|
||||
)
|
||||
again = await client.delete(
|
||||
"/api/v1/auth/sessions/current", headers=bearer(session)
|
||||
)
|
||||
|
||||
assert first.status_code == 204
|
||||
assert first.content == b""
|
||||
assert again.status_code == 401
|
||||
|
||||
|
||||
async def test_session_expires_after_ttl(make_settings):
|
||||
app = create_app(make_settings(session_ttl_seconds=2))
|
||||
async with make_client(app) as client:
|
||||
session = await create_user(client)
|
||||
assert (
|
||||
await client.get("/api/v1/users/me", headers=bearer(session))
|
||||
).status_code == 200
|
||||
|
||||
await asyncio.sleep(3)
|
||||
|
||||
response = await client.get("/api/v1/users/me", headers=bearer(session))
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"].startswith("Bearer")
|
||||
await close_app(app)
|
||||
|
||||
|
||||
async def test_token_is_stored_only_as_sha256_key(client: AsyncClient, redis_client):
|
||||
session = await create_user(client)
|
||||
|
||||
keys = [key async for key in redis_client.scan_iter("session:*")]
|
||||
token_hash = hashlib.sha256(session["token"].encode()).hexdigest()
|
||||
|
||||
assert keys == [f"session:{token_hash}"]
|
||||
assert await redis_client.get(keys[0]) == session["id"]
|
||||
assert all(session["token"] not in key for key in keys)
|
||||
|
||||
|
||||
async def test_password_is_not_stored_in_plaintext(client: AsyncClient, db_engine):
|
||||
from sqlalchemy import text
|
||||
|
||||
await register(client, username="hash_check")
|
||||
|
||||
async with db_engine.connect() as connection:
|
||||
result = await connection.execute(
|
||||
text("SELECT password_hash FROM users WHERE username = 'hash_check'")
|
||||
)
|
||||
stored = result.scalar_one()
|
||||
|
||||
assert PASSWORD not in stored
|
||||
assert stored.startswith("$argon2id$")
|
||||
|
||||
|
||||
async def test_login_rejects_out_of_range_password_like_wrong_password(
|
||||
client: AsyncClient,
|
||||
):
|
||||
user = await register(client)
|
||||
reference = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], "wrong-password-123"),
|
||||
)
|
||||
|
||||
for password in ("x" * 11, "x" * 129, ""):
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], password),
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert (
|
||||
response.json()["error"]["message"] == reference.json()["error"]["message"]
|
||||
)
|
||||
assert (
|
||||
response.headers["WWW-Authenticate"]
|
||||
== reference.headers["WWW-Authenticate"]
|
||||
)
|
||||
|
||||
|
||||
async def test_malformed_basic_credentials_return_401(client: AsyncClient):
|
||||
import base64
|
||||
|
||||
def raw(value: bytes) -> dict[str, str]:
|
||||
return {"Authorization": "Basic " + base64.b64encode(value).decode()}
|
||||
|
||||
for headers in (
|
||||
raw(b"no-colon-here"),
|
||||
raw(b":password-without-user"),
|
||||
raw(b"\xff\xfe:invalid-utf8"),
|
||||
{"Authorization": "Basic"},
|
||||
{"Authorization": "Digest abc"},
|
||||
):
|
||||
response = await client.post("/api/v1/auth/sessions", headers=headers)
|
||||
assert response.status_code == 401, headers
|
||||
assert response.headers["WWW-Authenticate"].startswith("Basic")
|
||||
|
||||
|
||||
async def test_unknown_user_takes_comparable_time_to_wrong_password(
|
||||
client: AsyncClient,
|
||||
):
|
||||
import statistics
|
||||
import time
|
||||
|
||||
user = await register(client)
|
||||
|
||||
async def measure(username: str) -> float:
|
||||
samples = []
|
||||
for _ in range(5):
|
||||
started = time.perf_counter()
|
||||
await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(username, "wrong-password-123"),
|
||||
)
|
||||
samples.append(time.perf_counter() - started)
|
||||
return statistics.median(samples)
|
||||
|
||||
wrong_password = await measure(user["username"])
|
||||
unknown_user = await measure("no_such_user")
|
||||
|
||||
assert unknown_user > wrong_password * 0.5
|
||||
|
||||
|
||||
async def test_invalid_basic_username_returns_401_not_500(client: AsyncClient):
|
||||
user = await register(client)
|
||||
reference = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], "wrong-password-123"),
|
||||
)
|
||||
|
||||
for username in ("bad\u0000name", "UPPER", "no", "x" * 33, "имя", "a b c"):
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(username, "wrong-password-123"),
|
||||
)
|
||||
assert response.status_code == 401, username
|
||||
assert (
|
||||
response.json()["error"]["message"] == reference.json()["error"]["message"]
|
||||
)
|
||||
assert (
|
||||
response.headers["WWW-Authenticate"]
|
||||
== reference.headers["WWW-Authenticate"]
|
||||
)
|
||||
|
||||
|
||||
async def test_whitespace_only_password_at_login_returns_401(client: AsyncClient):
|
||||
user = await register(client)
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions", headers=basic_header(user["username"], " " * 12)
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"].startswith("Basic")
|
||||
@@ -0,0 +1,209 @@
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from helpers import assert_request_id, bearer, create_chat, create_user
|
||||
|
||||
|
||||
async def test_create_and_get_chat(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
chat = await create_chat(client, alice, bob)
|
||||
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}",
|
||||
headers=bearer(bob),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == chat
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_chat_is_not_visible_to_outsider(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
eve = await create_user(client)
|
||||
chat = await create_chat(client, alice, bob)
|
||||
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}",
|
||||
headers=bearer(eve),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_chat_creation_requires_creator_in_members(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [bob["id"]]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"title": "", "member_ids": []},
|
||||
{"title": " ", "member_ids": []},
|
||||
],
|
||||
)
|
||||
async def test_chat_payload_boundaries(client: AsyncClient, payload: dict):
|
||||
alice = await create_user(client)
|
||||
payload["member_ids"] = [alice["id"]]
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json=payload,
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_duplicate_members_are_rejected(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [alice["id"], bob["id"], bob["id"]]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_unknown_member_is_rejected(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_chat_exact_title_limit_is_accepted(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "x" * 100, "member_ids": [alice["id"]]},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert len(response.json()["title"]) == 100
|
||||
|
||||
|
||||
async def test_chat_list_hides_chats_without_membership(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
chat_for_bob = await create_chat(client, bob, title="Only Bob")
|
||||
chat_for_alice = await create_chat(client, alice, title="Only Alice")
|
||||
|
||||
response = await client.get(
|
||||
"/api/v1/chats?limit=100",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
ids = {item["id"] for item in response.json()["items"]}
|
||||
assert chat_for_alice["id"] in ids
|
||||
assert chat_for_bob["id"] not in ids
|
||||
|
||||
|
||||
async def test_nonexistent_chat_returns_404(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
|
||||
response = await client.get(
|
||||
"/api/v1/chats/00000000-0000-4000-8000-000000000000",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_failed_chat_creation_leaves_no_partial_data(
|
||||
client: AsyncClient, db_engine
|
||||
):
|
||||
"""Атомарность: неизвестный участник -> нет ни чата, ни записей членства."""
|
||||
from sqlalchemy import text
|
||||
|
||||
alice = await create_user(client)
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
async with db_engine.connect() as connection:
|
||||
chats = (
|
||||
await connection.execute(text("SELECT count(*) FROM chats"))
|
||||
).scalar_one()
|
||||
members = (
|
||||
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
||||
).scalar_one()
|
||||
assert chats == 0 and members == 0
|
||||
|
||||
|
||||
async def test_chat_list_pagination_and_order(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chats = [await create_chat(client, alice, title=f"chat-{i}") for i in range(5)]
|
||||
|
||||
page1 = (await client.get("/api/v1/chats?limit=2", headers=bearer(alice))).json()
|
||||
page2 = (
|
||||
await client.get(
|
||||
f"/api/v1/chats?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
page3 = (
|
||||
await client.get(
|
||||
f"/api/v1/chats?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
|
||||
ids = [c["id"] for page in (page1, page2, page3) for c in page["items"]]
|
||||
assert ids == [c["id"] for c in chats]
|
||||
assert page3["next_cursor"] is None
|
||||
|
||||
|
||||
async def test_chat_endpoints_require_bearer(client: AsyncClient):
|
||||
assert (await client.get("/api/v1/chats")).status_code == 401
|
||||
assert (
|
||||
await client.post("/api/v1/chats", json={"title": "x", "member_ids": []})
|
||||
).status_code in (401, 400)
|
||||
|
||||
|
||||
async def test_nul_in_chat_title_is_rejected(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "chat\u0000title", "member_ids": [alice["id"]]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Конкурентность на реальной БД: гонка регистрации и параллельная запись."""
|
||||
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import (
|
||||
PASSWORD,
|
||||
basic_header,
|
||||
bearer,
|
||||
create_user,
|
||||
idempotency_header,
|
||||
register,
|
||||
)
|
||||
|
||||
|
||||
async def test_parallel_registration_of_same_username_creates_exactly_one_user(
|
||||
make_settings,
|
||||
):
|
||||
app = create_app(
|
||||
make_settings(max_in_flight=64, db_pool_size=20, db_max_overflow=20)
|
||||
)
|
||||
|
||||
async with make_client(app) as client:
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": "race_user",
|
||||
"display_name": "Race",
|
||||
"password": PASSWORD,
|
||||
},
|
||||
)
|
||||
for _ in range(16)
|
||||
)
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
statuses = Counter(response.status_code for response in responses)
|
||||
assert statuses == Counter({201: 1, 409: 15}), statuses
|
||||
|
||||
|
||||
async def test_100_messages_from_10_clients(make_settings):
|
||||
app = create_app(
|
||||
make_settings(
|
||||
max_messages=1000, max_in_flight=100, db_pool_size=20, db_max_overflow=20
|
||||
)
|
||||
)
|
||||
|
||||
async with make_client(app) as client:
|
||||
users = [
|
||||
await create_user(client, username=f"load_{i}_{uuid4().hex[:6]}")
|
||||
for i in range(10)
|
||||
]
|
||||
created = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(users[0]),
|
||||
json={"title": "Concurrency", "member_ids": [u["id"] for u in users]},
|
||||
)
|
||||
chat = created.json()
|
||||
|
||||
async def worker(index: int, user: dict) -> list[dict]:
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"client-{index}-message-{n}"},
|
||||
)
|
||||
for n in range(10)
|
||||
)
|
||||
)
|
||||
assert all(r.status_code == 201 for r in responses), [
|
||||
r.text for r in responses if r.status_code != 201
|
||||
]
|
||||
return [r.json() for r in responses]
|
||||
|
||||
results = await asyncio.gather(*(worker(i, u) for i, u in enumerate(users)))
|
||||
messages = [m for batch in results for m in batch]
|
||||
|
||||
assert len(messages) == 100
|
||||
assert len({m["id"] for m in messages}) == 100
|
||||
assert Counter(m["sender_id"] for m in messages) == Counter(
|
||||
{u["id"]: 10 for u in users}
|
||||
)
|
||||
|
||||
history = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=bearer(users[0])
|
||||
)
|
||||
items = history.json()["items"]
|
||||
assert len(items) == 100
|
||||
assert len({m["id"] for m in items}) == 100
|
||||
await close_app(app)
|
||||
|
||||
|
||||
async def test_chat_creation_in_parallel_is_atomic(make_settings, db_engine):
|
||||
app = create_app(
|
||||
make_settings(max_in_flight=32, db_pool_size=20, db_max_overflow=20)
|
||||
)
|
||||
|
||||
async with make_client(app) as client:
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": f"c{i}", "member_ids": [alice["id"], bob["id"]]},
|
||||
)
|
||||
for i in range(10)
|
||||
)
|
||||
)
|
||||
assert all(r.status_code == 201 for r in responses)
|
||||
await close_app(app)
|
||||
|
||||
async with db_engine.connect() as connection:
|
||||
chats = (
|
||||
await connection.execute(text("SELECT count(*) FROM chats"))
|
||||
).scalar_one()
|
||||
members = (
|
||||
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
||||
).scalar_one()
|
||||
assert chats == 10 and members == 20
|
||||
|
||||
|
||||
async def test_parallel_registration_of_distinct_usernames_all_succeed(make_settings):
|
||||
app = create_app(make_settings(max_in_flight=64))
|
||||
async with make_client(app) as client:
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": f"distinct_{i}",
|
||||
"display_name": "D",
|
||||
"password": PASSWORD,
|
||||
},
|
||||
)
|
||||
for i in range(12)
|
||||
)
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert [r.status_code for r in responses] == [201] * 12
|
||||
assert len({r.json()["id"] for r in responses}) == 12
|
||||
|
||||
|
||||
async def test_parallel_logins_issue_distinct_valid_tokens(make_settings):
|
||||
app = create_app(make_settings(max_in_flight=64))
|
||||
async with make_client(app) as client:
|
||||
user = await register(client)
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
for _ in range(10)
|
||||
)
|
||||
)
|
||||
tokens = [r.json()["token"] for r in responses]
|
||||
checks = await asyncio.gather(
|
||||
*(
|
||||
client.get(
|
||||
"/api/v1/users/me", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
for token in tokens
|
||||
)
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert all(r.status_code == 201 for r in responses)
|
||||
assert len(set(tokens)) == 10
|
||||
assert all(r.status_code == 200 for r in checks)
|
||||
|
||||
|
||||
async def test_parallel_logout_of_same_token_succeeds_once(make_settings):
|
||||
app = create_app(make_settings(max_in_flight=64))
|
||||
async with make_client(app) as client:
|
||||
session = await create_user(client)
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.delete("/api/v1/auth/sessions/current", headers=bearer(session))
|
||||
for _ in range(10)
|
||||
)
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert Counter(r.status_code for r in responses) == Counter({204: 1, 401: 9})
|
||||
|
||||
|
||||
async def test_message_limit_is_exact_under_concurrency(make_settings, db_engine):
|
||||
app = create_app(
|
||||
make_settings(
|
||||
max_messages=5, max_in_flight=64, db_pool_size=20, db_max_overflow=20
|
||||
)
|
||||
)
|
||||
async with make_client(app) as client:
|
||||
user = await create_user(client)
|
||||
chat = (
|
||||
await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(user),
|
||||
json={"title": "limit", "member_ids": [user["id"]]},
|
||||
)
|
||||
).json()
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"m{i}"},
|
||||
)
|
||||
for i in range(20)
|
||||
)
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert Counter(r.status_code for r in responses) == Counter({201: 5, 503: 15})
|
||||
async with db_engine.connect() as connection:
|
||||
stored = (
|
||||
await connection.execute(text("SELECT count(*) FROM messages"))
|
||||
).scalar_one()
|
||||
counter = (
|
||||
await connection.execute(
|
||||
text("SELECT value FROM counters WHERE name = 'messages'")
|
||||
)
|
||||
).scalar_one()
|
||||
assert stored == counter == 5
|
||||
|
||||
|
||||
async def test_failed_chat_insert_rolls_back_whole_transaction(
|
||||
make_settings, db_engine, monkeypatch
|
||||
):
|
||||
import app.domain.chats as chats_domain
|
||||
|
||||
async def accept_everyone(_session, user_ids):
|
||||
return set(user_ids)
|
||||
|
||||
app = create_app(make_settings())
|
||||
async with make_client(app) as client:
|
||||
alice = await create_user(client)
|
||||
monkeypatch.setattr(
|
||||
chats_domain.users_storage, "get_existing_user_ids", accept_everyone
|
||||
)
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "broken", "member_ids": [alice["id"], str(uuid4())]},
|
||||
)
|
||||
monkeypatch.undo()
|
||||
after = await client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "ok", "member_ids": [alice["id"]]},
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert after.status_code == 201
|
||||
async with db_engine.connect() as connection:
|
||||
titles = (await connection.execute(text("SELECT title FROM chats"))).scalars()
|
||||
members = (
|
||||
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
||||
).scalar_one()
|
||||
assert list(titles) == ["ok"]
|
||||
assert members == 1
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Ограничения на уровне БД: приложение — не единственный защитник данных."""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from helpers import create_chat, create_user
|
||||
|
||||
|
||||
async def test_duplicate_username_is_rejected_by_database(client, db_engine):
|
||||
await create_user(client, username="unique_name")
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (gen_random_uuid(), 'unique_name', 'Other', 'hash')"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def test_message_requires_existing_chat(client, db_engine):
|
||||
alice = await create_user(client)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text) "
|
||||
"VALUES (gen_random_uuid(), gen_random_uuid(), :sender, 'x')"
|
||||
),
|
||||
{"sender": alice["id"]},
|
||||
)
|
||||
|
||||
|
||||
async def test_duplicate_membership_is_rejected_by_database(client, db_engine):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text("INSERT INTO chat_members (chat_id, user_id) VALUES (:c, :u)"),
|
||||
{"c": chat["id"], "u": alice["id"]},
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from helpers import assert_request_id
|
||||
|
||||
|
||||
async def test_missing_token_returns_401(client: AsyncClient):
|
||||
response = await client.get("/api/v1/users/me")
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_garbage_token_returns_401(client: AsyncClient):
|
||||
response = await client.get(
|
||||
"/api/v1/users/me", headers={"Authorization": "Bearer garbage"}
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_malformed_json_returns_400(client: AsyncClient):
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
content='{"username":"alice",',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_not_found_returns_404(client: AsyncClient):
|
||||
response = await client.get("/no-such-path")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_method_not_allowed_preserves_405(client: AsyncClient):
|
||||
response = await client.delete("/api/v1/users")
|
||||
|
||||
assert response.status_code == 405
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_unhandled_exception_is_hidden_from_client(
|
||||
client_no_raise: AsyncClient, caplog
|
||||
):
|
||||
with caplog.at_level(logging.ERROR, logger="app.errors.handlers"):
|
||||
response = await client_no_raise.get("/__test__/explode")
|
||||
|
||||
assert response.status_code == 500
|
||||
payload = response.json()
|
||||
assert payload["error"]["code"] == "internal_error"
|
||||
assert payload["error"]["message"] == "Внутренняя ошибка сервера"
|
||||
assert "test-secret" not in json.dumps(payload, ensure_ascii=False)
|
||||
assert "Traceback" not in json.dumps(payload, ensure_ascii=False)
|
||||
assert "Unhandled error request_id=" in caplog.text
|
||||
assert "test-secret" in caplog.text
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_success_response_contains_request_id(client: AsyncClient):
|
||||
response = await client.get("/health/live")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers.get("X-Request-Id")
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Недоступность Redis и PostgreSQL: ограниченный 503, без анонимного доступа."""
|
||||
|
||||
import time
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import PASSWORD, assert_request_id, basic_header, bearer, create_user
|
||||
|
||||
ME = "/api/v1/users/me"
|
||||
DEAD_DATABASE_URL = "postgresql+asyncpg://nobody:secretpass@127.0.0.1:1/none"
|
||||
|
||||
|
||||
def assert_unavailable(response) -> None:
|
||||
assert response.status_code == 503, response.text
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert "secretpass" not in response.text
|
||||
assert "Traceback" not in response.text
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_redis_down_gives_503_for_login_and_protected_endpoints(make_settings):
|
||||
alive = create_app(make_settings())
|
||||
async with make_client(alive) as client:
|
||||
session = await create_user(client)
|
||||
await close_app(alive)
|
||||
|
||||
app = create_app(make_settings(redis_port=1, redis_connect_timeout_seconds=0.5))
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
started = time.perf_counter()
|
||||
protected = await client.get(ME, headers=bearer(session))
|
||||
elapsed = time.perf_counter() - started
|
||||
|
||||
login = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(session["username"], session["password"]),
|
||||
)
|
||||
logout = await client.delete(
|
||||
"/api/v1/auth/sessions/current", headers=bearer(session)
|
||||
)
|
||||
ready = await client.get("/health/ready")
|
||||
live = await client.get("/health/live")
|
||||
|
||||
await close_app(app)
|
||||
|
||||
for response in (protected, login, logout, ready):
|
||||
assert_unavailable(response)
|
||||
assert live.status_code == 200
|
||||
assert elapsed < 3
|
||||
|
||||
|
||||
async def test_redis_down_keeps_registration_working(make_settings):
|
||||
app = create_app(make_settings(redis_port=1, redis_connect_timeout_seconds=0.5))
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "no_redis", "display_name": "N", "password": PASSWORD},
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert response.status_code == 201
|
||||
|
||||
|
||||
async def test_database_down_with_valid_session_gives_503(make_settings):
|
||||
alive = create_app(make_settings())
|
||||
async with make_client(alive) as client:
|
||||
session = await create_user(client)
|
||||
await close_app(alive)
|
||||
|
||||
app = create_app(
|
||||
make_settings(database_url=DEAD_DATABASE_URL, db_connect_timeout_seconds=1)
|
||||
)
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
protected = await client.get(ME, headers=bearer(session))
|
||||
chats = await client.get("/api/v1/chats", headers=bearer(session))
|
||||
login = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(session["username"], session["password"]),
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
for response in (protected, chats, login):
|
||||
assert_unavailable(response)
|
||||
|
||||
|
||||
async def test_dependency_failure_never_authenticates_anonymous_requests(make_settings):
|
||||
app = create_app(make_settings(redis_port=1, redis_connect_timeout_seconds=0.5))
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
no_token = await client.get(ME)
|
||||
garbage = await client.get(ME, headers={"Authorization": "Bearer garbage"})
|
||||
await close_app(app)
|
||||
|
||||
assert no_token.status_code == 401
|
||||
assert_unavailable(garbage)
|
||||
|
||||
|
||||
async def test_statement_timeout_gives_503(make_settings, monkeypatch):
|
||||
from sqlalchemy import text
|
||||
|
||||
import app.domain.users as users_domain
|
||||
|
||||
async def slow_lookup(session, _username):
|
||||
await session.execute(text("SELECT pg_sleep(1)"))
|
||||
|
||||
app = create_app(make_settings(db_statement_timeout_ms=100))
|
||||
monkeypatch.setattr(users_domain.users_storage, "get_user_by_username", slow_lookup)
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "slow_user", "display_name": "S", "password": PASSWORD},
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert_unavailable(response)
|
||||
assert response.headers["Retry-After"] == "1"
|
||||
|
||||
|
||||
async def test_non_transient_database_error_stays_500(make_settings, monkeypatch):
|
||||
from sqlalchemy import text
|
||||
|
||||
import app.domain.users as users_domain
|
||||
|
||||
async def broken_lookup(session, _username):
|
||||
await session.execute(text("SELECT 1 / 0"))
|
||||
|
||||
app = create_app(make_settings())
|
||||
monkeypatch.setattr(
|
||||
users_domain.users_storage, "get_user_by_username", broken_lookup
|
||||
)
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "broken_user", "display_name": "B", "password": PASSWORD},
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert response.status_code == 500
|
||||
assert response.json()["error"]["code"] == "internal_error"
|
||||
assert "division" not in response.text
|
||||
@@ -0,0 +1,62 @@
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import assert_request_id
|
||||
|
||||
|
||||
async def test_liveness(client: AsyncClient):
|
||||
response = await client.get("/health/live")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_readiness(client: AsyncClient):
|
||||
response = await client.get("/health/ready")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_readiness_is_503_when_database_is_down(make_settings):
|
||||
app = create_app(
|
||||
make_settings(
|
||||
database_url="postgresql+asyncpg://nobody:nopass@127.0.0.1:1/none",
|
||||
db_connect_timeout_seconds=1,
|
||||
)
|
||||
)
|
||||
async with make_client(app) as client:
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
|
||||
ready = await client.get("/health/ready")
|
||||
assert ready.status_code == 503
|
||||
assert ready.json()["error"]["code"] == "unavailable"
|
||||
assert_request_id(ready)
|
||||
await close_app(app)
|
||||
|
||||
|
||||
async def test_business_request_is_503_when_database_is_down(make_settings):
|
||||
app = create_app(
|
||||
make_settings(
|
||||
database_url="postgresql+asyncpg://nobody:secretpass@127.0.0.1:1/none",
|
||||
db_connect_timeout_seconds=1,
|
||||
)
|
||||
)
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": "alice",
|
||||
"display_name": "Alice",
|
||||
"password": "Correct-horse-battery-1",
|
||||
},
|
||||
)
|
||||
await close_app(app)
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert "secretpass" not in response.text
|
||||
assert_request_id(response)
|
||||
@@ -0,0 +1,76 @@
|
||||
"""План запроса истории на >= 10 000 сообщений: индекс без Sort и полного скана."""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
|
||||
from helpers import bearer, create_chat, create_user
|
||||
|
||||
HISTORY_QUERY = """
|
||||
SELECT * FROM messages
|
||||
WHERE chat_id = :chat_id AND (created_at, id) > (:after_created_at, :after_id)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51
|
||||
"""
|
||||
|
||||
|
||||
def walk(node: dict) -> list[dict]:
|
||||
nodes = [node]
|
||||
for child in node.get("Plans", []):
|
||||
nodes.extend(walk(child))
|
||||
return nodes
|
||||
|
||||
|
||||
async def seed_messages(
|
||||
engine: AsyncEngine, chat_id: str, sender_id: str, count: int
|
||||
) -> None:
|
||||
async with engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), :chat_id, :sender_id, 'message ' || g,
|
||||
now() - make_interval(secs => :count - g)
|
||||
FROM generate_series(1, :count) AS g
|
||||
"""),
|
||||
{"chat_id": chat_id, "sender_id": sender_id, "count": count},
|
||||
)
|
||||
await connection.execute(text("ANALYZE messages"))
|
||||
|
||||
|
||||
async def test_history_page_uses_composite_index(client, db_engine: AsyncEngine):
|
||||
alice = await create_user(client)
|
||||
target = await create_chat(client, alice, title="target")
|
||||
noise = await create_chat(client, alice, title="noise")
|
||||
await seed_messages(db_engine, target["id"], alice["id"], 10_000)
|
||||
await seed_messages(db_engine, noise["id"], alice["id"], 10_000)
|
||||
|
||||
middle = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{target['id']}/messages?limit=100", headers=bearer(alice)
|
||||
)
|
||||
).json()["items"][-1]
|
||||
|
||||
async with db_engine.connect() as connection:
|
||||
raw_plan = (
|
||||
await connection.execute(
|
||||
text(f"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {HISTORY_QUERY}"),
|
||||
{
|
||||
"chat_id": UUID(target["id"]),
|
||||
"after_created_at": datetime.fromisoformat(middle["created_at"]),
|
||||
"after_id": UUID(middle["id"]),
|
||||
},
|
||||
)
|
||||
).scalar_one()
|
||||
|
||||
plan = (raw_plan if isinstance(raw_plan, list) else json.loads(raw_plan))[0]["Plan"]
|
||||
nodes = walk(plan)
|
||||
node_types = {node["Node Type"] for node in nodes}
|
||||
index_names = {node.get("Index Name") for node in nodes}
|
||||
|
||||
assert "ix_messages_chat_id_created_at_id" in index_names
|
||||
assert "Sort" not in node_types
|
||||
assert "Seq Scan" not in node_types
|
||||
assert all(node.get("Actual Rows", 0) <= 51 for node in nodes)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Повторы сообщений через приложения с общими хранилищами."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import AsyncExitStack
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.errors.exceptions import unavailable
|
||||
from app.main import create_app
|
||||
from app.storage import idempotency as key_storage
|
||||
from conftest import close_app, make_client
|
||||
from helpers import bearer, create_chat, create_user, idempotency_header, send_message
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def replicas(request, make_settings):
|
||||
overrides = getattr(request, "param", {})
|
||||
apps = [
|
||||
create_app(make_settings(instance_id=name, **overrides))
|
||||
for name in ("api-a", "api-b")
|
||||
]
|
||||
try:
|
||||
async with AsyncExitStack() as stack:
|
||||
clients = [
|
||||
await stack.enter_async_context(make_client(app)) for app in apps
|
||||
]
|
||||
yield clients
|
||||
finally:
|
||||
for app in apps:
|
||||
await close_app(app)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", [None, "", "a b", "a/b", "x" * 129])
|
||||
async def test_invalid_key_returns_400(client, key):
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
headers = bearer(user)
|
||||
if key is not None:
|
||||
headers["Idempotency-Key"] = key
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", headers=headers, json={"text": "hello"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["a", "x" * 128, "key_1.2:3-4"])
|
||||
async def test_valid_key_boundaries(client, key):
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
assert (await send_message(client, user, chat, "hello", key)).status_code == 201
|
||||
|
||||
|
||||
async def test_replay_and_conflict_across_replicas(replicas, db_engine):
|
||||
first, second = replicas
|
||||
user = await create_user(first)
|
||||
chat = await create_chat(first, user)
|
||||
original = await send_message(first, user, chat, "Привет", "same-key")
|
||||
repeated = await second.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={
|
||||
**bearer(user),
|
||||
**idempotency_header("same-key"),
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
content='{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442" }',
|
||||
)
|
||||
conflict = await send_message(second, user, chat, "другой текст", "same-key")
|
||||
assert original.status_code == repeated.status_code == 201
|
||||
assert original.json() == repeated.json()
|
||||
assert original.headers["X-Instance-Id"] != repeated.headers["X-Instance-Id"]
|
||||
assert conflict.status_code == 409
|
||||
async with db_engine.connect() as connection:
|
||||
assert (
|
||||
await connection.execute(text("SELECT count(*) FROM messages"))
|
||||
).scalar_one() == 1
|
||||
assert (
|
||||
await connection.execute(
|
||||
text("SELECT value FROM counters WHERE name='messages'")
|
||||
)
|
||||
).scalar_one() == 1
|
||||
|
||||
|
||||
async def test_parallel_replays_create_one_message(replicas, db_engine):
|
||||
user = await create_user(replicas[0])
|
||||
chat = await create_chat(replicas[0], user)
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
send_message(replicas[index % 2], user, chat, "parallel", "one-key")
|
||||
for index in range(24)
|
||||
)
|
||||
)
|
||||
assert all(response.status_code == 201 for response in responses)
|
||||
assert len({response.json()["id"] for response in responses}) == 1
|
||||
assert {response.headers["X-Instance-Id"] for response in responses} == {
|
||||
"api-a",
|
||||
"api-b",
|
||||
}
|
||||
async with db_engine.connect() as connection:
|
||||
assert (
|
||||
await connection.execute(text("SELECT count(*) FROM messages"))
|
||||
).scalar_one() == 1
|
||||
assert (
|
||||
await connection.execute(text("SELECT count(*) FROM idempotency_keys"))
|
||||
).scalar_one() == 1
|
||||
|
||||
|
||||
async def test_key_scope_separates_users_and_chats(client):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
shared = await create_chat(client, alice, bob)
|
||||
other = await create_chat(client, alice)
|
||||
responses = [
|
||||
await send_message(client, alice, shared, "a", "shared-key"),
|
||||
await send_message(client, bob, shared, "b", "shared-key"),
|
||||
await send_message(client, alice, other, "c", "shared-key"),
|
||||
]
|
||||
assert all(response.status_code == 201 for response in responses)
|
||||
assert len({response.json()["id"] for response in responses}) == 3
|
||||
|
||||
|
||||
async def test_expired_key_can_be_reused_without_removing_message(client, db_engine):
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
first = await send_message(client, user, chat, "old", "expiring-key")
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text(
|
||||
"UPDATE idempotency_keys SET created_at = clock_timestamp() - interval '25 hours'"
|
||||
)
|
||||
)
|
||||
second = await send_message(client, user, chat, "new", "expiring-key")
|
||||
assert first.status_code == second.status_code == 201
|
||||
assert first.json()["id"] != second.json()["id"]
|
||||
history = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages", headers=bearer(user)
|
||||
)
|
||||
assert [item["text"] for item in history.json()["items"]] == ["old", "new"]
|
||||
|
||||
|
||||
async def test_failed_transaction_does_not_poison_key(client, db_engine, monkeypatch):
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
original = key_storage.save_result
|
||||
|
||||
async def fail_after_insert(*args):
|
||||
await original(*args)
|
||||
raise unavailable()
|
||||
|
||||
monkeypatch.setattr(key_storage, "save_result", fail_after_insert)
|
||||
failed = await send_message(client, user, chat, "retry", "retry-key")
|
||||
assert failed.status_code == 503
|
||||
async with db_engine.connect() as connection:
|
||||
for table in ("messages", "idempotency_keys", "counters"):
|
||||
assert (
|
||||
await connection.execute(text(f"SELECT count(*) FROM {table}"))
|
||||
).scalar_one() == 0
|
||||
monkeypatch.setattr(key_storage, "save_result", original)
|
||||
recovered = await send_message(client, user, chat, "retry", "retry-key")
|
||||
assert recovered.status_code == 201
|
||||
|
||||
|
||||
@pytest.mark.parametrize("replicas", [{"max_messages": 1}], indirect=True)
|
||||
async def test_replay_works_when_message_limit_is_full(replicas):
|
||||
user = await create_user(replicas[0])
|
||||
chat = await create_chat(replicas[0], user)
|
||||
first = await send_message(replicas[0], user, chat, "last", "last-key")
|
||||
replay = await send_message(replicas[1], user, chat, "last", "last-key")
|
||||
rejected = await send_message(replicas[1], user, chat, "extra", "other-key")
|
||||
assert first.status_code == replay.status_code == 201
|
||||
assert first.json() == replay.json()
|
||||
assert rejected.status_code == 503
|
||||
|
||||
|
||||
async def test_replay_checks_session_and_membership(client, db_engine):
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
assert (
|
||||
await send_message(client, user, chat, "private", "private-key")
|
||||
).status_code == 201
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(text("DELETE FROM chat_members"))
|
||||
assert (
|
||||
await send_message(client, user, chat, "private", "private-key")
|
||||
).status_code == 404
|
||||
await client.delete("/api/v1/auth/sessions/current", headers=bearer(user))
|
||||
assert (
|
||||
await send_message(client, user, chat, "private", "private-key")
|
||||
).status_code == 401
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Реальные преобразования и OS-лимиты дочернего процесса worker."""
|
||||
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image
|
||||
import pytest
|
||||
|
||||
from app.core.image_processing import ImageSettings
|
||||
from app.domain.image_pipeline import create_variants
|
||||
from app.domain.job_files import render_variants
|
||||
from app.storage.jobs import JobWork
|
||||
from test_attachments import MemoryStorage
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size,transparent", [((1600, 800), False), ((24, 12), True)])
|
||||
async def test_variant_geometry_metadata_and_alpha(tmp_path, size, transparent):
|
||||
source = tmp_path / "source.png"
|
||||
with Image.new("RGBA", size, (255, 0, 0, 0 if transparent else 255)) as image:
|
||||
exif = Image.Exif()
|
||||
exif[270] = "private description"
|
||||
image.save(source, format="PNG", exif=exif)
|
||||
result = create_variants(
|
||||
source, tmp_path, "image/png", 40_000_000, ImageSettings(_env_file=None)
|
||||
)
|
||||
variants = {v.name: v for v in result.variants}
|
||||
assert (variants["crop"].width, variants["crop"].height) == (128, 128)
|
||||
assert (variants["thumbnail"].width, variants["thumbnail"].height) == (
|
||||
(256, 128) if size[0] > 256 else size
|
||||
)
|
||||
assert (variants["optimized"].width, variants["optimized"].height) == (
|
||||
(1280, 640) if size[0] > 1280 else size
|
||||
)
|
||||
for name in ("thumbnail.jpg", "crop.jpg", "optimized.webp"):
|
||||
with Image.open(tmp_path / name) as image:
|
||||
assert (
|
||||
not image.getexif()
|
||||
and not image.info.get("icc_profile")
|
||||
and not image.info.get("xmp")
|
||||
)
|
||||
if transparent:
|
||||
if name.endswith("webp"):
|
||||
assert image.getpixel((0, 0))[3] == 0
|
||||
else:
|
||||
assert min(image.getpixel((0, 0))) >= 250
|
||||
|
||||
|
||||
async def test_exif_orientation_applied(tmp_path):
|
||||
source = tmp_path / "source.jpg"
|
||||
with Image.new("RGB", (400, 200), "blue") as image:
|
||||
exif = Image.Exif()
|
||||
exif[274] = 6
|
||||
image.save(source, exif=exif)
|
||||
result = create_variants(
|
||||
source, tmp_path, "image/jpeg", 40_000_000, ImageSettings(_env_file=None)
|
||||
)
|
||||
assert (result.variants[0].width, result.variants[0].height) == (128, 256)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["memory", "cpu"])
|
||||
async def test_worker_os_limits(failure, tmp_path):
|
||||
body = (
|
||||
"return bytearray(2 * 1024 ** 3)" if failure == "memory" else "while True: pass"
|
||||
)
|
||||
code = (
|
||||
"from app.core import thumbnail_worker as w\ndef fail(*args):\n "
|
||||
+ body
|
||||
+ "\nw.create_variants=fail\nraise SystemExit(w.main())"
|
||||
)
|
||||
result = await asyncio.to_thread(
|
||||
subprocess.run,
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
code,
|
||||
"source",
|
||||
str(tmp_path),
|
||||
str(tmp_path / "metadata"),
|
||||
"image/png",
|
||||
"40000000",
|
||||
],
|
||||
env={**os.environ, "IMAGE_MEMORY_MIB": "256", "IMAGE_CPU_SECONDS": "1"},
|
||||
capture_output=True,
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == (3 if failure == "memory" else -9)
|
||||
assert not (tmp_path / "metadata").exists()
|
||||
|
||||
|
||||
async def test_render_timeout_kills_child(monkeypatch, tmp_path):
|
||||
create = asyncio.create_subprocess_exec
|
||||
children = []
|
||||
|
||||
async def slow_child(*args, **kwargs):
|
||||
child = await create(
|
||||
sys.executable, "-c", "import time;time.sleep(60)", **kwargs
|
||||
)
|
||||
children.append(child)
|
||||
return child
|
||||
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", slow_child)
|
||||
work = JobWork(
|
||||
uuid4(), uuid4(), uuid4(), 1, "staging/test", "image/png", 1, "0" * 64
|
||||
)
|
||||
with pytest.raises(TimeoutError):
|
||||
async with asyncio.timeout(0.2):
|
||||
await render_variants(MemoryStorage(), work, tmp_path / "source", tmp_path)
|
||||
assert len(children) == 1 and children[0].returncode is not None
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Идентификатор реплики и заголовки ответов без PostgreSQL, Redis и Docker."""
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from fastapi import Request
|
||||
|
||||
from app.core.instance import resolve_instance_id
|
||||
from app.errors.exceptions import unavailable
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_db() -> None:
|
||||
"""Заменяет очистку БД из conftest: эти тесты не обращаются к хранилищам."""
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("configured", "expected"),
|
||||
[
|
||||
("api-explicit", "api-explicit"),
|
||||
(" api-explicit ", "api-explicit"),
|
||||
(None, "container-123"),
|
||||
("", "container-123"),
|
||||
(" ", "container-123"),
|
||||
],
|
||||
)
|
||||
def test_resolve_prefers_configured_id_then_hostname(monkeypatch, configured, expected):
|
||||
monkeypatch.setenv("HOSTNAME", " container-123 ")
|
||||
|
||||
assert resolve_instance_id(configured) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hostname", [None, "", " "])
|
||||
def test_resolve_without_config_or_hostname_returns_uuid(monkeypatch, hostname):
|
||||
if hostname is None:
|
||||
monkeypatch.delenv("HOSTNAME", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("HOSTNAME", hostname)
|
||||
|
||||
assert UUID(resolve_instance_id(None)).version == 4
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def instance_client(make_settings):
|
||||
app = create_app(
|
||||
make_settings(
|
||||
instance_id="api-test",
|
||||
database_url="postgresql+asyncpg://unused@127.0.0.1:1/unused",
|
||||
redis_port=1,
|
||||
)
|
||||
)
|
||||
|
||||
@app.get("/__test__/request-id", include_in_schema=False)
|
||||
async def request_id(request: Request) -> dict[str, str]:
|
||||
return {"request_id": request.state.request_id}
|
||||
|
||||
@app.get("/__test__/explode", include_in_schema=False)
|
||||
async def explode() -> None:
|
||||
raise RuntimeError("test error")
|
||||
|
||||
@app.get("/__test__/unavailable", include_in_schema=False)
|
||||
async def dependency_failure() -> None:
|
||||
raise unavailable()
|
||||
|
||||
try:
|
||||
async with make_client(app, raise_app_exceptions=False) as client:
|
||||
yield client
|
||||
finally:
|
||||
await close_app(app)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path", "status"),
|
||||
[
|
||||
("GET", "/health/live", 200),
|
||||
("POST", "/api/v1/users", 400),
|
||||
("GET", "/api/v1/users/me", 401),
|
||||
("GET", "/no-such-path", 404),
|
||||
("DELETE", "/health/live", 405),
|
||||
("GET", "/__test__/explode", 500),
|
||||
("GET", "/__test__/unavailable", 503),
|
||||
],
|
||||
)
|
||||
async def test_instance_header_is_present_on_success_and_errors(
|
||||
instance_client, method, path, status
|
||||
):
|
||||
response = await instance_client.request(method, path)
|
||||
|
||||
assert response.status_code == status
|
||||
assert response.headers["X-Instance-Id"] == "api-test"
|
||||
assert response.headers["X-Request-Id"]
|
||||
if status >= 400:
|
||||
assert (
|
||||
response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
)
|
||||
|
||||
|
||||
async def test_instance_id_is_stable_while_request_ids_are_distinct(instance_client):
|
||||
first = await instance_client.get("/__test__/request-id")
|
||||
second = await instance_client.get("/__test__/request-id")
|
||||
|
||||
assert first.status_code == second.status_code == 200
|
||||
assert (
|
||||
first.headers["X-Instance-Id"] == second.headers["X-Instance-Id"] == "api-test"
|
||||
)
|
||||
assert first.headers["X-Request-Id"] != second.headers["X-Request-Id"]
|
||||
for response in (first, second):
|
||||
assert response.json()["request_id"] == response.headers["X-Request-Id"]
|
||||
@@ -0,0 +1,267 @@
|
||||
"""Retry/replay, fencing, cleanup, limits и транзакции реального PostgreSQL."""
|
||||
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
import errno
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.jobs import JobSettings
|
||||
from app.domain import attachment_jobs
|
||||
from app.domain.attachment_jobs import (
|
||||
claim_job,
|
||||
process_attachment_job,
|
||||
cleanup_staging,
|
||||
build_result,
|
||||
)
|
||||
from app.domain.job_admin import replay_failed_job
|
||||
from app.domain.job_retry import classify_failure, retry_delay
|
||||
from app.errors.exceptions import JobOperationError, ProcessingError
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
from app.models.job_replay import JobReplay
|
||||
from app.schemas.job import JobMessage
|
||||
from app.storage import jobs
|
||||
from test_attachments import context, upload, finish_attachment
|
||||
|
||||
|
||||
async def envelope(session, attachment_id):
|
||||
job = await session.scalar(
|
||||
select(AttachmentJob).where(AttachmentJob.attachment_id == UUID(attachment_id))
|
||||
)
|
||||
return JobMessage(
|
||||
job_id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=1,
|
||||
attempt=job.attempt + 1,
|
||||
created_at=job.created_at,
|
||||
)
|
||||
|
||||
|
||||
async def test_retry_budget_backoff_replay_and_duplicate(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
settings = JobSettings(_env_file=None, job_max_attempts=3)
|
||||
|
||||
def fail(_):
|
||||
raise TimeoutError
|
||||
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
first = await envelope(session, attachment["id"])
|
||||
for attempt in range(1, 4):
|
||||
message = await envelope(session, attachment["id"])
|
||||
assert await process_attachment_job(
|
||||
session, storage, message, settings, before_processing=fail
|
||||
)
|
||||
job, item = await jobs.lock_job(session, first.job_id)
|
||||
assert job.attempt == attempt
|
||||
delay = (job.next_attempt_at - item.updated_at).total_seconds()
|
||||
assert 5 * 2 ** (attempt - 1) / 2 <= delay <= 5 * 2 ** (attempt - 1)
|
||||
assert item.status == ("failed" if attempt == 3 else "queued")
|
||||
assert job.last_error_permanent is False
|
||||
job.next_attempt_at = await jobs.database_time(session) - timedelta(
|
||||
seconds=1
|
||||
)
|
||||
await session.commit()
|
||||
assert item.error_code == "retry_exhausted"
|
||||
request_id = uuid4()
|
||||
result = await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
first.job_id,
|
||||
request_id=request_id,
|
||||
actor="test",
|
||||
reason="dependency_restored",
|
||||
)
|
||||
assert result["attempt_limit"] == 6
|
||||
# Old envelope cannot consume the fresh replay budget.
|
||||
assert await process_attachment_job(session, storage, first, settings)
|
||||
job, item = await jobs.lock_job(session, first.job_id)
|
||||
assert job.attempt == 3 and item.status == "queued"
|
||||
await session.commit()
|
||||
message = await envelope(session, attachment["id"])
|
||||
assert await process_attachment_job(session, storage, message, settings)
|
||||
before = dict(storage.objects)
|
||||
assert await process_attachment_job(session, storage, message, settings)
|
||||
assert storage.objects == before
|
||||
repeat = await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
first.job_id,
|
||||
request_id=request_id,
|
||||
actor="test",
|
||||
reason="dependency_restored",
|
||||
)
|
||||
assert repeat["already_applied"]
|
||||
with pytest.raises(JobOperationError, match="job_not_failed"):
|
||||
await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
first.job_id,
|
||||
request_id=uuid4(),
|
||||
actor="test",
|
||||
reason="manual_review",
|
||||
)
|
||||
await session.rollback()
|
||||
assert len((await session.scalars(select(JobReplay))).all()) == 1
|
||||
|
||||
|
||||
async def test_permanent_failure_and_missing_source_replay(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
|
||||
def fail(_):
|
||||
raise ProcessingError("image_limits")
|
||||
|
||||
settings = JobSettings(_env_file=None)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment["id"])
|
||||
await process_attachment_job(
|
||||
session, storage, message, settings, before_processing=fail
|
||||
)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
assert item.status == "failed" and job.attempt == 1 and job.last_error_permanent
|
||||
job.staging_key = None
|
||||
await session.commit()
|
||||
with pytest.raises(JobOperationError, match="source_expired"):
|
||||
await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
job.id,
|
||||
request_id=uuid4(),
|
||||
actor="test",
|
||||
reason="manual_review",
|
||||
)
|
||||
|
||||
|
||||
async def test_stale_worker_cannot_write_and_cleanup_keeps_active(
|
||||
client, context, db_engine
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
settings = JobSettings(_env_file=None)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment["id"])
|
||||
claim = await claim_job(session, message, settings)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
job.lease_token = uuid4()
|
||||
job.finished_at = await jobs.database_time(session) - timedelta(days=10)
|
||||
await session.commit()
|
||||
assert await cleanup_staging(session, storage, settings, apply=True) == 0
|
||||
# Rendering must not be allowed to PUT on a stale lease.
|
||||
before = dict(storage.objects)
|
||||
assert await build_result(session, storage, claim.work)
|
||||
assert storage.objects == before
|
||||
|
||||
|
||||
async def test_cleanup_ready_preserves_final_objects(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
await finish_attachment(client, storage, alice, attachment["id"])
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment["id"])
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
staging = job.staging_key
|
||||
job.finished_at = await jobs.database_time(session) - timedelta(days=2)
|
||||
await session.commit()
|
||||
assert (
|
||||
await cleanup_staging(
|
||||
session, storage, JobSettings(_env_file=None), apply=False
|
||||
)
|
||||
== 1
|
||||
)
|
||||
assert staging in storage.objects
|
||||
assert (
|
||||
await cleanup_staging(
|
||||
session, storage, JobSettings(_env_file=None), apply=True
|
||||
)
|
||||
== 1
|
||||
)
|
||||
assert staging not in storage.objects and len(storage.objects) == 4
|
||||
assert (
|
||||
await cleanup_staging(
|
||||
session, storage, JobSettings(_env_file=None), apply=True
|
||||
)
|
||||
== 0
|
||||
)
|
||||
|
||||
|
||||
async def test_retry_classification_and_cap():
|
||||
settings = JobSettings(_env_file=None)
|
||||
for attempt in (1, 2, 6, 100):
|
||||
cap = min(120, 5 * 2 ** min(30, attempt - 1))
|
||||
assert all(cap / 2 <= retry_delay(settings, attempt) <= cap for _ in range(100))
|
||||
assert classify_failure(TimeoutError()) == ("processing_timeout", False)
|
||||
assert classify_failure(OSError(errno.EACCES, "denied"))[1]
|
||||
assert not classify_failure(OSError(errno.ENOSPC, "full"))[1]
|
||||
|
||||
|
||||
async def test_timeout_records_retry_and_clears_lease(
|
||||
client, context, db_engine, monkeypatch
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
|
||||
async def stalled(*args, **kwargs):
|
||||
await asyncio.sleep(60)
|
||||
|
||||
monkeypatch.setattr(attachment_jobs, "build_result", stalled)
|
||||
settings = JobSettings(_env_file=None).model_copy(
|
||||
update={"job_timeout_seconds": 0.05}
|
||||
)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment["id"])
|
||||
assert await process_attachment_job(session, storage, message, settings)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
assert item.status == "queued" and job.last_error_code == "processing_timeout"
|
||||
assert job.lease_token is None and job.lease_until is None
|
||||
|
||||
|
||||
async def test_failed_retention_and_source_checksum_protect_replay(
|
||||
client, context, db_engine
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
|
||||
def fail(_):
|
||||
raise ProcessingError("invalid_image")
|
||||
|
||||
settings = JobSettings(_env_file=None)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment["id"])
|
||||
await process_attachment_job(
|
||||
session, storage, message, settings, before_processing=fail
|
||||
)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
key = job.staging_key
|
||||
job.finished_at = await jobs.database_time(session) - timedelta(days=2)
|
||||
await session.commit()
|
||||
assert await cleanup_staging(session, storage, settings, apply=True) == 0
|
||||
data, metadata = storage.objects[key]
|
||||
storage.objects[key] = (b"x" * len(data), metadata)
|
||||
with pytest.raises(JobOperationError, match="source_mismatch"):
|
||||
await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
message.job_id,
|
||||
request_id=uuid4(),
|
||||
actor="test",
|
||||
reason="manual_review",
|
||||
)
|
||||
await session.rollback()
|
||||
assert not (await session.scalars(select(JobReplay))).all()
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
job.finished_at = await jobs.database_time(session) - timedelta(days=8)
|
||||
await session.commit()
|
||||
assert await cleanup_staging(session, storage, settings, apply=True) == 1
|
||||
assert key not in storage.objects
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Готовность при завершении и ограничение времени проверки зависимостей."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from app.domain import health
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_db() -> None:
|
||||
"""Эти проверки не обращаются к хранилищам."""
|
||||
|
||||
|
||||
async def test_draining_keeps_liveness_but_rejects_new_work(make_settings):
|
||||
app = create_app(make_settings())
|
||||
app.state.lifecycle.start_draining()
|
||||
try:
|
||||
async with make_client(app) as client:
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
assert (await client.get("/health/ready")).status_code == 503
|
||||
assert (await client.get("/api/v1/users/me")).status_code == 503
|
||||
finally:
|
||||
await close_app(app)
|
||||
|
||||
|
||||
async def test_readiness_timeout_cancels_dependency_checks(make_settings, monkeypatch):
|
||||
cancelled = []
|
||||
|
||||
async def stalled(_):
|
||||
try:
|
||||
await asyncio.sleep(30)
|
||||
finally:
|
||||
cancelled.append(True)
|
||||
|
||||
monkeypatch.setattr(health, "check_database", stalled)
|
||||
monkeypatch.setattr(health, "check_redis", stalled)
|
||||
app = create_app(make_settings(readiness_timeout_seconds=0.03))
|
||||
try:
|
||||
async with make_client(app) as client:
|
||||
started = time.monotonic()
|
||||
response = await client.get("/health/ready")
|
||||
assert response.status_code == 503
|
||||
assert time.monotonic() - started < 1
|
||||
assert len(cancelled) == 2
|
||||
finally:
|
||||
await close_app(app)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Ограничения нагрузки: MAX_IN_FLIGHT -> 429, MAX_MESSAGES -> 503."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import (
|
||||
assert_request_id,
|
||||
bearer,
|
||||
create_chat,
|
||||
create_user,
|
||||
idempotency_header,
|
||||
)
|
||||
|
||||
|
||||
def _assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
assert response.status_code == status
|
||||
body = response.json()
|
||||
assert body["error"]["code"] == code
|
||||
assert response.headers.get("X-Request-Id") == body["error"]["request_id"]
|
||||
|
||||
|
||||
async def test_message_limit_rejects_without_deleting_confirmed_messages(make_settings):
|
||||
app = create_app(make_settings(max_messages=2))
|
||||
async with make_client(app) as client:
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
for index in range(2):
|
||||
ok = await client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"confirmed-{index}"},
|
||||
)
|
||||
assert ok.status_code == 201
|
||||
|
||||
rejected = await client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": "rejected"},
|
||||
)
|
||||
_assert_error(rejected, 503, "unavailable")
|
||||
|
||||
history = await client.get(f"{url}?limit=100", headers=bearer(user))
|
||||
assert history.status_code == 200
|
||||
assert [m["text"] for m in history.json()["items"]] == [
|
||||
"confirmed-0",
|
||||
"confirmed-1",
|
||||
]
|
||||
await close_app(app)
|
||||
|
||||
|
||||
async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypatch):
|
||||
import app.endpoints.messages as message_endpoint
|
||||
|
||||
app = create_app(make_settings(max_in_flight=2))
|
||||
|
||||
original_send_message = message_endpoint.send_message_idempotent
|
||||
accepted_count = 0
|
||||
all_slots_taken = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def blocking_send_message(*args, **kwargs):
|
||||
nonlocal accepted_count
|
||||
accepted_count += 1
|
||||
if accepted_count == 2:
|
||||
all_slots_taken.set()
|
||||
await asyncio.wait_for(release.wait(), timeout=5)
|
||||
return await original_send_message(*args, **kwargs)
|
||||
|
||||
async with make_client(app, timeout=10) as client:
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
|
||||
monkeypatch.setattr(
|
||||
message_endpoint, "send_message_idempotent", blocking_send_message
|
||||
)
|
||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
held = [
|
||||
asyncio.create_task(
|
||||
client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"held-{i}"},
|
||||
)
|
||||
)
|
||||
for i in range(2)
|
||||
]
|
||||
|
||||
await asyncio.wait_for(all_slots_taken.wait(), timeout=2)
|
||||
|
||||
rejected = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"rejected-{i}"},
|
||||
)
|
||||
for i in range(4)
|
||||
)
|
||||
)
|
||||
for response in rejected:
|
||||
_assert_error(response, 429, "rate_limited")
|
||||
assert response.headers.get("Retry-After") == "1"
|
||||
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
|
||||
release.set()
|
||||
assert all(r.status_code == 201 for r in await asyncio.gather(*held))
|
||||
|
||||
recovered = await client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": "after"},
|
||||
)
|
||||
assert recovered.status_code == 201
|
||||
assert_request_id(recovered)
|
||||
await close_app(app)
|
||||
@@ -0,0 +1,238 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from helpers import (
|
||||
assert_request_id,
|
||||
bearer,
|
||||
create_chat,
|
||||
create_user,
|
||||
idempotency_header,
|
||||
send_message,
|
||||
)
|
||||
|
||||
|
||||
async def _message(client: AsyncClient, user: dict, chat: dict, text: str):
|
||||
return await send_message(client, user, chat, text)
|
||||
|
||||
|
||||
async def test_send_and_list_message(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
chat = await create_chat(client, alice, bob)
|
||||
|
||||
created = await _message(client, alice, chat, "Привет, мир 👋")
|
||||
|
||||
assert created.status_code == 201
|
||||
message = created.json()
|
||||
assert message["sender_id"] == alice["id"]
|
||||
assert message["chat_id"] == chat["id"]
|
||||
assert_request_id(created)
|
||||
|
||||
listed = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1",
|
||||
headers=bearer(bob),
|
||||
)
|
||||
|
||||
assert listed.status_code == 200
|
||||
assert listed.json()["items"] == [message]
|
||||
assert listed.json()["next_cursor"] is None
|
||||
assert_request_id(listed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", "x" * 4001])
|
||||
async def test_invalid_message_text(client: AsyncClient, text: str):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
|
||||
response = await _message(client, alice, chat, text)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_extra_message_field_is_rejected(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={**bearer(alice), **idempotency_header()},
|
||||
json={"text": "hello", "sender_id": alice["id"]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_messages_are_private_to_chat_members(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
eve = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
await _message(client, alice, chat, "секрет")
|
||||
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=bearer(eve),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_pagination_has_no_duplicates(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
|
||||
created = [
|
||||
(await _message(client, alice, chat, f"message-{index}")).json()
|
||||
for index in range(5)
|
||||
]
|
||||
|
||||
page1 = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=2",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
page2 = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
page3 = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
|
||||
ids = [item["id"] for page in (page1, page2, page3) for item in page["items"]]
|
||||
assert ids == [item["id"] for item in created]
|
||||
assert len(ids) == len(set(ids)) == 5
|
||||
assert len(page1["items"]) == 2
|
||||
assert len(page2["items"]) == 2
|
||||
assert len(page3["items"]) == 1
|
||||
assert page3["next_cursor"] is None
|
||||
|
||||
|
||||
async def test_cursor_cannot_be_used_for_another_chat(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat_a = await create_chat(client, alice, title="A")
|
||||
chat_b = await create_chat(client, alice, title="B")
|
||||
|
||||
await _message(client, alice, chat_a, "a1")
|
||||
await _message(client, alice, chat_a, "a2")
|
||||
await _message(client, alice, chat_b, "b1")
|
||||
await _message(client, alice, chat_b, "b2")
|
||||
|
||||
page = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat_a['id']}/messages?limit=1",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat_b['id']}/messages?limit=1&cursor={quote(page['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"limit, expected_status", [(0, 400), (1, 200), (100, 200), (101, 400)]
|
||||
)
|
||||
async def test_limit_boundaries(client: AsyncClient, limit: int, expected_status: int):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
await _message(client, alice, chat, "one")
|
||||
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit={limit}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == expected_status
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_message_exact_max_length_is_accepted(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
|
||||
response = await _message(client, alice, chat, "x" * 4000)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert len(response.json()["text"]) == 4000
|
||||
|
||||
|
||||
async def test_nonexistent_chat_messages_return_404(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
|
||||
response = await client.get(
|
||||
"/api/v1/chats/00000000-0000-4000-8000-000000000000/messages",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_unauthenticated_requests_are_rejected(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
assert (await client.get(url)).status_code == 401
|
||||
assert (await client.post(url, json={"text": "hi"})).status_code == 401
|
||||
|
||||
|
||||
async def test_messages_survive_new_login(client: AsyncClient):
|
||||
"""Сообщения принадлежат пользователю, а не сессии: после logout/login видны."""
|
||||
from helpers import login
|
||||
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
message = (await _message(client, alice, chat, "до выхода")).json()
|
||||
await client.delete("/api/v1/auth/sessions/current", headers=bearer(alice))
|
||||
|
||||
alice_again = await login(client, alice)
|
||||
listed = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages", headers=bearer(alice_again)
|
||||
)
|
||||
|
||||
assert listed.json()["items"] == [message]
|
||||
|
||||
|
||||
async def test_history_order_is_created_at_then_id(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
created = [(await _message(client, alice, chat, f"m{i}")).json() for i in range(10)]
|
||||
|
||||
listed = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=bearer(alice)
|
||||
)
|
||||
).json()["items"]
|
||||
|
||||
assert [m["id"] for m in listed] == [m["id"] for m in created]
|
||||
keys = [(m["created_at"], m["id"]) for m in listed]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
async def test_nul_in_message_text_is_rejected(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
|
||||
response = await _message(client, alice, chat, "hello\u0000world")
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Миграции: применение с нуля, идемпотентный повтор, совпадение со схемой моделей."""
|
||||
|
||||
import pytest
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from app.models import Base
|
||||
from conftest import reset_schema, upgrade_head
|
||||
|
||||
EXPECTED_TABLES = {
|
||||
"users",
|
||||
"chats",
|
||||
"chat_members",
|
||||
"messages",
|
||||
"counters",
|
||||
"idempotency_keys",
|
||||
"attachments",
|
||||
"message_attachments",
|
||||
"upload_intents",
|
||||
"attachment_jobs",
|
||||
"job_replays",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def migrated_engine(database_url, db_engine):
|
||||
await reset_schema(db_engine)
|
||||
await upgrade_head(database_url)
|
||||
yield db_engine
|
||||
|
||||
await reset_schema(db_engine)
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
|
||||
|
||||
async def test_upgrade_creates_all_tables(migrated_engine):
|
||||
async with migrated_engine.connect() as connection:
|
||||
tables = await connection.run_sync(
|
||||
lambda sync: set(inspect(sync).get_table_names())
|
||||
)
|
||||
assert EXPECTED_TABLES <= tables
|
||||
|
||||
|
||||
async def test_upgrade_twice_is_idempotent_and_keeps_data(
|
||||
migrated_engine, database_url
|
||||
):
|
||||
async with migrated_engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (gen_random_uuid(), 'keep_me', 'Keep', 'hash')"
|
||||
)
|
||||
)
|
||||
|
||||
await upgrade_head(database_url)
|
||||
|
||||
async with migrated_engine.connect() as connection:
|
||||
count = (
|
||||
await connection.execute(
|
||||
text("SELECT count(*) FROM users WHERE username = 'keep_me'")
|
||||
)
|
||||
).scalar_one()
|
||||
assert count == 1
|
||||
|
||||
|
||||
async def test_models_and_migrations_are_in_sync(migrated_engine):
|
||||
def compare(sync_connection):
|
||||
context = MigrationContext.configure(
|
||||
sync_connection, opts={"compare_type": True}
|
||||
)
|
||||
return compare_metadata(context, Base.metadata)
|
||||
|
||||
async with migrated_engine.connect() as connection:
|
||||
diff = await connection.run_sync(compare)
|
||||
|
||||
assert (
|
||||
diff == []
|
||||
), f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Курсоры: непрозрачность, привязка к ресурсу и устойчивость к подделке."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from helpers import bearer, create_chat, create_user, send_message
|
||||
|
||||
|
||||
def forged_cursor(**payload: str) -> str:
|
||||
return base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cursor",
|
||||
[
|
||||
"not-base64-%%%",
|
||||
base64.urlsafe_b64encode(b"not json").decode(),
|
||||
base64.urlsafe_b64encode(b"[1, 2, 3]").decode(),
|
||||
forged_cursor(kind="messages"),
|
||||
],
|
||||
)
|
||||
async def test_garbage_cursor_returns_400(client: AsyncClient, cursor: str):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
|
||||
for url in (
|
||||
f"/api/v1/chats?cursor={quote(cursor, safe='')}",
|
||||
f"/api/v1/chats/{chat['id']}/messages?cursor={quote(cursor, safe='')}",
|
||||
):
|
||||
response = await client.get(url, headers=bearer(alice))
|
||||
assert response.status_code == 400, url
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_cursor_without_timezone_is_rejected(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
cursor = forged_cursor(
|
||||
kind="chats",
|
||||
resource_id=alice["id"],
|
||||
created_at="2026-01-01T00:00:00",
|
||||
item_id="00000000-0000-4000-8000-000000000000",
|
||||
)
|
||||
|
||||
response = await client.get(
|
||||
f"/api/v1/chats?cursor={quote(cursor, safe='')}", headers=bearer(alice)
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
async def test_chat_list_cursor_is_bound_to_its_owner(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
for index in range(2):
|
||||
await create_chat(client, alice, bob, title=f"shared-{index}")
|
||||
|
||||
page = (await client.get("/api/v1/chats?limit=1", headers=bearer(alice))).json()
|
||||
response = await client.get(
|
||||
f"/api/v1/chats?limit=1&cursor={quote(page['next_cursor'], safe='')}",
|
||||
headers=bearer(bob),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
async def test_messages_cursor_is_not_accepted_by_chat_list(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
for index in range(2):
|
||||
await send_message(client, alice, chat, f"m{index}")
|
||||
|
||||
page = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=bearer(alice)
|
||||
)
|
||||
).json()
|
||||
response = await client.get(
|
||||
f"/api/v1/chats?cursor={quote(page['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
async def test_limit_can_change_between_pages(client: AsyncClient):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
sent = [
|
||||
(await send_message(client, alice, chat, f"m{index}")).json()
|
||||
for index in range(6)
|
||||
]
|
||||
|
||||
first = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=bearer(alice)
|
||||
)
|
||||
).json()
|
||||
rest = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100"
|
||||
f"&cursor={quote(first['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
|
||||
assert [m["id"] for m in first["items"] + rest["items"]] == [m["id"] for m in sent]
|
||||
assert rest["next_cursor"] is None
|
||||
|
||||
|
||||
async def test_message_sent_after_reading_last_page_is_seen_with_cursor(
|
||||
client: AsyncClient,
|
||||
):
|
||||
alice = await create_user(client)
|
||||
chat = await create_chat(client, alice)
|
||||
await send_message(client, alice, chat, "first")
|
||||
await send_message(client, alice, chat, "second")
|
||||
|
||||
page = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=bearer(alice)
|
||||
)
|
||||
).json()
|
||||
new = (await send_message(client, alice, chat, "third")).json()
|
||||
rest = (
|
||||
await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100"
|
||||
f"&cursor={quote(page['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
).json()
|
||||
|
||||
assert [m["text"] for m in rest["items"]] == ["second", "third"]
|
||||
assert rest["items"][-1] == new
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Освобождение HTTP-соединения и порядок завершения SDK при отмене."""
|
||||
|
||||
import asyncio
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.core.s3 import S3Settings
|
||||
from app.storage.s3 import ObjectStream, run_sync
|
||||
|
||||
|
||||
async def test_sdk_thread_finishes_before_cancellation_returns():
|
||||
entered, release, finished = Event(), Event(), Event()
|
||||
|
||||
def operation():
|
||||
entered.set()
|
||||
release.wait(timeout=3)
|
||||
finished.set()
|
||||
|
||||
task = asyncio.create_task(run_sync(operation))
|
||||
await asyncio.to_thread(entered.wait, 2)
|
||||
task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not task.done()
|
||||
release.set()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
assert finished.is_set()
|
||||
|
||||
|
||||
async def test_response_discarded_when_get_is_cancelled():
|
||||
entered, release = Event(), Event()
|
||||
discarded = []
|
||||
response = object()
|
||||
|
||||
def operation():
|
||||
entered.set()
|
||||
release.wait(timeout=3)
|
||||
return response
|
||||
|
||||
task = asyncio.create_task(run_sync(operation, discard_result=discarded.append))
|
||||
await asyncio.to_thread(entered.wait, 2)
|
||||
task.cancel()
|
||||
release.set()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
assert discarded == [response]
|
||||
|
||||
|
||||
async def test_stream_closes_even_before_first_iteration():
|
||||
calls = []
|
||||
response = SimpleNamespace(
|
||||
close=lambda: calls.append("close"),
|
||||
release_conn=lambda: calls.append("release"),
|
||||
)
|
||||
storage = SimpleNamespace(settings=S3Settings(_env_file=None))
|
||||
stream = ObjectStream(storage, response)
|
||||
await stream.aclose()
|
||||
await stream.aclose()
|
||||
assert calls == ["close", "release"]
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Сессии в Redis: TTL, абсолютный срок, отзыв, потеря и перезапуск хранилища."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from redis.asyncio import Redis
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import basic_header, bearer, create_user, register
|
||||
|
||||
ME = "/api/v1/users/me"
|
||||
LOGOUT = "/api/v1/auth/sessions/current"
|
||||
|
||||
|
||||
def session_key(token: str) -> str:
|
||||
return "session:" + hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
async def test_session_key_ttl_matches_expires_at(
|
||||
client: AsyncClient, redis_client: Redis
|
||||
):
|
||||
user = await register(client)
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
body = response.json()
|
||||
|
||||
expires_at = datetime.fromisoformat(body["expires_at"])
|
||||
expire_time_ms = await redis_client.pexpiretime(session_key(body["token"]))
|
||||
|
||||
assert abs(expire_time_ms - expires_at.timestamp() * 1000) < 2
|
||||
assert 299_000 < await redis_client.pttl(session_key(body["token"])) <= 300_000
|
||||
|
||||
|
||||
async def test_session_ttl_is_absolute_and_not_extended_by_activity(
|
||||
client: AsyncClient, redis_client: Redis
|
||||
):
|
||||
session = await create_user(client)
|
||||
key = session_key(session["token"])
|
||||
expire_before = await redis_client.pexpiretime(key)
|
||||
|
||||
for _ in range(5):
|
||||
assert (await client.get(ME, headers=bearer(session))).status_code == 200
|
||||
|
||||
assert await redis_client.pexpiretime(key) == expire_before
|
||||
|
||||
|
||||
async def test_logout_removes_session_key(client: AsyncClient, redis_client: Redis):
|
||||
session = await create_user(client)
|
||||
key = session_key(session["token"])
|
||||
assert await redis_client.exists(key) == 1
|
||||
|
||||
assert (await client.delete(LOGOUT, headers=bearer(session))).status_code == 204
|
||||
|
||||
assert await redis_client.exists(key) == 0
|
||||
assert (await client.get(ME, headers=bearer(session))).status_code == 401
|
||||
|
||||
|
||||
async def test_expired_session_is_rejected_everywhere(make_settings):
|
||||
app = create_app(make_settings(session_ttl_seconds=1))
|
||||
async with make_client(app) as client:
|
||||
session = await create_user(client)
|
||||
assert (await client.get(ME, headers=bearer(session))).status_code == 200
|
||||
|
||||
await asyncio.sleep(1.5)
|
||||
|
||||
for method, url in (("GET", ME), ("GET", "/api/v1/chats"), ("DELETE", LOGOUT)):
|
||||
response = await client.request(method, url, headers=bearer(session))
|
||||
assert response.status_code == 401, (method, url)
|
||||
assert response.headers["WWW-Authenticate"].startswith("Bearer")
|
||||
await close_app(app)
|
||||
|
||||
|
||||
async def test_relogin_after_expiry_issues_new_working_token(make_settings):
|
||||
app = create_app(make_settings(session_ttl_seconds=1))
|
||||
async with make_client(app) as client:
|
||||
user = await register(client)
|
||||
first = (
|
||||
await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
).json()
|
||||
await asyncio.sleep(1.5)
|
||||
second = (
|
||||
await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
).json()
|
||||
|
||||
assert first["token"] != second["token"]
|
||||
assert (await client.get(ME, headers=bearer(first))).status_code == 401
|
||||
assert (await client.get(ME, headers=bearer(second))).status_code == 200
|
||||
await close_app(app)
|
||||
|
||||
|
||||
async def test_tampered_token_is_rejected(client: AsyncClient):
|
||||
session = await create_user(client)
|
||||
token = session["token"]
|
||||
tampered = token[:-1] + ("A" if token[-1] != "A" else "B")
|
||||
|
||||
response = await client.get(ME, headers={"Authorization": f"Bearer {tampered}"})
|
||||
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
async def test_session_of_deleted_user_is_rejected(client: AsyncClient, db_engine):
|
||||
from sqlalchemy import text
|
||||
|
||||
session = await create_user(client)
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text("DELETE FROM users WHERE id = :id"), {"id": session["id"]}
|
||||
)
|
||||
|
||||
response = await client.get(ME, headers=bearer(session))
|
||||
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
async def test_redis_flush_invalidates_all_sessions(
|
||||
client: AsyncClient, redis_client: Redis
|
||||
):
|
||||
alice = await create_user(client)
|
||||
bob = await create_user(client)
|
||||
|
||||
await redis_client.flushdb()
|
||||
|
||||
for session in (alice, bob):
|
||||
assert (await client.get(ME, headers=bearer(session))).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("DOCKER_TESTS") != "1",
|
||||
reason="перезапускает контейнер redis из compose; включается DOCKER_TESTS=1",
|
||||
)
|
||||
async def test_sessions_survive_redis_restart(client: AsyncClient, redis_client: Redis):
|
||||
active = await create_user(client)
|
||||
revoked = await create_user(client)
|
||||
assert (await client.delete(LOGOUT, headers=bearer(revoked))).status_code == 204
|
||||
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"docker",
|
||||
"compose",
|
||||
"restart",
|
||||
"redis",
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
assert await process.wait() == 0
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
await redis_client.ping()
|
||||
break
|
||||
except Exception:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
response = await client.get(ME, headers=bearer(active))
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == active["id"]
|
||||
assert (await client.get(ME, headers=bearer(revoked))).status_code == 401
|
||||
@@ -0,0 +1,128 @@
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from helpers import PASSWORD, assert_request_id, bearer, create_user, register
|
||||
|
||||
|
||||
async def test_register_does_not_leak_password(client: AsyncClient):
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "alice", "display_name": "Алиса 👋", "password": PASSWORD},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
body = response.json()
|
||||
assert set(body) == {"id", "username", "display_name", "created_at"}
|
||||
assert PASSWORD not in response.text
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_get_current_user(client: AsyncClient):
|
||||
user = await create_user(client, display_name="Алиса 👋")
|
||||
|
||||
response = await client.get("/api/v1/users/me", headers=bearer(user))
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == user["id"]
|
||||
assert response.json()["username"] == user["username"]
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"username": "alice", "display_name": "", "password": PASSWORD},
|
||||
{"username": "alice", "display_name": " ", "password": PASSWORD},
|
||||
{"username": "alice", "display_name": "a" * 101, "password": PASSWORD},
|
||||
{"username": "ab", "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "alice-123", "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "AlicE", "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "a" * 33, "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "alice", "display_name": "Alice"},
|
||||
{"username": "alice", "display_name": "Alice", "password": "x" * 11},
|
||||
{"username": "alice", "display_name": "Alice", "password": "x" * 129},
|
||||
],
|
||||
)
|
||||
async def test_invalid_user_payloads(client: AsyncClient, body: dict):
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_password_length_boundaries_are_accepted(client: AsyncClient):
|
||||
for index, password in enumerate(
|
||||
["x" * 12, "y" * 128, "п" * 12, " spaces inside "]
|
||||
):
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": f"pw_user_{index}",
|
||||
"display_name": "Alice",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 201, (index, response.text)
|
||||
|
||||
|
||||
async def test_extra_user_field_is_rejected(client: AsyncClient):
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": "alice",
|
||||
"display_name": "Alice",
|
||||
"password": PASSWORD,
|
||||
"extra": True,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_duplicate_username_returns_conflict(client: AsyncClient):
|
||||
user = await register(client, username="duplicate_user")
|
||||
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": user["username"],
|
||||
"display_name": "Другой",
|
||||
"password": PASSWORD,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 409
|
||||
assert response.json()["error"]["code"] == "conflict"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
async def test_user_exact_length_boundaries_are_accepted(client: AsyncClient):
|
||||
for length in (3, 32):
|
||||
user = await register(client, username=("a" * length), display_name="d" * 100)
|
||||
assert len(user["username"]) == length
|
||||
assert len(user["display_name"]) == 100
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", [" " * 12, "\t" * 12, " \n" * 6])
|
||||
async def test_whitespace_only_password_is_rejected(client: AsyncClient, password: str):
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "blank_pw", "display_name": "Blank", "password": password},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["display_name", "password"])
|
||||
async def test_nul_in_user_fields_is_rejected(client: AsyncClient, field: str):
|
||||
body = {"username": "nul_user", "display_name": "Nul", "password": PASSWORD}
|
||||
body[field] = body[field] + "\u0000tail"
|
||||
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
Reference in New Issue
Block a user