feat: перенос логики с 4лабф
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
auth,
|
||||
basic,
|
||||
message_headers,
|
||||
png_bytes,
|
||||
unique_password,
|
||||
unique_username,
|
||||
upload_raw,
|
||||
)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
|
||||
|
||||
REQUEST_TIMEOUT_SEC = 10
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def base_url() -> str:
|
||||
return os.environ.get("BASE_URL") or DEFAULT_BASE_URL
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def api(base_url: str) -> Iterator[httpx.Client]:
|
||||
with httpx.Client(base_url=base_url, timeout=REQUEST_TIMEOUT_SEC) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def register_and_login(
|
||||
client: httpx.Client, label: str, display_name: str | None = None
|
||||
) -> dict:
|
||||
"""Регистрация и вход; в словаре User плюс token и password для тестов"""
|
||||
username = unique_username(label)
|
||||
password = unique_password()
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": display_name or f"Студент {label}",
|
||||
"password": password,
|
||||
}
|
||||
response = client.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201, response.text
|
||||
user = response.json()
|
||||
session = client.post("/api/v1/auth/sessions", headers=basic(username, password))
|
||||
assert session.status_code == 201, session.text
|
||||
return {**user, "token": session.json()["token"], "password": password}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_user(api: httpx.Client) -> Callable[..., dict]:
|
||||
def create(label: str = "user", display_name: str | None = None) -> dict:
|
||||
return register_and_login(api, label, display_name)
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_chat(api: httpx.Client) -> Callable[..., dict]:
|
||||
def create(owner: dict, members: list[dict], title: str = "Тестовый чат") -> dict:
|
||||
body = {"title": title, "member_ids": [member["id"] for member in members]}
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(owner))
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def send_message(api: httpx.Client) -> Callable[..., dict]:
|
||||
def send(user: dict, chat: dict, text: str) -> dict:
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
return send
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def upload(api: httpx.Client) -> Callable[..., dict]:
|
||||
"""Успешная загрузка вложения: 201 и Attachment"""
|
||||
|
||||
def create(
|
||||
user: dict,
|
||||
chat: dict,
|
||||
content: bytes | None = None,
|
||||
content_type: str = "image/png",
|
||||
filename: str = "image.png",
|
||||
) -> dict:
|
||||
response = upload_raw(
|
||||
api, user, chat["id"], content or png_bytes(), content_type, filename
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def send_attachments(api: httpx.Client) -> Callable[..., httpx.Response]:
|
||||
"""POST сообщения с attachment_ids; ответ не проверяется"""
|
||||
|
||||
def send(
|
||||
user: dict,
|
||||
chat: dict,
|
||||
attachment_ids: list[str],
|
||||
text: str = "",
|
||||
key: str | None = None,
|
||||
) -> httpx.Response:
|
||||
return api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text, "attachment_ids": attachment_ids},
|
||||
headers=message_headers(user, key),
|
||||
)
|
||||
|
||||
return send
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Общие проверки для собственных black-box тестов"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import io
|
||||
import struct
|
||||
import subprocess
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
USER_FIELDS = ("id", "username", "display_name", "created_at")
|
||||
|
||||
|
||||
def unique_username(label: str) -> str:
|
||||
return f"st_{label}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def unique_password() -> str:
|
||||
return f"Pw-{uuid.uuid4().hex}"
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
"""Authorization: Basic; пароль кодируется в UTF-8"""
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
||||
|
||||
|
||||
def auth(user: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {user['token']}"}
|
||||
|
||||
|
||||
def message_headers(user: dict, key: str | None = None) -> dict[str, str]:
|
||||
"""Bearer и Idempotency-Key (новый, если не задан)"""
|
||||
return {**auth(user), "Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
def public_user(user: dict) -> dict:
|
||||
"""User из ответа API без тестовых полей token/password"""
|
||||
return {field: user[field] for field in USER_FIELDS}
|
||||
|
||||
|
||||
def assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
"""Код ответа и единый формат ошибки: request_id совпадает с заголовком"""
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
error = response.json()["error"]
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def assert_unauthorized(response: httpx.Response, scheme: str = "Bearer") -> None:
|
||||
"""401 с challenge нужной схемы"""
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert response.headers["WWW-Authenticate"].startswith(scheme)
|
||||
|
||||
|
||||
def read_all_messages(
|
||||
api: httpx.Client, user: dict, chat_id: str, limit: int
|
||||
) -> tuple[list[dict], int]:
|
||||
"""Обход истории по next_cursor; возвращает сообщения и число страниц"""
|
||||
items: list[dict] = []
|
||||
pages = 0
|
||||
params: dict[str, str | int] = {"limit": limit}
|
||||
while True:
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_id}/messages", params=params, headers=auth(user)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
items.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
return items, pages
|
||||
params = {"limit": limit, "cursor": page["next_cursor"]}
|
||||
|
||||
|
||||
def compose(*args: str, stdin: str | None = None) -> str:
|
||||
"""docker compose из корня репозитория; вывод не печатается (может быть секретен)"""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
"""Запрос в PostgreSQL стенда изнутри контейнера; порт БД наружу не открыт"""
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
stdin=sql,
|
||||
).strip()
|
||||
|
||||
|
||||
# --- Изображения и вложения (lab4) ---
|
||||
|
||||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
MAX_IMAGE_PIXELS = 40_000_000
|
||||
FIXTURE_PNG = ROOT / "tests/fixtures/sample.png"
|
||||
|
||||
|
||||
def png_bytes(width: int = 32, height: int = 20, noise: bool = False) -> bytes:
|
||||
"""Настоящий PNG; noise — плохо сжимаемое содержимое"""
|
||||
image = (
|
||||
Image.effect_noise((width, height), 64).convert("RGB")
|
||||
if noise
|
||||
else Image.new("RGB", (width, height), (200, 30, 90))
|
||||
)
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def jpeg_bytes(width: int = 32, height: int = 20, progressive: bool = False) -> bytes:
|
||||
image = Image.effect_noise((width, height), 64).convert("RGB")
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "JPEG", quality=85, progressive=progressive)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def bilevel_png(width: int, height: int) -> bytes:
|
||||
"""Огромное по пикселям, но крошечное по байтам изображение (1 бит, нули)"""
|
||||
buffer = io.BytesIO()
|
||||
Image.new("1", (width, height)).save(buffer, "PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def png_chunk(chunk_type: bytes, data: bytes) -> bytes:
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ chunk_type
|
||||
+ data
|
||||
+ struct.pack(">I", zlib.crc32(chunk_type + data))
|
||||
)
|
||||
|
||||
|
||||
def png_of_size(size: int) -> bytes:
|
||||
"""
|
||||
Валидный PNG ровно size байт: перед IEND вставляется chunk tEXt
|
||||
с корректным CRC нужной длины.
|
||||
"""
|
||||
base = png_bytes()
|
||||
iend = base[-12:]
|
||||
padding = size - len(base) - 12
|
||||
keyword = b"Comment\x00"
|
||||
text = png_chunk(b"tEXt", keyword + b"a" * (padding - len(keyword)))
|
||||
result = base[:-12] + text + iend
|
||||
assert len(result) == size
|
||||
return result
|
||||
|
||||
|
||||
def upload_headers(user: dict, content_type: str = "image/png") -> dict[str, str]:
|
||||
return {**auth(user), "Content-Type": content_type}
|
||||
|
||||
|
||||
def upload_raw(
|
||||
api: httpx.Client,
|
||||
user: dict,
|
||||
chat_id: str,
|
||||
content: bytes,
|
||||
content_type: str | None = "image/png",
|
||||
filename: str = "image.png",
|
||||
) -> httpx.Response:
|
||||
"""POST сырых байт; content_type=None — без заголовка Content-Type"""
|
||||
headers = auth(user) if content_type is None else upload_headers(user, content_type)
|
||||
return api.post(
|
||||
f"/api/v1/chats/{chat_id}/attachments",
|
||||
params={"filename": filename},
|
||||
content=content,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
def assert_not_server_error(response: httpx.Response) -> None:
|
||||
"""Ошибка пользователя не превращается в 5xx и имеет формат контракта"""
|
||||
assert response.status_code < 500, response.text
|
||||
assert response.headers["X-Instance-Id"]
|
||||
|
||||
|
||||
def last_json_line(output: str) -> dict:
|
||||
"""Результат скрипта — последняя JSON-строка stdout; выше — журнал loguru"""
|
||||
return json.loads(
|
||||
next(line for line in reversed(output.splitlines()) if line.startswith("{"))
|
||||
)
|
||||
|
||||
|
||||
def container_json(service: str, script: str) -> dict:
|
||||
"""
|
||||
Python-скрипт внутри контейнера стенда: его сети, секреты и код из src.
|
||||
Скрипт печатает результат одной JSON-строкой.
|
||||
"""
|
||||
prelude = "import sys\nsys.path.insert(0, 'src')\n"
|
||||
output = compose("exec", "-T", service, "python", "-", stdin=prelude + script)
|
||||
return last_json_line(output)
|
||||
|
||||
|
||||
def run_janitor(*args: str) -> dict:
|
||||
"""Один проход janitor внутри его контейнера; отчёт сверки"""
|
||||
output = compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once", *args)
|
||||
return last_json_line(output)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
Upload → остановка именно той API-реплики, что приняла файл → download через
|
||||
другую реплику возвращает тот же файл. На репликах нет локальной копии
|
||||
оригинала: байты лежат в общем S3.
|
||||
|
||||
Останавливает контейнер (scripts/stop-one.sh) и возвращает его
|
||||
(scripts/restore.sh), поэтому запускается явно: make test-failures.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import ROOT, auth, png_bytes, upload_raw
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_FAILURE_TESTS") != "1",
|
||||
reason="останавливает API-реплику: запускайте через make test-failures",
|
||||
)
|
||||
|
||||
DOWNLOADS_AFTER_STOP = 10
|
||||
HOOK_TIMEOUT_SEC = 90
|
||||
|
||||
|
||||
def run_script(name: str, **env: str) -> None:
|
||||
subprocess.run(
|
||||
[str(ROOT / "scripts" / name)],
|
||||
cwd=ROOT,
|
||||
env={**os.environ, **env},
|
||||
capture_output=True,
|
||||
timeout=HOOK_TIMEOUT_SEC,
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
def test_download_survives_stop_of_uploading_replica(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
content = png_bytes(800, 600, noise=True)
|
||||
|
||||
uploaded = upload_raw(api, alice, chat["id"], content)
|
||||
assert uploaded.status_code == 201, uploaded.text
|
||||
attachment = uploaded.json()
|
||||
uploader = uploaded.headers["X-Instance-Id"]
|
||||
|
||||
run_script("stop-one.sh", TARGET_INSTANCE_ID=uploader)
|
||||
try:
|
||||
served_by = set()
|
||||
for _ in range(DOWNLOADS_AFTER_STOP):
|
||||
response = api.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(bob)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
assert hashlib.sha256(response.content).hexdigest() == attachment["sha256"]
|
||||
assert response.content == content
|
||||
served_by.add(response.headers["X-Instance-Id"])
|
||||
print(f"\nUPLOADED BY {uploader}, DOWNLOADED FROM {sorted(served_by)}")
|
||||
assert uploader not in served_by
|
||||
finally:
|
||||
run_script("restore.sh")
|
||||
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
Вложения: загрузка, побайтное скачивание, доступ, лимиты и проверка содержимого.
|
||||
Любая ошибка пользователя — 4xx в формате контракта, никогда не 5xx.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import uuid
|
||||
from urllib.parse import unquote
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
FIXTURE_PNG,
|
||||
MAX_IMAGE_PIXELS,
|
||||
MAX_UPLOAD_BYTES,
|
||||
assert_error,
|
||||
assert_not_server_error,
|
||||
auth,
|
||||
bilevel_png,
|
||||
jpeg_bytes,
|
||||
png_bytes,
|
||||
png_of_size,
|
||||
upload_raw,
|
||||
)
|
||||
|
||||
ATTACHMENT_FIELDS = {
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"status",
|
||||
"variants",
|
||||
"error_code",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
}
|
||||
|
||||
|
||||
def download(api: httpx.Client, user: dict, attachment_id: str) -> httpx.Response:
|
||||
return api.get(f"/api/v1/attachments/{attachment_id}/content", headers=auth(user))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("content", "content_type"),
|
||||
[
|
||||
(FIXTURE_PNG.read_bytes(), "image/png"),
|
||||
(jpeg_bytes(640, 480), "image/jpeg"),
|
||||
(jpeg_bytes(640, 480, progressive=True), "image/jpeg"),
|
||||
],
|
||||
ids=["png-fixture", "jpeg-baseline", "jpeg-progressive"],
|
||||
)
|
||||
def test_upload_and_download_byte_exact(
|
||||
api: httpx.Client, make_user, make_chat, upload, content: bytes, content_type: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
|
||||
attachment = upload(alice, chat, content, content_type, "photo")
|
||||
|
||||
assert set(attachment) == ATTACHMENT_FIELDS
|
||||
assert attachment["status"] == "ready"
|
||||
assert attachment["variants"] == [] and attachment["error_code"] is None
|
||||
assert attachment["chat_id"] == chat["id"] and attachment["owner_id"] == alice["id"]
|
||||
assert attachment["content_type"] == content_type
|
||||
assert attachment["size_bytes"] == len(content)
|
||||
assert attachment["sha256"] == hashlib.sha256(content).hexdigest()
|
||||
assert attachment["created_at"].endswith("Z")
|
||||
|
||||
metadata = api.get(f"/api/v1/attachments/{attachment['id']}", headers=auth(bob))
|
||||
assert metadata.status_code == 200 and metadata.json() == attachment
|
||||
|
||||
response = download(api, bob, attachment["id"])
|
||||
assert response.status_code == 200
|
||||
assert response.content == content
|
||||
assert response.headers["content-type"] == content_type
|
||||
assert response.headers["content-length"] == str(len(content))
|
||||
assert response.headers["x-content-type-options"] == "nosniff"
|
||||
assert response.headers["X-Instance-Id"]
|
||||
|
||||
|
||||
def test_public_api_does_not_expose_storage_details(
|
||||
api: httpx.Client, make_user, make_chat, upload
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
attachment = upload(alice, chat)
|
||||
response = download(api, alice, attachment["id"])
|
||||
exposed = (str(attachment) + str(dict(response.headers))).lower()
|
||||
for marker in ("originals/", "s3:9000", "messenger-attachments", "amz"):
|
||||
assert marker not in exposed
|
||||
assert response.status_code == 200
|
||||
assert not response.history, "download must not redirect to storage"
|
||||
|
||||
|
||||
def test_unicode_filename_is_preserved(
|
||||
api: httpx.Client, make_user, make_chat, upload
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
name = "Фото отпуска 😀 «море» — 1.png"
|
||||
attachment = upload(alice, chat, filename=name)
|
||||
assert attachment["filename"] == name
|
||||
disposition = download(api, alice, attachment["id"]).headers["content-disposition"]
|
||||
assert disposition.startswith("inline; filename*=UTF-8''")
|
||||
assert unquote(disposition.split("''", 1)[1]) == name
|
||||
|
||||
|
||||
def test_outsider_and_unknown_get_indistinguishable_404(
|
||||
api: httpx.Client, make_user, make_chat, upload
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
attachment = upload(alice, chat)
|
||||
|
||||
for suffix in ("", "/content"):
|
||||
foreign = api.get(f"/api/v1/attachments/{attachment['id']}{suffix}", headers=auth(eve))
|
||||
missing = api.get(f"/api/v1/attachments/{uuid.uuid4()}{suffix}", headers=auth(eve))
|
||||
assert_error(foreign, 404, "not_found")
|
||||
assert_error(missing, 404, "not_found")
|
||||
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
|
||||
|
||||
|
||||
def test_outsider_cannot_upload_into_foreign_chat(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
assert_error(upload_raw(api, eve, chat["id"], png_bytes()), 404, "not_found")
|
||||
assert_error(upload_raw(api, eve, str(uuid.uuid4()), png_bytes()), 404, "not_found")
|
||||
|
||||
|
||||
def test_authentication_is_required(api: httpx.Client, make_user, make_chat, upload) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
attachment = upload(alice, chat)
|
||||
anonymous = {"token": "x" * 43}
|
||||
for response in (
|
||||
api.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": "a.png"},
|
||||
content=png_bytes(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
),
|
||||
api.get(f"/api/v1/attachments/{attachment['id']}"),
|
||||
download(api, anonymous, attachment["id"]),
|
||||
):
|
||||
assert_error(response, 401, "unauthorized")
|
||||
|
||||
|
||||
def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upload) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
attachment = upload(alice, chat)
|
||||
path = f"/api/v1/attachments/{attachment['id']}/content"
|
||||
|
||||
original = api.get(path, params={"variant": "original"}, headers=auth(alice))
|
||||
assert original.status_code == 200
|
||||
# Вариант из контракта, но в lab4 его нет у ready-вложения
|
||||
missing = api.get(path, params={"variant": "thumbnail"}, headers=auth(alice))
|
||||
assert_error(missing, 404, "not_found")
|
||||
unknown = api.get(path, params={"variant": "../../etc"}, headers=auth(alice))
|
||||
assert_error(unknown, 400, "invalid_request")
|
||||
malformed = api.get("/api/v1/attachments/not-a-uuid", headers=auth(alice))
|
||||
assert_error(malformed, 400, "invalid_request")
|
||||
|
||||
|
||||
# --- Размер ---
|
||||
|
||||
|
||||
def test_exactly_max_bytes_is_accepted(api: httpx.Client, make_user, make_chat, upload) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
content = png_of_size(MAX_UPLOAD_BYTES)
|
||||
attachment = upload(alice, chat, content)
|
||||
assert attachment["size_bytes"] == MAX_UPLOAD_BYTES
|
||||
assert download(api, alice, attachment["id"]).content == content
|
||||
|
||||
|
||||
def test_too_large_file_is_rejected_by_api(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""10 MiB + 1 байт отклоняет реплика (X-Instance-Id), а не только LB"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], png_of_size(MAX_UPLOAD_BYTES + 1))
|
||||
assert_error(response, 413, "payload_too_large")
|
||||
assert response.headers["X-Instance-Id"]
|
||||
|
||||
|
||||
def test_huge_body_is_rejected_by_balancer(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], b"\x00" * (12 * 1024 * 1024))
|
||||
assert_error(response, 413, "payload_too_large")
|
||||
|
||||
|
||||
def test_empty_body_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
assert_error(upload_raw(api, alice, chat["id"], b""), 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("width", "height", "status"),
|
||||
[
|
||||
(8000, 5000, 201),
|
||||
(8000, 5001, 413),
|
||||
(20000, 20000, 413),
|
||||
],
|
||||
)
|
||||
def test_pixel_limit_applies_before_decoding(
|
||||
api: httpx.Client, make_user, make_chat, width: int, height: int, status: int
|
||||
) -> None:
|
||||
"""Файл крошечный по байтам: лимит считается по заголовку, а не по размеру"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
content = bilevel_png(width, height)
|
||||
assert len(content) < 1024 * 1024
|
||||
response = upload_raw(api, alice, chat["id"], content)
|
||||
if status == 201:
|
||||
assert width * height == MAX_IMAGE_PIXELS
|
||||
assert response.status_code == 201, response.text
|
||||
else:
|
||||
assert_error(response, 413, "payload_too_large")
|
||||
|
||||
|
||||
# --- Содержимое и MIME ---
|
||||
|
||||
|
||||
def corrupted_payloads() -> list[tuple[str, bytes, str]]:
|
||||
png = png_bytes(300, 200, noise=True)
|
||||
jpeg = jpeg_bytes(300, 200)
|
||||
flipped = bytearray(png)
|
||||
flipped[len(png) // 2] ^= 0xFF
|
||||
return [
|
||||
("png-truncated", png[: len(png) // 2], "image/png"),
|
||||
("png-bit-flip-crc", bytes(flipped), "image/png"),
|
||||
("png-signature-garbage", png[:8] + b"\x00garbage" * 64, "image/png"),
|
||||
("png-without-iend", png[:-12], "image/png"),
|
||||
("jpeg-truncated", jpeg[: len(jpeg) // 2], "image/jpeg"),
|
||||
("jpeg-signature-garbage", b"\xff\xd8\xff" + b"garbage" * 64, "image/jpeg"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "content", "content_type"),
|
||||
corrupted_payloads(),
|
||||
ids=[item[0] for item in corrupted_payloads()],
|
||||
)
|
||||
def test_corrupted_image_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, name: str, content: bytes, content_type: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], content, content_type)
|
||||
assert_not_server_error(response)
|
||||
assert_error(response, 415, "unsupported_media_type")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("content", "content_type"),
|
||||
[
|
||||
(png_bytes(), "image/jpeg"),
|
||||
(jpeg_bytes(), "image/png"),
|
||||
(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;", "image/png"),
|
||||
(b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/png"),
|
||||
(b"%PDF-1.7\n", "image/jpeg"),
|
||||
(png_bytes(), "application/octet-stream"),
|
||||
(png_bytes(), "image/gif"),
|
||||
(png_bytes(), "text/html"),
|
||||
(png_bytes(), None),
|
||||
],
|
||||
ids=[
|
||||
"png-as-jpeg",
|
||||
"jpeg-as-png",
|
||||
"gif-as-png",
|
||||
"svg-as-png",
|
||||
"pdf-as-jpeg",
|
||||
"octet-stream",
|
||||
"image-gif",
|
||||
"text-html",
|
||||
"no-content-type",
|
||||
],
|
||||
)
|
||||
def test_mime_spoofing_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, content: bytes, content_type: str | None
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], content, content_type)
|
||||
assert_not_server_error(response)
|
||||
assert_error(response, 415, "unsupported_media_type")
|
||||
|
||||
|
||||
def test_content_type_parameters_are_ignored(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], png_bytes(), "Image/PNG; foo=bar")
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.json()["content_type"] == "image/png"
|
||||
|
||||
|
||||
# --- Имя файла ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"filename",
|
||||
[
|
||||
"../../etc/passwd",
|
||||
"dir/photo.png",
|
||||
"C:\\photo.png",
|
||||
"a\x00b.png",
|
||||
"line\nbreak.png",
|
||||
"tab\t.png",
|
||||
"bell\x07.png",
|
||||
"photo\u202egnp.exe",
|
||||
"",
|
||||
" ",
|
||||
".",
|
||||
"..",
|
||||
"x" * 256,
|
||||
],
|
||||
ids=[
|
||||
"traversal",
|
||||
"slash",
|
||||
"backslash",
|
||||
"nul",
|
||||
"newline",
|
||||
"tab",
|
||||
"control",
|
||||
"bidi-override",
|
||||
"empty",
|
||||
"blank",
|
||||
"dot",
|
||||
"dotdot",
|
||||
"too-long",
|
||||
],
|
||||
)
|
||||
def test_dangerous_filename_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, filename: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = upload_raw(api, alice, chat["id"], png_bytes(), filename=filename)
|
||||
assert_not_server_error(response)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_missing_filename_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
content=png_bytes(),
|
||||
headers={**auth(alice), "Content-Type": "image/png"},
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_longest_filename_is_accepted(make_user, make_chat, upload) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
name = "я" * 251 + ".png"
|
||||
assert upload(alice, chat, filename=name)["filename"] == name
|
||||
|
||||
|
||||
def test_same_filename_gets_separate_attachments(
|
||||
api: httpx.Client, make_user, make_chat, upload
|
||||
) -> None:
|
||||
"""filename — только отображение: одинаковые имена не перезаписывают файл"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
first_content, second_content = png_bytes(10, 10), png_bytes(20, 20)
|
||||
first = upload(alice, chat, first_content, filename="same.png")
|
||||
second = upload(alice, chat, second_content, filename="same.png")
|
||||
assert first["id"] != second["id"]
|
||||
assert download(api, alice, first["id"]).content == first_content
|
||||
assert download(api, alice, second["id"]).content == second_content
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Вход по Basic, opaque Bearer-сессия, неверный пароль и logout"""
|
||||
|
||||
import base64
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_unauthorized,
|
||||
auth,
|
||||
basic,
|
||||
psql,
|
||||
public_user,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
SESSIONS_PATH = "/api/v1/auth/sessions"
|
||||
CURRENT_SESSION_PATH = "/api/v1/auth/sessions/current"
|
||||
|
||||
|
||||
def test_login_returns_opaque_bearer_session(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
response = api.post(
|
||||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
session = response.json()
|
||||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert session["user"] == public_user(alice)
|
||||
assert len(session["token"]) >= 43 # 32 байта в base64url
|
||||
assert alice["id"] not in session["token"]
|
||||
assert alice["username"] not in session["token"]
|
||||
assert session["token"] != alice["token"]
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
assert expires_at > datetime.now(UTC)
|
||||
|
||||
|
||||
def test_wrong_password_and_unknown_user_are_indistinguishable(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
wrong = api.post(SESSIONS_PATH, headers=basic(alice["username"], "Wrong-pass-123"))
|
||||
unknown = api.post(
|
||||
SESSIONS_PATH, headers=basic(unique_username("ghost"), "Wrong-pass-123")
|
||||
)
|
||||
for response in (wrong, unknown):
|
||||
assert_unauthorized(response, scheme="Basic")
|
||||
assert 'realm="messenger"' in response.headers["WWW-Authenticate"]
|
||||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"authorization",
|
||||
[
|
||||
None,
|
||||
"",
|
||||
"Basic",
|
||||
"Basic !!!not-base64!!!",
|
||||
"Basic " + base64.b64encode(b"no-colon-here").decode(),
|
||||
"Basic " + base64.b64encode(b"\xff\xfe:password").decode(),
|
||||
"Bearer some-token",
|
||||
],
|
||||
)
|
||||
def test_malformed_basic_is_unauthorized(
|
||||
api: httpx.Client, authorization: str | None
|
||||
) -> None:
|
||||
headers = {} if authorization is None else {"Authorization": authorization}
|
||||
assert_unauthorized(api.post(SESSIONS_PATH, headers=headers), scheme="Basic")
|
||||
|
||||
|
||||
def test_utf8_password_with_colon(api: httpx.Client) -> None:
|
||||
username = unique_username("utf")
|
||||
password = "пароль:с:двоеточием 🔐"
|
||||
body = {"username": username, "display_name": "x", "password": password}
|
||||
assert api.post("/api/v1/users", json=body).status_code == 201
|
||||
assert api.post(SESSIONS_PATH, headers=basic(username, password)).status_code == 201
|
||||
assert_unauthorized(
|
||||
api.post(SESSIONS_PATH, headers=basic(username, "пароль:с:двоеточием")),
|
||||
scheme="Basic",
|
||||
)
|
||||
|
||||
|
||||
def test_basic_is_rejected_on_business_endpoints(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
headers = basic(alice["username"], alice["password"])
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
|
||||
|
||||
|
||||
def test_logout_revokes_only_current_session(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
second = api.post(
|
||||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||||
)
|
||||
other_session = {**alice, "token": second.json()["token"]}
|
||||
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
response = api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||||
assert response.status_code == 204
|
||||
assert response.content == b""
|
||||
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH, headers=auth(alice)))
|
||||
assert api.get("/api/v1/users/me", headers=auth(other_session)).status_code == 200
|
||||
|
||||
|
||||
def test_logout_without_token(api: httpx.Client) -> None:
|
||||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH))
|
||||
assert_unauthorized(
|
||||
api.delete(CURRENT_SESSION_PATH, headers={"Authorization": "Bearer unknown"})
|
||||
)
|
||||
|
||||
|
||||
def test_relogin_after_logout(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||||
again = api.post(SESSIONS_PATH, headers=basic(alice["username"], alice["password"]))
|
||||
assert again.status_code == 201
|
||||
renewed = {**alice, "token": again.json()["token"]}
|
||||
assert api.get("/api/v1/users/me", headers=auth(renewed)).status_code == 200
|
||||
|
||||
|
||||
def test_password_is_not_stored_in_plaintext(make_user) -> None:
|
||||
"""Проверка в БД стенда: в users лежит PHC-строка Argon2id, а не пароль"""
|
||||
alice = make_user("alice")
|
||||
stored = psql(
|
||||
f"SELECT password_hash FROM users WHERE username = '{alice['username']}';"
|
||||
)
|
||||
assert stored.startswith("$argon2id$")
|
||||
assert alice["password"] not in stored
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
Балансировка без sticky sessions: запросы одной сессии обслуживают разные
|
||||
реплики, а состояние (сессии, сообщения, logout) общее для всех.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import httpx
|
||||
from helpers import assert_unauthorized, auth, message_headers, public_user
|
||||
|
||||
REQUESTS = 20
|
||||
|
||||
|
||||
def test_one_session_is_served_by_several_replicas(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
"""Одно keep-alive соединение клиента к LB, без повторного входа"""
|
||||
alice = make_user("alice")
|
||||
instances: Counter[str] = Counter()
|
||||
for _ in range(REQUESTS):
|
||||
response = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == public_user(alice)
|
||||
instances[response.headers["X-Instance-Id"]] += 1
|
||||
print("\nINSTANCES FOR ONE SESSION:", dict(instances))
|
||||
assert len(instances) >= 2
|
||||
|
||||
|
||||
def test_write_is_visible_through_every_replica(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
sent = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"видно везде {uuid.uuid4().hex}"},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert sent.status_code == 201, sent.text
|
||||
readers: set[str] = set()
|
||||
for _ in range(REQUESTS):
|
||||
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(bob))
|
||||
assert page.status_code == 200, page.text
|
||||
assert page.json()["items"] == [sent.json()]
|
||||
readers.add(page.headers["X-Instance-Id"])
|
||||
assert len(readers) >= 2
|
||||
|
||||
|
||||
def test_logout_applies_to_all_replicas(api: httpx.Client, make_user) -> None:
|
||||
"""Сессия попала в общий кэш через обе реплики, затем отозвана на одной"""
|
||||
alice = make_user("alice")
|
||||
for _ in range(4):
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
logout = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert logout.status_code == 204
|
||||
rejected_by: set[str] = set()
|
||||
for _ in range(REQUESTS):
|
||||
response = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert_unauthorized(response)
|
||||
rejected_by.add(response.headers["X-Instance-Id"])
|
||||
assert len(rejected_by) >= 2
|
||||
|
||||
|
||||
def test_every_api_response_has_instance_id(api: httpx.Client) -> None:
|
||||
for response in (
|
||||
api.get("/health/live"),
|
||||
api.get("/health/ready"),
|
||||
api.get("/api/v1/unknown"),
|
||||
api.get("/api/v1/users/me"),
|
||||
):
|
||||
assert response.headers["X-Instance-Id"]
|
||||
assert response.headers["X-Request-Id"]
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Защита состояния от гонок: 100 сообщений от 10 параллельных клиентов"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from helpers import auth, message_headers, read_all_messages
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
TOTAL_MESSAGES = CLIENTS * MESSAGES_PER_CLIENT
|
||||
PAGE_LIMIT = 30
|
||||
|
||||
|
||||
async def _send_concurrently(
|
||||
base_url: str, chat_id: str, users: list[dict]
|
||||
) -> list[int]:
|
||||
"""Каждый клиент — отдельный пользователь и пул соединений; старт по сигналу"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def client_worker(user: dict) -> list[int]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, headers=auth(user), timeout=30
|
||||
) as client:
|
||||
await start.wait()
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": f"{user['username']}#{n}"},
|
||||
headers=message_headers(user),
|
||||
)
|
||||
for n in range(MESSAGES_PER_CLIENT)
|
||||
)
|
||||
)
|
||||
return [response.status_code for response in responses]
|
||||
|
||||
workers = [asyncio.create_task(client_worker(user)) for user in users]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
results = await asyncio.gather(*workers)
|
||||
return [status for statuses in results for status in statuses]
|
||||
|
||||
|
||||
def test_parallel_messages_are_not_lost_or_duplicated(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
users = [make_user(f"c{n}") for n in range(CLIENTS)]
|
||||
chat = make_chat(users[0], users)
|
||||
|
||||
started = time.perf_counter()
|
||||
statuses = asyncio.run(_send_concurrently(base_url, chat["id"], users))
|
||||
elapsed = time.perf_counter() - started
|
||||
|
||||
items, pages = read_all_messages(api, users[-1], chat["id"], PAGE_LIMIT)
|
||||
expected_texts = {
|
||||
f"{user['username']}#{n}" for user in users for n in range(MESSAGES_PER_CLIENT)
|
||||
}
|
||||
summary = {
|
||||
"clients": CLIENTS,
|
||||
"messages_sent": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"messages_read": len(items),
|
||||
"unique_ids": len({item["id"] for item in items}),
|
||||
"unique_texts": len({item["text"] for item in items}),
|
||||
"pages_read": pages,
|
||||
"send_seconds": round(elapsed, 3),
|
||||
}
|
||||
print("\nCONCURRENCY RESULT:", json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
assert statuses == [201] * TOTAL_MESSAGES
|
||||
assert len(items) == TOTAL_MESSAGES
|
||||
assert summary["unique_ids"] == TOTAL_MESSAGES
|
||||
assert {item["text"] for item in items} == expected_texts
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
assert len(set(keys)) == TOTAL_MESSAGES
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Отказы зависимостей: Valkey и PostgreSQL останавливаются через docker compose.
|
||||
|
||||
Тесты меняют состояние стенда (stop/start контейнеров, volumes сохраняются),
|
||||
поэтому запускаются только явно: make test-failures (RUN_FAILURE_TESTS=1).
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, assert_unauthorized, auth, basic, compose
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_FAILURE_TESTS") != "1",
|
||||
reason="останавливает контейнеры стенда: запускайте через make test-failures",
|
||||
)
|
||||
|
||||
READY_TIMEOUT_SEC = 60
|
||||
# Ответ при упавшей зависимости должен быть быстрым, а не висеть до таймаута клиента
|
||||
BOUNDED_RESPONSE_SEC = 3
|
||||
|
||||
|
||||
def wait_ready(api: httpx.Client) -> None:
|
||||
deadline = time.monotonic() + READY_TIMEOUT_SEC
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if api.get("/health/ready").status_code == 200:
|
||||
return
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("API не стал готов после восстановления зависимости")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valkey_stopped(api: httpx.Client) -> Iterator[None]:
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
wait_ready(api)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def postgres_stopped(api: httpx.Client) -> Iterator[None]:
|
||||
compose("stop", "postgres")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
compose("up", "-d", "--wait", "postgres")
|
||||
wait_ready(api)
|
||||
|
||||
|
||||
def test_valkey_down_cache_is_bypassed(
|
||||
api: httpx.Client, make_user, make_chat, send_message, valkey_stopped
|
||||
) -> None:
|
||||
"""Без Valkey всё работает через PostgreSQL: вход, Bearer, запись, logout"""
|
||||
alice = make_user("alice")
|
||||
started = time.monotonic()
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200, me.text
|
||||
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
|
||||
|
||||
chat = make_chat(alice, [alice])
|
||||
send_message(alice, chat, "без кэша")
|
||||
assert api.get("/health/ready").status_code == 200
|
||||
|
||||
assert (
|
||||
api.delete("/api/v1/auth/sessions/current", headers=auth(alice)).status_code
|
||||
== 204
|
||||
)
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(api.get("/api/v1/users/me"))
|
||||
|
||||
|
||||
def test_logout_during_valkey_outage_is_not_resurrected(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
"""
|
||||
Сессия попала в кэш, затем Valkey упал и пользователь вышел. После подъёма
|
||||
Valkey (без persistence — пустой) отозванный токен не принимается.
|
||||
"""
|
||||
alice = make_user("alice")
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
response = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert response.status_code == 204
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
wait_ready(api)
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
|
||||
|
||||
def test_postgres_down_returns_bounded_503_and_no_anonymous_access(
|
||||
api: httpx.Client, make_user, postgres_stopped
|
||||
) -> None:
|
||||
alice_token_unused = {"token": "x" * 43}
|
||||
|
||||
started = time.monotonic()
|
||||
ready = api.get("/health/ready")
|
||||
assert_error(ready, 503, "unavailable")
|
||||
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
|
||||
|
||||
# Анонимный запрос остаётся 401, неизвестный токен не принимается как доверенный
|
||||
assert_unauthorized(api.get("/api/v1/users/me"))
|
||||
unknown = api.get("/api/v1/users/me", headers=auth(alice_token_unused))
|
||||
assert_error(unknown, 503, "unavailable")
|
||||
assert "asyncpg" not in unknown.text and "postgres" not in unknown.text.lower()
|
||||
|
||||
body = {"username": "st_pg_down", "display_name": "x", "password": "P" * 12}
|
||||
assert_error(api.post("/api/v1/users", json=body), 503, "unavailable")
|
||||
login = api.post("/api/v1/auth/sessions", headers=basic("st_pg_down", "P" * 12))
|
||||
assert_error(login, 503, "unavailable")
|
||||
|
||||
|
||||
def test_session_survives_postgres_restart(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
compose("restart", "postgres")
|
||||
wait_ready(api)
|
||||
chats = api.get("/api/v1/chats", headers=auth(alice))
|
||||
assert chats.status_code == 200, chats.text
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
Истечение сессии при коротком SESSION_TTL_SECONDS.
|
||||
|
||||
Нужен отдельный API с SESSION_TTL_SECONDS=2: make test-expiry поднимает
|
||||
api-short-ttl на :8081 поверх тех же PostgreSQL и Valkey.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from conftest import register_and_login
|
||||
from helpers import assert_unauthorized, auth, basic
|
||||
|
||||
EXPIRY_BASE_URL = os.environ.get("EXPIRY_BASE_URL")
|
||||
SHORT_TTL_SEC = 2
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not EXPIRY_BASE_URL, reason="EXPIRY_BASE_URL не задан: запустите make test-expiry"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def short_api() -> httpx.Client:
|
||||
assert EXPIRY_BASE_URL is not None
|
||||
with httpx.Client(base_url=EXPIRY_BASE_URL, timeout=10) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def test_session_expires_after_short_ttl(short_api: httpx.Client) -> None:
|
||||
alice = register_and_login(short_api, "ttl")
|
||||
me = short_api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200, me.text
|
||||
|
||||
time.sleep(SHORT_TTL_SEC + 1)
|
||||
|
||||
# Сессия уже лежала в кэше после первого запроса: истечь должна и там
|
||||
assert_unauthorized(short_api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(short_api.get("/api/v1/chats", headers=auth(alice)))
|
||||
assert_unauthorized(
|
||||
short_api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
)
|
||||
|
||||
|
||||
def test_expires_at_matches_short_ttl(short_api: httpx.Client) -> None:
|
||||
before = datetime.now(UTC)
|
||||
alice = register_and_login(short_api, "ttl")
|
||||
session = short_api.post(
|
||||
"/api/v1/auth/sessions", headers=basic(alice["username"], alice["password"])
|
||||
).json()
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
lifetime = (expires_at - before).total_seconds()
|
||||
assert 0 < lifetime <= SHORT_TTL_SEC + 1
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Чужой чат: посторонний получает 404, существование чата не раскрывается"""
|
||||
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
|
||||
def test_outsider_cannot_access_chat(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
send_message(alice, chat, "секрет")
|
||||
path = f"/api/v1/chats/{chat['id']}"
|
||||
|
||||
assert_error(api.get(path, headers=auth(eve)), 404, "not_found")
|
||||
assert_error(api.get(f"{path}/messages", headers=auth(eve)), 404, "not_found")
|
||||
response = api.post(
|
||||
f"{path}/messages", json={"text": "чужое"}, headers=message_headers(eve)
|
||||
)
|
||||
assert_error(response, 404, "not_found")
|
||||
|
||||
history = api.get(f"{path}/messages", headers=auth(bob)).json()
|
||||
assert [item["text"] for item in history["items"]] == ["секрет"]
|
||||
|
||||
|
||||
def test_foreign_and_missing_chat_are_indistinguishable(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
foreign = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(eve)).json()
|
||||
missing = api.get(f"/api/v1/chats/{uuid.uuid4()}", headers=auth(eve)).json()
|
||||
assert foreign["error"]["code"] == missing["error"]["code"] == "not_found"
|
||||
assert foreign["error"]["message"] == missing["error"]["message"]
|
||||
|
||||
|
||||
def test_chat_list_contains_only_own_chats(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
own = api.get("/api/v1/chats", headers=auth(eve)).json()
|
||||
assert own == {"items": [], "next_cursor": None}
|
||||
listed = api.get("/api/v1/chats", headers=auth(alice)).json()
|
||||
assert [item["id"] for item in listed["items"]] == [chat["id"]]
|
||||
@@ -0,0 +1,15 @@
|
||||
import httpx
|
||||
from helpers import assert_error
|
||||
|
||||
|
||||
def test_health_endpoints_have_request_id(api: httpx.Client) -> None:
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
response = api.get(path)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def test_unknown_route_uses_error_format(api: httpx.Client) -> None:
|
||||
assert_error(api.get("/api/v1/unknown"), 404, "not_found")
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Idempotency-Key отправки сообщения: повтор, конфликт, область ключа, гонки"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, message_headers, psql, read_all_messages
|
||||
|
||||
PARALLEL_REPLAYS = 20
|
||||
|
||||
|
||||
def post_message(
|
||||
api: httpx.Client, user: dict, chat: dict, text: str, key: str
|
||||
) -> httpx.Response:
|
||||
return api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user, key),
|
||||
)
|
||||
|
||||
|
||||
def history(api: httpx.Client, user: dict, chat: dict) -> list[dict]:
|
||||
items, _ = read_all_messages(api, user, chat["id"], 100)
|
||||
return items
|
||||
|
||||
|
||||
def test_replay_returns_same_message(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
first = post_message(api, alice, chat, "один раз", key)
|
||||
second = post_message(api, alice, chat, "один раз", key)
|
||||
|
||||
assert first.status_code == second.status_code == 201, second.text
|
||||
assert first.json() == second.json()
|
||||
assert history(api, alice, chat) == [first.json()]
|
||||
|
||||
|
||||
def test_replay_ignores_json_formatting(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
"""Пробелы и форма записи JSON не меняют смысл тела: это тот же запрос"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
headers = {**message_headers(alice), "Content-Type": "application/json"}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
escaped = b'{"text":"\\u041f\\u0440\\u0438"}'
|
||||
compact = api.post(path, content=escaped, headers=headers)
|
||||
spaced = api.post(path, content='{ "text" : "При" }'.encode(), headers=headers)
|
||||
|
||||
assert compact.status_code == spaced.status_code == 201, spaced.text
|
||||
assert compact.json() == spaced.json()
|
||||
assert len(history(api, alice, chat)) == 1
|
||||
|
||||
|
||||
def test_same_key_with_other_body_is_conflict(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
original = post_message(api, alice, chat, "оригинал", key).json()
|
||||
|
||||
assert_error(post_message(api, alice, chat, "другой", key), 409, "conflict")
|
||||
assert history(api, alice, chat) == [original]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[
|
||||
{},
|
||||
{"Idempotency-Key": ""},
|
||||
{"Idempotency-Key": "with space"},
|
||||
{"Idempotency-Key": "ключ".encode()},
|
||||
{"Idempotency-Key": "a/b"},
|
||||
{"Idempotency-Key": "x" * 129},
|
||||
],
|
||||
)
|
||||
def test_missing_or_invalid_key_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, headers: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "без ключа"},
|
||||
headers={**auth(alice), **headers},
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert history(api, alice, chat) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["x" * 128, "Az09._:-"])
|
||||
def test_key_boundaries_are_accepted(
|
||||
api: httpx.Client, make_user, make_chat, key: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
assert post_message(api, alice, chat, "граница", key).status_code == 201
|
||||
|
||||
|
||||
def test_key_scope_is_user_and_chat(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""Один ключ у разных пользователей и в разных чатах — независимые сообщения"""
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
other_chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
from_alice = post_message(api, alice, chat, "текст", key).json()
|
||||
from_bob = post_message(api, bob, chat, "текст", key).json()
|
||||
in_other_chat = post_message(api, alice, other_chat, "текст", key).json()
|
||||
|
||||
assert len({from_alice["id"], from_bob["id"], in_other_chat["id"]}) == 3
|
||||
assert from_bob["sender_id"] == bob["id"]
|
||||
assert len(history(api, alice, chat)) == 2
|
||||
assert len(history(api, alice, other_chat)) == 1
|
||||
|
||||
|
||||
def test_replay_rechecks_session_and_access(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
post_message(api, alice, chat, "секрет", key)
|
||||
|
||||
# Чужой с тем же ключом не получает сохранённое сообщение
|
||||
assert_error(post_message(api, eve, chat, "секрет", key), 404, "not_found")
|
||||
# Отозванная сессия не даёт повтора
|
||||
logout = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert logout.status_code == 204
|
||||
replay = post_message(api, alice, chat, "секрет", key)
|
||||
assert_error(replay, 401, "unauthorized")
|
||||
|
||||
|
||||
def test_expired_key_can_be_reused(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""После срока хранения (24 ч) ключ снова создаёт сообщение; срок сдвигается в БД"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
first = post_message(api, alice, chat, "вчера", key).json()
|
||||
psql(
|
||||
"UPDATE message_idempotency_keys "
|
||||
"SET created_at = now() - interval '2 days', "
|
||||
"expires_at = now() - interval '1 day' "
|
||||
f"WHERE chat_id = '{chat['id']}' AND idempotency_key = '{key}';"
|
||||
)
|
||||
|
||||
second = post_message(api, alice, chat, "сегодня", key)
|
||||
|
||||
assert second.status_code == 201, second.text
|
||||
assert second.json()["id"] != first["id"]
|
||||
assert [item["text"] for item in history(api, alice, chat)] == ["вчера", "сегодня"]
|
||||
stored = psql(
|
||||
"SELECT count(*) FROM message_idempotency_keys "
|
||||
f"WHERE chat_id = '{chat['id']}' AND idempotency_key = '{key}';"
|
||||
)
|
||||
assert stored == "1"
|
||||
|
||||
|
||||
async def _post_concurrently(
|
||||
base_url: str, user: dict, chat: dict, key: str, texts: list[str]
|
||||
) -> list[httpx.Response]:
|
||||
"""Все запросы стартуют по одному сигналу; отдельные соединения к LB"""
|
||||
start = asyncio.Event()
|
||||
limits = httpx.Limits(max_connections=len(texts))
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, timeout=30, limits=limits
|
||||
) as client:
|
||||
|
||||
async def post(text: str) -> httpx.Response:
|
||||
await start.wait()
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(user, key),
|
||||
)
|
||||
|
||||
tasks = [asyncio.create_task(post(text)) for text in texts]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
return list(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
def test_parallel_replays_through_replicas_create_one_message(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
responses = asyncio.run(
|
||||
_post_concurrently(
|
||||
base_url, alice, chat, key, ["одно сообщение"] * PARALLEL_REPLAYS
|
||||
)
|
||||
)
|
||||
|
||||
statuses = Counter(response.status_code for response in responses)
|
||||
instances = Counter(response.headers["X-Instance-Id"] for response in responses)
|
||||
bodies = {json.dumps(response.json(), sort_keys=True) for response in responses}
|
||||
items = history(api, alice, chat)
|
||||
rows = psql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}';")
|
||||
print(
|
||||
"\nPARALLEL SAME KEY:",
|
||||
json.dumps(
|
||||
{
|
||||
"requests": len(responses),
|
||||
"statuses": dict(statuses),
|
||||
"instances": dict(instances),
|
||||
"distinct_bodies": len(bodies),
|
||||
"messages_in_history": len(items),
|
||||
"rows_in_db": int(rows),
|
||||
}
|
||||
),
|
||||
)
|
||||
assert statuses == {201: PARALLEL_REPLAYS}
|
||||
assert len(instances) >= 2, "запросы не распределились по репликам"
|
||||
assert len(bodies) == 1
|
||||
assert len(items) == 1 and rows == "1"
|
||||
|
||||
|
||||
def test_parallel_same_key_with_different_bodies(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
"""Победитель гонки один; совпавшие с ним тела — 201, остальные — 409"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
texts = ["вариант A", "вариант B"] * (PARALLEL_REPLAYS // 2)
|
||||
|
||||
responses = asyncio.run(_post_concurrently(base_url, alice, chat, key, texts))
|
||||
|
||||
items = history(api, alice, chat)
|
||||
assert len(items) == 1
|
||||
winner = items[0]
|
||||
for text, response in zip(texts, responses):
|
||||
if text == winner["text"]:
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.json() == winner
|
||||
else:
|
||||
assert_error(response, 409, "conflict")
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Неверный JSON и неверная структура тела — 400 invalid_request"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
PASSWORD = "Valid-password-123"
|
||||
|
||||
MALFORMED_BODIES = [
|
||||
b'{"username": "abc",',
|
||||
b"not json at all",
|
||||
b'{"text": "\xff\xfe"}',
|
||||
b"",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", MALFORMED_BODIES)
|
||||
def test_malformed_json_on_register(api: httpx.Client, raw: bytes) -> None:
|
||||
response = api.post(
|
||||
"/api/v1/users", content=raw, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", MALFORMED_BODIES)
|
||||
def test_malformed_json_on_create_chat_and_message(
|
||||
api: httpx.Client, make_user, make_chat, raw: bytes
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
headers = {**auth(alice), "Content-Type": "application/json"}
|
||||
assert_error(
|
||||
api.post("/api/v1/chats", content=raw, headers=headers), 400, "invalid_request"
|
||||
)
|
||||
message_post_headers = {
|
||||
**message_headers(alice),
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
assert_error(
|
||||
api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
content=raw,
|
||||
headers=message_post_headers,
|
||||
),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
[],
|
||||
"alice",
|
||||
{"username": "valid_name", "password": PASSWORD},
|
||||
{"username": 123, "display_name": "x", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": None, "password": PASSWORD},
|
||||
{
|
||||
"username": "valid_name",
|
||||
"display_name": "x",
|
||||
"password": PASSWORD,
|
||||
"is_admin": True,
|
||||
},
|
||||
{"username": "Upper_Case", "display_name": "x", "password": PASSWORD},
|
||||
{"username": "ab", "display_name": "x", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": " ", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": "я" * 101, "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": "a\u0000b", "password": PASSWORD},
|
||||
],
|
||||
)
|
||||
def test_invalid_user_payload(api: httpx.Client, body: object) -> None:
|
||||
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"text": 42},
|
||||
{"text": "привет", "sender_id": "11111111-1111-4111-8111-111111111111"},
|
||||
{},
|
||||
],
|
||||
)
|
||||
def test_invalid_message_payload(
|
||||
api: httpx.Client, make_user, make_chat, body: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json=body,
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_invalid_chat_payload(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
cases = [
|
||||
{"title": "t", "member_ids": [bob["id"]]},
|
||||
{"title": "t", "member_ids": [alice["id"], alice["id"]]},
|
||||
{
|
||||
"title": "t",
|
||||
"member_ids": [alice["id"], "11111111-1111-4111-8111-111111111111"],
|
||||
},
|
||||
{"title": "t", "member_ids": [alice["id"], "not-a-uuid"]},
|
||||
{"title": "t", "member_ids": []},
|
||||
{"title": " ", "member_ids": [alice["id"]]},
|
||||
]
|
||||
for body in cases:
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,166 @@
|
||||
"""
|
||||
Сообщения с attachment_ids: вложение только своего чата, порядок, пустой
|
||||
текст, идемпотентность; при любом отказе сообщение не появляется.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_error,
|
||||
assert_not_server_error,
|
||||
auth,
|
||||
message_headers,
|
||||
png_bytes,
|
||||
read_all_messages,
|
||||
)
|
||||
|
||||
|
||||
def history(api: httpx.Client, user: dict, chat: dict) -> list[dict]:
|
||||
items, _ = read_all_messages(api, user, chat["id"], 100)
|
||||
return items
|
||||
|
||||
|
||||
def test_message_with_attachment_is_readable_by_members(
|
||||
api: httpx.Client, make_user, make_chat, upload, send_attachments
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
attachment = upload(alice, chat)
|
||||
|
||||
response = send_attachments(alice, chat, [attachment["id"]])
|
||||
assert response.status_code == 201, response.text
|
||||
message = response.json()
|
||||
assert message["text"] == "" and message["attachment_ids"] == [attachment["id"]]
|
||||
|
||||
assert history(api, bob, chat) == [message]
|
||||
content = api.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(bob)
|
||||
)
|
||||
assert content.status_code == 200
|
||||
|
||||
|
||||
def test_any_member_may_reference_chat_attachment_and_order_is_kept(
|
||||
make_user, make_chat, upload, send_attachments
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
ids = [upload(alice, chat, png_bytes(i + 1, i + 1))["id"] for i in range(10)]
|
||||
reordered = list(reversed(ids))
|
||||
|
||||
response = send_attachments(bob, chat, reordered, text="от Боба")
|
||||
assert response.status_code == 201, response.text
|
||||
assert response.json()["attachment_ids"] == reordered
|
||||
|
||||
|
||||
def test_text_message_has_empty_attachment_ids(make_user, make_chat, send_message) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
assert send_message(alice, chat, "только текст")["attachment_ids"] == []
|
||||
|
||||
|
||||
def test_attachment_of_other_chat_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, upload, send_attachments
|
||||
) -> None:
|
||||
"""Алиса — участник обоих чатов, но файл привязан к другому чату"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice], title="Чат A")
|
||||
other = make_chat(alice, [alice], title="Чат B")
|
||||
foreign = upload(alice, other)
|
||||
own = upload(alice, chat)
|
||||
|
||||
for ids in ([foreign["id"]], [own["id"], foreign["id"]]):
|
||||
response = send_attachments(alice, chat, ids, text="чужой файл")
|
||||
assert_not_server_error(response)
|
||||
assert_error(response, 404, "not_found")
|
||||
assert history(api, alice, chat) == []
|
||||
|
||||
|
||||
def test_foreign_attachment_id_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, upload, send_attachments
|
||||
) -> None:
|
||||
"""Вложение из чата, где пользователь не участник, и несуществующее — 404"""
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
eve_chat = make_chat(eve, [eve])
|
||||
eve_attachment = upload(eve, eve_chat)
|
||||
|
||||
foreign = send_attachments(alice, chat, [eve_attachment["id"]])
|
||||
missing = send_attachments(alice, chat, [str(uuid.uuid4())])
|
||||
assert_error(foreign, 404, "not_found")
|
||||
assert_error(missing, 404, "not_found")
|
||||
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
|
||||
assert history(api, alice, chat) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"text": ""},
|
||||
{"text": " "},
|
||||
{"text": "", "attachment_ids": []},
|
||||
{"text": "x", "attachment_ids": ["not-a-uuid"]},
|
||||
{"text": "x", "attachment_ids": "a"},
|
||||
{"text": "x", "attachment_ids": None},
|
||||
{"text": "x", "attachment_ids": [str(uuid.uuid4())] * 2},
|
||||
{"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]},
|
||||
],
|
||||
ids=[
|
||||
"empty-text",
|
||||
"blank-text",
|
||||
"empty-both",
|
||||
"bad-uuid",
|
||||
"not-array",
|
||||
"null",
|
||||
"duplicates",
|
||||
"too-many",
|
||||
],
|
||||
)
|
||||
def test_invalid_attachment_ids_are_rejected(
|
||||
api: httpx.Client, make_user, make_chat, body: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=message_headers(alice)
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_idempotent_replay_with_attachments(
|
||||
api: httpx.Client, make_user, make_chat, upload, send_attachments
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
first, second = upload(alice, chat), upload(alice, chat)
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
created = send_attachments(alice, chat, [first["id"]], key=key)
|
||||
replay = send_attachments(alice, chat, [first["id"]], key=key)
|
||||
assert created.status_code == replay.status_code == 201
|
||||
assert created.json() == replay.json()
|
||||
|
||||
changed = send_attachments(alice, chat, [first["id"], second["id"]], key=key)
|
||||
assert_error(changed, 409, "conflict")
|
||||
assert history(api, alice, chat) == [created.json()]
|
||||
|
||||
|
||||
def test_missing_attachment_ids_equals_empty_list_for_idempotency(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
key = uuid.uuid4().hex
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
first = api.post(path, json={"text": "a"}, headers=message_headers(alice, key))
|
||||
second = api.post(
|
||||
path,
|
||||
json={"attachment_ids": [], "text": "a"},
|
||||
headers=message_headers(alice, key),
|
||||
)
|
||||
assert first.status_code == second.status_code == 201
|
||||
assert first.json() == second.json()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Пустые сообщения, границы длины и Unicode"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, message_headers
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", " \n\t ", " "])
|
||||
def test_empty_or_blank_message_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, text: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
history = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice))
|
||||
assert history.json()["items"] == []
|
||||
|
||||
|
||||
def test_message_length_is_counted_in_code_points(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
longest = "😀" * 4000
|
||||
assert send_message(alice, chat, longest)["text"] == longest
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "😀" * 4001},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_unicode_is_preserved(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
name = "Алиса 👩💻 é"
|
||||
alice = make_user("alice", display_name=name)
|
||||
assert alice["display_name"] == name
|
||||
chat = make_chat(alice, [alice], title="Чат 🚀 中文")
|
||||
assert chat["title"] == "Чат 🚀 中文"
|
||||
text = "Привет, мир 👋 — «кавычки» \t\n и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
|
||||
message = send_message(alice, chat, text)
|
||||
assert message["text"] == text
|
||||
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice)).json()
|
||||
assert page["items"][0]["text"] == text
|
||||
|
||||
|
||||
def test_nul_character_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""PostgreSQL text не хранит U+0000: отказ 400 до записи, а не 500"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "до\u0000после"},
|
||||
headers=message_headers(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
response = api.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "a\u0000b", "member_ids": [alice["id"]]},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_sender_is_taken_from_session(make_user, make_chat, send_message) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
message = send_message(bob, chat, "от Боба")
|
||||
assert message["sender_id"] == bob["id"]
|
||||
assert message["chat_id"] == chat["id"]
|
||||
assert message["created_at"].endswith("Z")
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Обход нескольких страниц истории и списка чатов по cursor"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, read_all_messages
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("total", "limit", "expected_pages"),
|
||||
[(7, 3, 3), (6, 3, 2), (5, 1, 5), (3, 100, 1)],
|
||||
)
|
||||
def test_walk_message_pages(
|
||||
api: httpx.Client,
|
||||
make_user,
|
||||
make_chat,
|
||||
send_message,
|
||||
total: int,
|
||||
limit: int,
|
||||
expected_pages: int,
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
sent = [send_message(alice if n % 2 else bob, chat, f"m{n}") for n in range(total)]
|
||||
|
||||
items, pages = read_all_messages(api, bob, chat["id"], limit)
|
||||
|
||||
assert pages == expected_pages
|
||||
assert items == sent
|
||||
assert len({item["id"] for item in items}) == total
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
def test_limit_can_change_between_pages(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
sent = [send_message(alice, chat, f"m{n}") for n in range(6)]
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
first = api.get(path, params={"limit": 2}, headers=auth(alice)).json()
|
||||
second = api.get(
|
||||
path, params={"limit": 4, "cursor": first["next_cursor"]}, headers=auth(alice)
|
||||
).json()
|
||||
|
||||
assert first["items"] + second["items"] == sent
|
||||
assert second["next_cursor"] is None
|
||||
|
||||
|
||||
def test_new_message_appears_after_cursor(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
send_message(alice, chat, "m0")
|
||||
send_message(alice, chat, "m1")
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
first = api.get(path, params={"limit": 1}, headers=auth(alice)).json()
|
||||
late = send_message(alice, chat, "m2")
|
||||
rest = api.get(
|
||||
path, params={"limit": 10, "cursor": first["next_cursor"]}, headers=auth(alice)
|
||||
).json()
|
||||
assert [item["text"] for item in rest["items"]] == ["m1", "m2"]
|
||||
assert rest["items"][-1] == late
|
||||
|
||||
|
||||
def test_cursor_is_bound_to_chat(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat_a = make_chat(alice, [alice], title="A")
|
||||
chat_b = make_chat(alice, [alice], title="B")
|
||||
for n in range(3):
|
||||
send_message(alice, chat_a, f"a{n}")
|
||||
cursor = api.get(
|
||||
f"/api/v1/chats/{chat_a['id']}/messages",
|
||||
params={"limit": 1},
|
||||
headers=auth(alice),
|
||||
).json()["next_cursor"]
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_b['id']}/messages",
|
||||
params={"cursor": cursor},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"params",
|
||||
[
|
||||
{"limit": 0},
|
||||
{"limit": 101},
|
||||
{"limit": "abc"},
|
||||
{"cursor": ""},
|
||||
{"cursor": "not-a-cursor"},
|
||||
{"cursor": "eyJzY29wZSI6IDF9"},
|
||||
],
|
||||
)
|
||||
def test_invalid_limit_or_cursor(
|
||||
api: httpx.Client, make_user, make_chat, params: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages", params=params, headers=auth(alice)
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_walk_chat_list_pages(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
created = [make_chat(alice, [alice], title=f"chat {n}") for n in range(5)]
|
||||
listed: list[dict] = []
|
||||
params: dict[str, str | int] = {"limit": 2}
|
||||
pages = 0
|
||||
while True:
|
||||
page = api.get("/api/v1/chats", params=params, headers=auth(alice)).json()
|
||||
listed.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
break
|
||||
params = {"limit": 2, "cursor": page["next_cursor"]}
|
||||
assert pages == 3
|
||||
assert listed == created
|
||||
|
||||
|
||||
def test_chat_cursor_is_bound_to_user(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
for n in range(2):
|
||||
make_chat(alice, [alice, bob], title=f"chat {n}")
|
||||
cursor = api.get("/api/v1/chats", params={"limit": 1}, headers=auth(alice)).json()[
|
||||
"next_cursor"
|
||||
]
|
||||
response = api.get("/api/v1/chats", params={"cursor": cursor}, headers=auth(bob))
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,188 @@
|
||||
"""
|
||||
Согласованность S3 и PostgreSQL на живом стенде.
|
||||
|
||||
Сбои внедряются напрямую в хранилища: строка pending с объектом — процесс
|
||||
упал между PUT в S3 и подтверждением в БД; объект без строки — сирота.
|
||||
Затем janitor (тот же код и ключи, что в сервисе janitor) выполняет проход
|
||||
с коротким grace period. Обрыв загрузки идёт напрямую в API-реплику, минуя
|
||||
буферизацию nginx.
|
||||
|
||||
Запуск явно: make test-storage (RUN_STORAGE_TESTS=1).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import auth, container_json, png_bytes, psql, run_janitor
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_STORAGE_TESTS") != "1",
|
||||
reason="меняет данные стенда напрямую: запускайте через make test-storage",
|
||||
)
|
||||
|
||||
# Запас на время docker exec janitor (импорт кода под лимитом CPU 0.25)
|
||||
GRACE_SECONDS = 20
|
||||
STALE_ROW_AGE_SECONDS = 300
|
||||
|
||||
PUT_OBJECTS = """
|
||||
import asyncio, json
|
||||
from infrastructure.dependencies import storage_manager
|
||||
|
||||
async def main():
|
||||
s3 = await storage_manager.create_client()
|
||||
for key in {keys!r}:
|
||||
await s3.put_object(Bucket=storage_manager.bucket, Key=key, Body=b"x")
|
||||
await storage_manager.close()
|
||||
print(json.dumps({{"put": len({keys!r})}}))
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
|
||||
EXISTING_OBJECTS = """
|
||||
import asyncio, json
|
||||
from infrastructure.dependencies import storage_manager
|
||||
|
||||
async def main():
|
||||
s3 = await storage_manager.create_client()
|
||||
found = {{}}
|
||||
for key in {keys!r}:
|
||||
try:
|
||||
await s3.head_object(Bucket=storage_manager.bucket, Key=key)
|
||||
found[key] = True
|
||||
except Exception:
|
||||
found[key] = False
|
||||
await storage_manager.close()
|
||||
print(json.dumps(found))
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
|
||||
|
||||
def put_objects(*keys: str) -> None:
|
||||
container_json("janitor", PUT_OBJECTS.format(keys=list(keys)))
|
||||
|
||||
|
||||
def existing_objects(*keys: str) -> dict[str, bool]:
|
||||
return container_json("janitor", EXISTING_OBJECTS.format(keys=list(keys)))
|
||||
|
||||
|
||||
def insert_pending(chat: dict, owner: dict, key: str, age_seconds: int) -> None:
|
||||
"""Строка, какую оставляет падение API между PUT и подтверждением"""
|
||||
psql(
|
||||
f"""
|
||||
INSERT INTO attachments
|
||||
(chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, created_at, updated_at)
|
||||
VALUES
|
||||
('{chat["id"]}', '{owner["id"]}', 'crash.png', 'image/png', 1,
|
||||
sha256('x'), '{key}', 'pending',
|
||||
clock_timestamp() - make_interval(secs => {age_seconds}),
|
||||
clock_timestamp());
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def row_status(key: str) -> str:
|
||||
return psql(f"SELECT coalesce(max(status), 'absent') FROM attachments WHERE object_key = '{key}';")
|
||||
|
||||
|
||||
def test_janitor_cleans_only_stale_unaccounted_data(
|
||||
api: httpx.Client, make_user, make_chat, upload, send_attachments
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
ready = upload(alice, chat, png_bytes(12, 12))
|
||||
linked = upload(alice, chat, png_bytes(13, 13))
|
||||
assert send_attachments(alice, chat, [linked["id"]]).status_code == 201
|
||||
|
||||
run_id = uuid.uuid4().hex
|
||||
crashed = f"originals/test-crashed-{run_id}"
|
||||
crashed_no_object = f"originals/test-crashed-before-put-{run_id}"
|
||||
orphan_old = f"originals/test-orphan-old-{run_id}"
|
||||
fresh_pending = f"originals/test-fresh-pending-{run_id}"
|
||||
orphan_fresh = f"originals/test-orphan-fresh-{run_id}"
|
||||
|
||||
# «Старые» сбои: строка старше grace по часам БД, объект — по времени ожидания.
|
||||
# Возраст меньше grace фонового сервиса janitor (900 с): строки забирает
|
||||
# только проход теста, без гонки с сервисом
|
||||
insert_pending(chat, alice, crashed, age_seconds=STALE_ROW_AGE_SECONDS)
|
||||
insert_pending(chat, alice, crashed_no_object, age_seconds=STALE_ROW_AGE_SECONDS)
|
||||
put_objects(crashed, orphan_old)
|
||||
time.sleep(GRACE_SECONDS + 2)
|
||||
|
||||
dry = run_janitor("--dry-run", "--grace-seconds", str(GRACE_SECONDS))
|
||||
assert dry["unfinished_claimed"] >= 2 and dry["orphan_objects_found"] >= 1
|
||||
assert existing_objects(crashed, orphan_old) == {crashed: True, orphan_old: True}
|
||||
|
||||
# «Свежие»: загрузка, которая могла бы ещё идти
|
||||
insert_pending(chat, alice, fresh_pending, age_seconds=0)
|
||||
put_objects(fresh_pending, orphan_fresh)
|
||||
report = run_janitor("--grace-seconds", str(GRACE_SECONDS))
|
||||
print("\nJANITOR REPORT:", json.dumps(report))
|
||||
|
||||
assert existing_objects(crashed, orphan_old, fresh_pending, orphan_fresh) == {
|
||||
crashed: False,
|
||||
orphan_old: False,
|
||||
fresh_pending: True,
|
||||
orphan_fresh: True,
|
||||
}
|
||||
assert row_status(crashed) == row_status(crashed_no_object) == "absent"
|
||||
assert row_status(fresh_pending) == "pending"
|
||||
|
||||
# Готовые вложения (в том числе привязанные к сообщению) не тронуты
|
||||
for attachment in (ready, linked):
|
||||
response = api.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
# Свежие данные становятся «старыми» и тоже убираются
|
||||
time.sleep(GRACE_SECONDS + 1)
|
||||
run_janitor("--grace-seconds", str(GRACE_SECONDS))
|
||||
assert existing_objects(fresh_pending, orphan_fresh) == {
|
||||
fresh_pending: False,
|
||||
orphan_fresh: False,
|
||||
}
|
||||
assert row_status(fresh_pending) == "absent"
|
||||
again = run_janitor("--dry-run", "--grace-seconds", str(GRACE_SECONDS))
|
||||
assert again["orphan_objects_found"] == 0
|
||||
|
||||
|
||||
INTERRUPTED_UPLOAD = """
|
||||
import json, socket
|
||||
body = {body!r}
|
||||
request = (
|
||||
"POST /api/v1/chats/{chat_id}/attachments?filename=cut.png HTTP/1.1\\r\\n"
|
||||
"Host: api\\r\\n"
|
||||
"Authorization: Bearer {token}\\r\\n"
|
||||
"Content-Type: image/png\\r\\n"
|
||||
"Content-Length: " + str(len(body)) + "\\r\\n\\r\\n"
|
||||
).encode()
|
||||
sent = 0
|
||||
with socket.create_connection(("api", 8080), timeout=5) as connection:
|
||||
connection.sendall(request)
|
||||
connection.sendall(body[: len(body) // 3])
|
||||
sent = len(body) // 3
|
||||
print(json.dumps({{"sent": sent, "declared": len(body)}}))
|
||||
"""
|
||||
|
||||
|
||||
def test_interrupted_upload_leaves_nothing(make_user, make_chat) -> None:
|
||||
"""Клиент оборвал соединение посреди тела, прямо к реплике API"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
body = list(png_bytes(400, 400, noise=True))
|
||||
result = container_json(
|
||||
"janitor",
|
||||
INTERRUPTED_UPLOAD.format(
|
||||
body=bytes(body), chat_id=chat["id"], token=alice["token"]
|
||||
),
|
||||
)
|
||||
assert 0 < result["sent"] < result["declared"]
|
||||
time.sleep(1)
|
||||
rows = psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{chat['id']}';")
|
||||
assert rows == "0"
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
Недоступность S3: контейнер s3 останавливается через docker compose
|
||||
(volume сохраняется), затем запускается снова.
|
||||
|
||||
Ожидаемое поведение: загрузка и скачивание — быстрый 503 в формате контракта,
|
||||
readiness — 503 (вложения входят в обязательный путь lab4), но метаданные
|
||||
и сообщения продолжают работать: nginx не исключает реплики по readiness.
|
||||
После восстановления незавершённых строк не остаётся: компенсация или
|
||||
janitor их дочищают.
|
||||
|
||||
Запуск явно: make test-s3-failure (RUN_FAILURE_TESTS=1).
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_error,
|
||||
auth,
|
||||
compose,
|
||||
png_bytes,
|
||||
psql,
|
||||
run_janitor,
|
||||
upload_raw,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_FAILURE_TESTS") != "1",
|
||||
reason="останавливает контейнер s3: запускайте через make test-s3-failure",
|
||||
)
|
||||
|
||||
# connect timeout 2 с × 2 попытки + проверка изображения
|
||||
BOUNDED_RESPONSE_SEC = 6
|
||||
READY_TIMEOUT_SEC = 60
|
||||
|
||||
|
||||
def unfinished_rows(chat_id: str) -> int:
|
||||
return int(
|
||||
psql(
|
||||
f"SELECT count(*) FROM attachments "
|
||||
f"WHERE chat_id = '{chat_id}' AND status <> 'ready';"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def wait_upload_works(api: httpx.Client, user: dict, chat_id: str) -> httpx.Response:
|
||||
deadline = time.monotonic() + READY_TIMEOUT_SEC
|
||||
while True:
|
||||
response = upload_raw(api, user, chat_id, png_bytes())
|
||||
if response.status_code == 201 or time.monotonic() > deadline:
|
||||
return response
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def test_s3_outage_is_isolated_and_leaves_no_garbage(
|
||||
api: httpx.Client, make_user, make_chat, upload, send_attachments
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
before = upload(alice, chat)
|
||||
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
started = time.monotonic()
|
||||
failed_upload = upload_raw(api, alice, chat["id"], png_bytes(64, 64))
|
||||
elapsed = time.monotonic() - started
|
||||
assert_error(failed_upload, 503, "unavailable")
|
||||
assert elapsed < BOUNDED_RESPONSE_SEC, elapsed
|
||||
assert "s3" not in failed_upload.json()["error"]["message"].lower()
|
||||
|
||||
download = api.get(
|
||||
f"/api/v1/attachments/{before['id']}/content", headers=auth(bob)
|
||||
)
|
||||
assert_error(download, 503, "unavailable")
|
||||
|
||||
# Путь без байтов S3 работает: метаданные и сообщения
|
||||
metadata = api.get(f"/api/v1/attachments/{before['id']}", headers=auth(bob))
|
||||
assert metadata.status_code == 200 and metadata.json() == before
|
||||
message = send_attachments(alice, chat, [before["id"]], text="S3 лежит")
|
||||
assert message.status_code == 201, message.text
|
||||
assert api.get("/health/live").status_code == 200
|
||||
started = time.monotonic()
|
||||
assert_error(api.get("/health/ready"), 503, "unavailable")
|
||||
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "s3")
|
||||
|
||||
after = wait_upload_works(api, alice, chat["id"])
|
||||
assert after.status_code == 201, after.text
|
||||
content = api.get(f"/api/v1/attachments/{before['id']}/content", headers=auth(bob))
|
||||
assert content.status_code == 200
|
||||
|
||||
# Компенсация не смогла удалить объект при лежащем S3: строка deleting
|
||||
# дочищается janitor независимо от grace period
|
||||
run_janitor()
|
||||
assert unfinished_rows(chat["id"]) == 0
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
Защита хранилища вне API: приватный bucket, ограниченные ключи API,
|
||||
закрытые административные интерфейсы, идемпотентный bootstrap.
|
||||
|
||||
Проверки заходят внутрь контейнеров стенда (docker compose exec/run),
|
||||
поэтому запускаются явно: make test-storage (RUN_STORAGE_TESTS=1).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import ROOT, auth, compose, container_json
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_STORAGE_TESTS") != "1",
|
||||
reason="заходит в контейнеры стенда: запускайте через make test-storage",
|
||||
)
|
||||
|
||||
# Порты SeaweedFS кроме S3: master, volume, filer (HTTP с веб-интерфейсами
|
||||
# и gRPC). Они слушают только loopback контейнера s3.
|
||||
ADMIN_PORTS = (9333, 19333, 8080, 18080, 8888, 18888, 8181, 9101)
|
||||
|
||||
|
||||
def test_anonymous_s3_access_is_denied(api: httpx.Client, make_user, make_chat, upload) -> None:
|
||||
"""Прямой неподписанный GET объекта (ключ известен) и списка bucket — 403"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
attachment = upload(alice, chat)
|
||||
object_key = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'psql -X -q -tA -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c '
|
||||
f"\"SELECT object_key FROM attachments WHERE id = '{attachment['id']}'\"",
|
||||
).strip()
|
||||
assert object_key.startswith("originals/")
|
||||
|
||||
result = container_json(
|
||||
"api",
|
||||
f"""
|
||||
import json, urllib.error, urllib.request
|
||||
from config import S3_BUCKET, S3_ENDPOINT
|
||||
codes = {{}}
|
||||
for name, path in {{
|
||||
"object": "/" + S3_BUCKET + "/{object_key}",
|
||||
"bucket_list": "/" + S3_BUCKET,
|
||||
"service": "/",
|
||||
}}.items():
|
||||
try:
|
||||
with urllib.request.urlopen(S3_ENDPOINT + path, timeout=3) as response:
|
||||
codes[name] = response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
codes[name] = error.code
|
||||
print(json.dumps(codes))
|
||||
""",
|
||||
)
|
||||
assert result == {"object": 403, "bucket_list": 403, "service": 403}
|
||||
# Через API участник по-прежнему скачивает файл
|
||||
content = api.get(f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice))
|
||||
assert content.status_code == 200
|
||||
|
||||
|
||||
def test_api_credentials_are_limited_to_own_bucket_objects() -> None:
|
||||
"""Ключи API: объекты своего bucket — да; bucket, политика, ACL — нет"""
|
||||
result = container_json(
|
||||
"api",
|
||||
"""
|
||||
import asyncio, json
|
||||
from infrastructure.dependencies import storage_manager
|
||||
from infrastructure.utils import storage_error_code
|
||||
|
||||
async def attempt(name, call, results):
|
||||
try:
|
||||
await call
|
||||
results[name] = "allowed"
|
||||
except Exception as error:
|
||||
results[name] = storage_error_code(error)
|
||||
|
||||
async def main():
|
||||
s3 = await storage_manager.create_client()
|
||||
bucket = storage_manager.bucket
|
||||
key = "originals/security-probe"
|
||||
policy = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
|
||||
"Principal": "*", "Action": "s3:GetObject",
|
||||
"Resource": "arn:aws:s3:::" + bucket + "/*"}]})
|
||||
results = {}
|
||||
await attempt("put_object", s3.put_object(Bucket=bucket, Key=key, Body=b"x"), results)
|
||||
await attempt("get_object", s3.get_object(Bucket=bucket, Key=key), results)
|
||||
await attempt("delete_object", s3.delete_object(Bucket=bucket, Key=key), results)
|
||||
await attempt("create_bucket", s3.create_bucket(Bucket="intruder-bucket"), results)
|
||||
await attempt("delete_bucket", s3.delete_bucket(Bucket=bucket), results)
|
||||
await attempt("put_bucket_policy", s3.put_bucket_policy(Bucket=bucket, Policy=policy), results)
|
||||
await attempt("put_bucket_acl", s3.put_bucket_acl(Bucket=bucket, ACL="public-read"), results)
|
||||
await storage_manager.close()
|
||||
print(json.dumps(results))
|
||||
|
||||
asyncio.run(main())
|
||||
""",
|
||||
)
|
||||
assert result["put_object"] == result["get_object"] == "allowed"
|
||||
assert result["delete_object"] == "allowed"
|
||||
for forbidden in ("create_bucket", "delete_bucket", "put_bucket_policy", "put_bucket_acl"):
|
||||
assert result[forbidden] == "AccessDenied", result
|
||||
|
||||
|
||||
def test_api_container_has_no_admin_credentials() -> None:
|
||||
files = compose("exec", "-T", "api", "ls", "/run/secrets").split()
|
||||
assert sorted(files) == ["s3_access_key_id", "s3_secret_access_key"]
|
||||
|
||||
|
||||
def test_admin_interfaces_are_not_reachable() -> None:
|
||||
"""Из сети storage открыт только S3 API; наружу стенда S3 не опубликован"""
|
||||
result = container_json(
|
||||
"api",
|
||||
f"""
|
||||
import json, socket
|
||||
state = {{}}
|
||||
for port in (9000,) + {ADMIN_PORTS!r}:
|
||||
try:
|
||||
socket.create_connection(("s3", port), timeout=2).close()
|
||||
state[port] = "open"
|
||||
except OSError as error:
|
||||
state[port] = type(error).__name__
|
||||
print(json.dumps(state))
|
||||
""",
|
||||
)
|
||||
assert result.pop("9000") == "open"
|
||||
assert all(value != "open" for value in result.values()), result
|
||||
|
||||
for line in compose("ps", "--format", "json", "s3").splitlines():
|
||||
publishers = json.loads(line)["Publishers"] or []
|
||||
assert all(item["PublishedPort"] == 0 for item in publishers), publishers
|
||||
|
||||
|
||||
def test_balancer_network_cannot_reach_storage() -> None:
|
||||
"""nginx (сеть edge) не видит S3: клиентский трафик идёт только через API"""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "exec", "-T", "nginx",
|
||||
"wget", "-q", "-T", "2", "-O", "/dev/null", "http://s3:9000/"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
assert result.returncode != 0
|
||||
|
||||
|
||||
def test_bucket_bootstrap_is_idempotent() -> None:
|
||||
for _ in range(2):
|
||||
output = compose("run", "--rm", "--no-deps", "s3-bootstrap")
|
||||
assert "уже существует" in output
|
||||
assert "приватен" in output
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Гонка регистрации одинакового username и rollback создания чата"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth, psql, unique_password, unique_username
|
||||
|
||||
PARALLEL_REGISTRATIONS = 20
|
||||
|
||||
|
||||
async def _register_concurrently(base_url: str, username: str) -> list[int]:
|
||||
"""Все запросы стартуют по одному сигналу, у каждого свой пароль"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def register(client: httpx.AsyncClient) -> int:
|
||||
await start.wait()
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "Гонка",
|
||||
"password": unique_password(),
|
||||
}
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
return response.status_code
|
||||
|
||||
limits = httpx.Limits(max_connections=PARALLEL_REGISTRATIONS)
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, timeout=30, limits=limits
|
||||
) as client:
|
||||
tasks = [
|
||||
asyncio.create_task(register(client)) for _ in range(PARALLEL_REGISTRATIONS)
|
||||
]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
return list(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
def test_same_username_race_creates_exactly_one_user(base_url: str) -> None:
|
||||
username = unique_username("race")
|
||||
statuses = asyncio.run(_register_concurrently(base_url, username))
|
||||
stored = psql(f"SELECT count(*) FROM users WHERE username = '{username}';")
|
||||
print(
|
||||
"\nREGISTRATION RACE:",
|
||||
json.dumps(
|
||||
{
|
||||
"requests": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"status_409": statuses.count(409),
|
||||
"rows_in_db": int(stored),
|
||||
}
|
||||
),
|
||||
)
|
||||
assert statuses.count(201) == 1
|
||||
assert statuses.count(409) == PARALLEL_REGISTRATIONS - 1
|
||||
assert stored == "1"
|
||||
|
||||
|
||||
def test_failed_chat_creation_is_rolled_back(api: httpx.Client, make_user) -> None:
|
||||
"""
|
||||
Строка chats вставляется первой, затем участники нарушают FK (неизвестный
|
||||
пользователь в конце списка). После 400 в БД не должно остаться ни чата
|
||||
с этим title, ни его участников: откатилась вся транзакция.
|
||||
"""
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"rollback-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}
|
||||
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
|
||||
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert psql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0"
|
||||
orphan_members = psql(
|
||||
"SELECT count(*) FROM chat_members m "
|
||||
"LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL;"
|
||||
)
|
||||
assert orphan_members == "0"
|
||||
listed = api.get("/api/v1/chats", params={"limit": 100}, headers=auth(alice))
|
||||
assert all(chat["title"] != title for chat in listed.json()["items"])
|
||||
|
||||
|
||||
def test_successful_chat_creation_commits_all_members(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"commit-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [bob["id"], alice["id"]]}
|
||||
chat = api.post("/api/v1/chats", json=body, headers=auth(alice)).json()
|
||||
assert chat["member_ids"] == [bob["id"], alice["id"]]
|
||||
members = psql(f"SELECT count(*) FROM chat_members WHERE chat_id = '{chat['id']}';")
|
||||
assert members == "2"
|
||||
again = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(bob)).json()
|
||||
assert again == chat
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Регистрация, дубликат username и идентификация только через Bearer"""
|
||||
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_error,
|
||||
assert_unauthorized,
|
||||
auth,
|
||||
public_user,
|
||||
unique_password,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
|
||||
def test_duplicate_username_is_conflict(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("dup")
|
||||
body = {
|
||||
"username": alice["username"],
|
||||
"display_name": "B",
|
||||
"password": unique_password(),
|
||||
}
|
||||
assert_error(api.post("/api/v1/users", json=body), 409, "conflict")
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.json()["display_name"] == alice["display_name"]
|
||||
|
||||
|
||||
def test_registration_never_returns_password(api: httpx.Client) -> None:
|
||||
password = unique_password()
|
||||
body = {
|
||||
"username": unique_username("pw"),
|
||||
"display_name": "x",
|
||||
"password": password,
|
||||
}
|
||||
response = api.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201
|
||||
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
|
||||
assert password not in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"password",
|
||||
[None, "", "короткий", "x" * 11, "x" * 129, 123456789012],
|
||||
)
|
||||
def test_invalid_password_is_rejected(api: httpx.Client, password: object) -> None:
|
||||
body: dict[str, object] = {"username": unique_username("pw"), "display_name": "x"}
|
||||
if password is not None:
|
||||
body["password"] = password
|
||||
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
|
||||
|
||||
def test_password_length_is_counted_in_code_points(api: httpx.Client) -> None:
|
||||
for password in ("😀" * 12, "😀" * 128):
|
||||
body = {
|
||||
"username": unique_username("pw"),
|
||||
"display_name": "x",
|
||||
"password": password,
|
||||
}
|
||||
assert api.post("/api/v1/users", json=body).status_code == 201
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[
|
||||
{},
|
||||
{"Authorization": ""},
|
||||
{"Authorization": "Bearer"},
|
||||
{"Authorization": "Bearer not-a-real-token"},
|
||||
{"Authorization": "Bearer " + "x" * 5000},
|
||||
{"Authorization": "Token abc"},
|
||||
],
|
||||
)
|
||||
def test_missing_or_unknown_token_is_unauthorized(
|
||||
api: httpx.Client, headers: dict
|
||||
) -> None:
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
|
||||
|
||||
|
||||
def test_x_user_id_gives_no_access(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}))
|
||||
me = api.get("/api/v1/users/me", headers={**auth(alice), "X-User-Id": eve["id"]})
|
||||
assert me.json()["id"] == alice["id"]
|
||||
unknown = {"X-User-Id": str(uuid.uuid4())}
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=unknown))
|
||||
|
||||
|
||||
def test_current_user(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200
|
||||
assert me.json() == public_user(alice)
|
||||
@@ -0,0 +1,12 @@
|
||||
"""
|
||||
Unit-тесты слоя сервисов без стенда: зависимости заменены фейками интерфейсов.
|
||||
Конфигурация берётся из .env.example; сеть, PostgreSQL и S3 не нужны.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
os.environ["ENV_FILE"] = str(ROOT / ".env.example")
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
@@ -0,0 +1,219 @@
|
||||
"""
|
||||
In-memory реализации интерфейсов с внедрением отказов.
|
||||
|
||||
fail — имена методов, которые бросают UnavailableError (как репозитории
|
||||
при недоступной БД/S3); hang — методы, которые зависают.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import BinaryIO
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from domain import (
|
||||
AttachmentSchema,
|
||||
AttachmentStatus,
|
||||
ChatSchema,
|
||||
NewAttachmentSchema,
|
||||
PageKey,
|
||||
StoredAttachmentSchema,
|
||||
UnfinishedUploadSchema,
|
||||
)
|
||||
from domain.errors import UnavailableError
|
||||
from interfaces import AttachmentRepository, ChatRepository, ObjectStorage, StoredObject
|
||||
|
||||
HANG_SEC = 3600
|
||||
|
||||
|
||||
class FaultInjection:
|
||||
def __init__(self) -> None:
|
||||
self.fail: set[str] = set()
|
||||
self.hang: set[str] = set()
|
||||
self.calls: list[str] = []
|
||||
|
||||
async def _enter(self, name: str) -> None:
|
||||
self.calls.append(name)
|
||||
if name in self.hang:
|
||||
await asyncio.sleep(HANG_SEC)
|
||||
if name in self.fail:
|
||||
raise UnavailableError()
|
||||
|
||||
|
||||
class FakeChatRepository(ChatRepository):
|
||||
"""Пользователь — участник любого чата, кроме перечисленных в foreign"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.foreign: set[UUID] = set()
|
||||
|
||||
async def create(self, title: str, created_by: UUID, member_ids: list[UUID]) -> ChatSchema:
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
|
||||
if chat_id in self.foreign:
|
||||
return None
|
||||
return ChatSchema(
|
||||
id=chat_id, title="chat", member_ids=[member_id], created_at=datetime.now(UTC)
|
||||
)
|
||||
|
||||
async def list_for_member(
|
||||
self, member_id: UUID, after: PageKey | None, limit: int
|
||||
) -> list[ChatSchema]:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.rows: dict[UUID, dict] = {}
|
||||
self.ready_returns_none = False
|
||||
|
||||
def add_row(self, object_key: str, status: AttachmentStatus, age_seconds: float) -> UUID:
|
||||
attachment_id = uuid4()
|
||||
self.rows[attachment_id] = {
|
||||
"status": status,
|
||||
"object_key": object_key,
|
||||
"created_at": datetime.now(UTC) - timedelta(seconds=age_seconds),
|
||||
"new": None,
|
||||
}
|
||||
return attachment_id
|
||||
|
||||
async def create_pending(self, attachment: NewAttachmentSchema) -> UUID:
|
||||
await self._enter("create_pending")
|
||||
attachment_id = self.add_row(attachment.object_key, AttachmentStatus.PENDING, 0)
|
||||
self.rows[attachment_id]["new"] = attachment
|
||||
return attachment_id
|
||||
|
||||
async def mark_ready(self, attachment_id: UUID, grace_seconds: int) -> AttachmentSchema | None:
|
||||
await self._enter("mark_ready")
|
||||
row = self.rows.get(attachment_id)
|
||||
if self.ready_returns_none or row is None or row["status"] != AttachmentStatus.PENDING:
|
||||
return None
|
||||
if row["created_at"] <= datetime.now(UTC) - timedelta(seconds=grace_seconds):
|
||||
return None
|
||||
row["status"] = AttachmentStatus.READY
|
||||
new: NewAttachmentSchema = row["new"]
|
||||
return AttachmentSchema(
|
||||
id=attachment_id,
|
||||
chat_id=new.chat_id,
|
||||
owner_id=new.owner_id,
|
||||
filename=new.filename,
|
||||
content_type=new.content_type,
|
||||
size_bytes=new.size_bytes,
|
||||
sha256=new.sha256.hex(),
|
||||
created_at=row["created_at"],
|
||||
updated_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
async def claim_pending(self, attachment_id: UUID) -> UnfinishedUploadSchema | None:
|
||||
await self._enter("claim_pending")
|
||||
row = self.rows.get(attachment_id)
|
||||
if row is None or row["status"] != AttachmentStatus.PENDING:
|
||||
return None
|
||||
row["status"] = AttachmentStatus.DELETING
|
||||
return UnfinishedUploadSchema(id=attachment_id, object_key=row["object_key"])
|
||||
|
||||
def _unfinished(self, grace_seconds: int) -> list[UUID]:
|
||||
threshold = datetime.now(UTC) - timedelta(seconds=grace_seconds)
|
||||
return [
|
||||
attachment_id
|
||||
for attachment_id, row in self.rows.items()
|
||||
if row["status"] == AttachmentStatus.DELETING
|
||||
or (row["status"] == AttachmentStatus.PENDING and row["created_at"] < threshold)
|
||||
]
|
||||
|
||||
async def claim_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
|
||||
await self._enter("claim_unfinished")
|
||||
# Повторный вызов в том же проходе не должен возвращать те же строки
|
||||
claimed = [
|
||||
attachment_id
|
||||
for attachment_id in self._unfinished(grace_seconds)
|
||||
if not self.rows[attachment_id].get("claimed_now")
|
||||
][:limit]
|
||||
for attachment_id in claimed:
|
||||
self.rows[attachment_id]["status"] = AttachmentStatus.DELETING
|
||||
self.rows[attachment_id]["claimed_now"] = True
|
||||
return [
|
||||
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"]) for i in claimed
|
||||
]
|
||||
|
||||
async def list_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
|
||||
await self._enter("list_unfinished")
|
||||
return [
|
||||
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
|
||||
for i in self._unfinished(grace_seconds)[:limit]
|
||||
]
|
||||
|
||||
async def delete_claimed(self, attachment_ids: list[UUID]) -> int:
|
||||
await self._enter("delete_claimed")
|
||||
deleted = [
|
||||
i
|
||||
for i in attachment_ids
|
||||
if i in self.rows and self.rows[i]["status"] == AttachmentStatus.DELETING
|
||||
]
|
||||
for attachment_id in deleted:
|
||||
del self.rows[attachment_id]
|
||||
return len(deleted)
|
||||
|
||||
async def get_for_member(
|
||||
self, attachment_id: UUID, member_id: UUID
|
||||
) -> StoredAttachmentSchema | None:
|
||||
raise NotImplementedError
|
||||
|
||||
async def find_known_keys(self, object_keys: list[str]) -> set[str]:
|
||||
await self._enter("find_known_keys")
|
||||
known = {row["object_key"] for row in self.rows.values()}
|
||||
return {key for key in object_keys if key in known}
|
||||
|
||||
def statuses(self) -> list[str]:
|
||||
return sorted(row["status"] for row in self.rows.values())
|
||||
|
||||
|
||||
class FakeStoredObject(StoredObject):
|
||||
def __init__(self, data: bytes) -> None:
|
||||
self._data = data
|
||||
self.content_length = len(data)
|
||||
|
||||
async def iter_chunks(self) -> AsyncIterator[bytes]:
|
||||
yield self._data
|
||||
|
||||
async def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class FakeObjectStorage(FaultInjection, ObjectStorage):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.objects: dict[str, tuple[bytes, datetime]] = {}
|
||||
|
||||
def add_object(self, key: str, age_seconds: float) -> None:
|
||||
self.objects[key] = (b"x", datetime.now(UTC) - timedelta(seconds=age_seconds))
|
||||
|
||||
async def put(
|
||||
self, key: str, body: BinaryIO, size: int, content_type: str, sha256: bytes
|
||||
) -> None:
|
||||
# Как S3: объект появляется до того, как вызывающий получит ответ
|
||||
self.objects[key] = (body.read(), datetime.now(UTC))
|
||||
await self._enter("put")
|
||||
|
||||
async def open(self, key: str) -> StoredObject | None:
|
||||
await self._enter("open")
|
||||
stored = self.objects.get(key)
|
||||
return FakeStoredObject(stored[0]) if stored else None
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
await self._enter("delete")
|
||||
self.objects.pop(key, None)
|
||||
|
||||
async def list_objects(self, prefix: str) -> AsyncIterator[tuple[str, datetime]]:
|
||||
await self._enter("list_objects")
|
||||
for key, (_, modified_at) in list(self.objects.items()):
|
||||
if key.startswith(prefix):
|
||||
yield key, modified_at
|
||||
|
||||
|
||||
async def chunks_of(data: bytes, size: int = 64 * 1024) -> AsyncIterator[bytes]:
|
||||
stream = io.BytesIO(data)
|
||||
while chunk := stream.read(size):
|
||||
yield chunk
|
||||
@@ -0,0 +1,261 @@
|
||||
"""
|
||||
Согласованность S3 и БД при загрузке: любой отказ после записи строки
|
||||
не оставляет неучтённых объектов — компенсация сразу или janitor позже.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fakes import (
|
||||
FakeAttachmentRepository,
|
||||
FakeChatRepository,
|
||||
FakeObjectStorage,
|
||||
chunks_of,
|
||||
)
|
||||
from PIL import Image
|
||||
|
||||
from domain import (
|
||||
AttachmentStatus,
|
||||
AttachmentVariant,
|
||||
StoredAttachmentSchema,
|
||||
UserSchema,
|
||||
)
|
||||
from domain.errors import (
|
||||
InvalidRequestError,
|
||||
NotFoundError,
|
||||
PayloadTooLargeError,
|
||||
UnavailableError,
|
||||
UnsupportedMediaTypeError,
|
||||
)
|
||||
from infrastructure.media import ImageInspector
|
||||
from infrastructure.services import AttachmentService, StorageReconciler
|
||||
|
||||
MAX_BYTES = 1024 * 1024
|
||||
GRACE_SECONDS = 900
|
||||
USER = UserSchema(
|
||||
id=uuid4(), username="alice", display_name="Алиса", created_at=datetime.now(UTC)
|
||||
)
|
||||
|
||||
|
||||
def png(width: int = 8, height: int = 8) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
Image.new("RGB", (width, height), (1, 2, 3)).save(buffer, "PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class Stand:
|
||||
"""Сервис с фейками; inspector настоящий"""
|
||||
|
||||
def __init__(self, store_timeout: float = 5) -> None:
|
||||
self.chats = FakeChatRepository()
|
||||
self.attachments = FakeAttachmentRepository()
|
||||
self.storage = FakeObjectStorage()
|
||||
self.inspector = ImageInspector(workers=1, max_pixels=1_000_000)
|
||||
self.service = AttachmentService(
|
||||
self.chats,
|
||||
self.attachments,
|
||||
self.storage,
|
||||
self.inspector,
|
||||
max_upload_bytes=MAX_BYTES,
|
||||
spool_memory_bytes=1024,
|
||||
store_timeout_seconds=store_timeout,
|
||||
pending_grace_seconds=GRACE_SECONDS,
|
||||
)
|
||||
|
||||
async def upload(self, data: bytes | None = None, content_type: str = "image/png"):
|
||||
data = data if data is not None else png()
|
||||
return await self.service.upload(
|
||||
USER, uuid4(), "a.png", content_type, len(data), chunks_of(data, 100)
|
||||
)
|
||||
|
||||
async def reconcile(self, grace_seconds: int = GRACE_SECONDS):
|
||||
reconciler = StorageReconciler(self.attachments, self.storage, grace_seconds)
|
||||
return await reconciler.run_once()
|
||||
|
||||
|
||||
def run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
def test_success_stores_object_and_ready_row() -> None:
|
||||
stand = Stand()
|
||||
data = png()
|
||||
attachment = run(stand.upload(data))
|
||||
assert attachment.sha256 == hashlib.sha256(data).hexdigest()
|
||||
assert stand.attachments.statuses() == [AttachmentStatus.READY]
|
||||
[(stored, _)] = stand.storage.objects.values()
|
||||
assert stored == data
|
||||
[key] = stand.storage.objects
|
||||
assert key.startswith("originals/") and "a.png" not in key
|
||||
# Строка записана до PUT, подтверждена после
|
||||
assert stand.attachments.calls[:2] == ["create_pending", "mark_ready"]
|
||||
|
||||
|
||||
def test_s3_failure_after_write_is_compensated() -> None:
|
||||
"""PUT дошёл до S3, но ответ — ошибка: объект удаляется, строка тоже"""
|
||||
stand = Stand()
|
||||
stand.storage.fail.add("put")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert stand.storage.objects == {}
|
||||
assert stand.attachments.rows == {}
|
||||
|
||||
|
||||
def test_db_failure_between_s3_and_commit_is_compensated() -> None:
|
||||
"""Объект записан в S3, подтверждение в БД не прошло"""
|
||||
stand = Stand()
|
||||
stand.attachments.fail.add("mark_ready")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert stand.storage.objects == {}
|
||||
assert stand.attachments.rows == {}
|
||||
|
||||
|
||||
def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
|
||||
"""
|
||||
БД пропала после PUT: ни подтвердить, ни компенсировать. Объект учтён
|
||||
строкой pending; janitor после grace period удаляет и объект, и строку.
|
||||
"""
|
||||
stand = Stand()
|
||||
stand.attachments.fail.update({"mark_ready", "claim_pending"})
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert len(stand.storage.objects) == 1
|
||||
assert stand.attachments.statuses() == [AttachmentStatus.PENDING]
|
||||
|
||||
stand.attachments.fail.clear()
|
||||
fresh = run(stand.reconcile(GRACE_SECONDS))
|
||||
assert fresh.unfinished_claimed == 0, "свежая загрузка не трогается"
|
||||
assert len(stand.storage.objects) == 1
|
||||
|
||||
report = run(stand.reconcile(grace_seconds=0))
|
||||
assert report.unfinished_objects_deleted == report.unfinished_rows_deleted == 1
|
||||
assert stand.storage.objects == {} and stand.attachments.rows == {}
|
||||
|
||||
|
||||
def test_s3_down_during_compensation_leaves_deleting_row_for_janitor() -> None:
|
||||
stand = Stand()
|
||||
stand.attachments.fail.add("mark_ready")
|
||||
stand.storage.fail.add("delete")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert stand.attachments.statuses() == [AttachmentStatus.DELETING]
|
||||
assert len(stand.storage.objects) == 1
|
||||
|
||||
stand.storage.fail.clear()
|
||||
# deleting очищается независимо от возраста
|
||||
report = run(stand.reconcile(GRACE_SECONDS))
|
||||
assert report.unfinished_rows_deleted == 1
|
||||
assert stand.storage.objects == {} and stand.attachments.rows == {}
|
||||
|
||||
|
||||
def test_store_timeout_is_compensated() -> None:
|
||||
stand = Stand(store_timeout=0.2)
|
||||
stand.storage.hang.add("put")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert stand.storage.objects == {} and stand.attachments.rows == {}
|
||||
|
||||
|
||||
def test_cancelled_upload_is_compensated() -> None:
|
||||
"""Остановка реплики посреди PUT: задача отменяется, компенсация выполняется"""
|
||||
stand = Stand()
|
||||
stand.storage.hang.add("put")
|
||||
|
||||
async def scenario() -> None:
|
||||
task = asyncio.create_task(stand.upload())
|
||||
while "put" not in stand.storage.calls:
|
||||
await asyncio.sleep(0.01)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
run(scenario())
|
||||
assert stand.storage.objects == {} and stand.attachments.rows == {}
|
||||
|
||||
|
||||
def test_upload_claimed_by_janitor_is_not_confirmed() -> None:
|
||||
stand = Stand()
|
||||
stand.attachments.ready_returns_none = True
|
||||
with pytest.raises(UnavailableError):
|
||||
run(stand.upload())
|
||||
assert stand.storage.objects == {} and stand.attachments.rows == {}
|
||||
|
||||
|
||||
def test_validation_errors_store_nothing() -> None:
|
||||
stand = Stand()
|
||||
cases = [
|
||||
(png(), "image/jpeg", UnsupportedMediaTypeError),
|
||||
(b"not an image", "image/png", UnsupportedMediaTypeError),
|
||||
(png()[:40], "image/png", UnsupportedMediaTypeError),
|
||||
(png(2000, 1000), "image/png", PayloadTooLargeError),
|
||||
(b"", "image/png", InvalidRequestError),
|
||||
]
|
||||
for data, content_type, error in cases:
|
||||
with pytest.raises(error):
|
||||
run(stand.upload(data, content_type))
|
||||
assert stand.storage.objects == {} and stand.attachments.rows == {}
|
||||
assert "create_pending" not in stand.attachments.calls
|
||||
|
||||
|
||||
def test_declared_length_over_limit_is_rejected_without_reading() -> None:
|
||||
stand = Stand()
|
||||
consumed = []
|
||||
|
||||
async def body() -> AsyncIterator[bytes]:
|
||||
consumed.append(True)
|
||||
yield b"x"
|
||||
|
||||
with pytest.raises(PayloadTooLargeError):
|
||||
run(
|
||||
stand.service.upload(
|
||||
USER, uuid4(), "a.png", "image/png", MAX_BYTES + 1, body()
|
||||
)
|
||||
)
|
||||
assert consumed == []
|
||||
|
||||
|
||||
def test_streamed_body_over_limit_stops_reading() -> None:
|
||||
"""Без Content-Length чтение обрывается на первом байте сверх лимита"""
|
||||
stand = Stand()
|
||||
chunks_read = 0
|
||||
|
||||
async def endless() -> AsyncIterator[bytes]:
|
||||
nonlocal chunks_read
|
||||
while True:
|
||||
chunks_read += 1
|
||||
yield b"\x00" * 64 * 1024
|
||||
|
||||
with pytest.raises(PayloadTooLargeError):
|
||||
run(stand.service.upload(USER, uuid4(), "a.png", "image/png", None, endless()))
|
||||
assert chunks_read == MAX_BYTES // (64 * 1024) + 1
|
||||
|
||||
|
||||
def test_foreign_chat_is_404_before_reading_body() -> None:
|
||||
stand = Stand()
|
||||
chat_id = uuid4()
|
||||
stand.chats.foreign.add(chat_id)
|
||||
with pytest.raises(NotFoundError):
|
||||
run(stand.service.upload(USER, chat_id, "a.png", "image/png", 10, chunks_of(b"")))
|
||||
|
||||
|
||||
def test_missing_variant_is_404() -> None:
|
||||
stand = Stand()
|
||||
attachment = run(stand.upload())
|
||||
|
||||
async def get_for_member(attachment_id, member_id):
|
||||
[key] = stand.storage.objects
|
||||
return StoredAttachmentSchema(attachment=attachment, object_key=key)
|
||||
|
||||
stand.attachments.get_for_member = get_for_member
|
||||
_, content = run(
|
||||
stand.service.open_content(USER, attachment.id, AttachmentVariant.ORIGINAL)
|
||||
)
|
||||
assert content.content_length == attachment.size_bytes
|
||||
with pytest.raises(NotFoundError):
|
||||
run(stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL))
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
Janitor: незавершённые загрузки и сироты удаляются только после grace period;
|
||||
готовые и свежие вложения не трогаются; dry-run ничего не меняет.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
from fakes import FakeAttachmentRepository, FakeObjectStorage
|
||||
|
||||
from domain import AttachmentStatus
|
||||
from domain.errors import UnavailableError
|
||||
from infrastructure.services import StorageReconciler
|
||||
|
||||
GRACE = 600
|
||||
OLD = 3600
|
||||
FRESH = 1
|
||||
|
||||
|
||||
def build() -> tuple[FakeAttachmentRepository, FakeObjectStorage]:
|
||||
rows, storage = FakeAttachmentRepository(), FakeObjectStorage()
|
||||
cases = {
|
||||
"originals/ready-old": (AttachmentStatus.READY, OLD),
|
||||
"originals/ready-fresh": (AttachmentStatus.READY, FRESH),
|
||||
"originals/pending-old": (AttachmentStatus.PENDING, OLD),
|
||||
"originals/pending-fresh": (AttachmentStatus.PENDING, FRESH),
|
||||
"originals/deleting-fresh": (AttachmentStatus.DELETING, FRESH),
|
||||
}
|
||||
for key, (status, age) in cases.items():
|
||||
rows.add_row(key, status, age)
|
||||
storage.add_object(key, age)
|
||||
# pending без объекта: процесс упал до PUT
|
||||
rows.add_row("originals/pending-no-object", AttachmentStatus.PENDING, OLD)
|
||||
storage.add_object("originals/orphan-old", OLD)
|
||||
storage.add_object("originals/orphan-fresh", FRESH)
|
||||
storage.add_object("other/not-ours", OLD)
|
||||
return rows, storage
|
||||
|
||||
|
||||
def run(rows, storage, dry_run: bool = False):
|
||||
return asyncio.run(StorageReconciler(rows, storage, GRACE).run_once(dry_run))
|
||||
|
||||
|
||||
def test_reconcile_removes_only_stale_unaccounted_data() -> None:
|
||||
rows, storage = build()
|
||||
report = run(rows, storage)
|
||||
|
||||
assert sorted(storage.objects) == [
|
||||
"originals/orphan-fresh",
|
||||
"originals/pending-fresh",
|
||||
"originals/ready-fresh",
|
||||
"originals/ready-old",
|
||||
"other/not-ours",
|
||||
]
|
||||
assert sorted(row["object_key"] for row in rows.rows.values()) == [
|
||||
"originals/pending-fresh",
|
||||
"originals/ready-fresh",
|
||||
"originals/ready-old",
|
||||
]
|
||||
assert report.unfinished_claimed == 3
|
||||
assert report.unfinished_rows_deleted == 3
|
||||
assert report.orphan_objects_found == report.orphan_objects_deleted == 1
|
||||
|
||||
|
||||
def test_dry_run_changes_nothing() -> None:
|
||||
rows, storage = build()
|
||||
before_rows = {k: dict(v) for k, v in rows.rows.items()}
|
||||
before_objects = dict(storage.objects)
|
||||
report = run(rows, storage, dry_run=True)
|
||||
assert rows.rows == before_rows and storage.objects == before_objects
|
||||
assert report.unfinished_claimed == 3 and report.orphan_objects_found == 1
|
||||
assert report.orphan_objects_deleted == 0
|
||||
|
||||
|
||||
def test_second_run_is_noop() -> None:
|
||||
rows, storage = build()
|
||||
run(rows, storage)
|
||||
report = run(rows, storage)
|
||||
assert report.unfinished_claimed == 0 and report.orphan_objects_found == 0
|
||||
|
||||
|
||||
def test_interrupted_cleanup_is_resumed() -> None:
|
||||
"""S3 упал после claim: строки остаются deleting и дочищаются в следующий раз"""
|
||||
rows, storage = build()
|
||||
storage.fail.add("delete")
|
||||
with pytest.raises(UnavailableError):
|
||||
run(rows, storage)
|
||||
assert AttachmentStatus.PENDING not in [
|
||||
row["status"] for row in rows.rows.values() if "old" in row["object_key"]
|
||||
]
|
||||
storage.fail.clear()
|
||||
for row in rows.rows.values():
|
||||
row.pop("claimed_now", None)
|
||||
run(rows, storage)
|
||||
assert not any("old" in key and "ready" not in key for key in storage.objects)
|
||||
assert all(row["status"] != AttachmentStatus.DELETING for row in rows.rows.values())
|
||||
Reference in New Issue
Block a user