This commit is contained in:
k00kzaAntonovaIra
2026-11-02 20:05:33 +03:00
parent 0ab3a341aa
commit e3ff3b25ce
145 changed files with 9724 additions and 473 deletions
+273
View File
@@ -0,0 +1,273 @@
"""Общие фикстуры тестов.
Тесты работают с настоящим PostgreSQL (отдельная БД messenger_test) и,
если задан TEST_CACHE_URL, с Redis.
"""
import asyncio
import base64
import os
import uuid
from pathlib import Path
from typing import Optional
import asyncpg
import pytest
from fastapi.testclient import TestClient
from app.config import Settings
from app.main import create_app
from app.db import create_engine
from app.migrate import run_migrations
ROOT = Path(__file__).resolve().parents[1]
TEST_DB_NAME = "messenger_test"
def read_dotenv() -> dict:
"""Прочитать .env из корня проекта в словарь."""
values = {}
path = ROOT / ".env"
if path.exists():
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, _, value = line.partition("=")
values[key.strip()] = value.strip()
return values
def database_parts() -> dict:
"""Параметры подключения к тестовой БД из TEST_DB_* или .env."""
env = read_dotenv()
return {
"user": os.environ.get("TEST_DB_USER", env.get("POSTGRES_USER", "messenger")),
"password": os.environ.get(
"TEST_DB_PASSWORD", env.get("POSTGRES_PASSWORD", "")
),
"host": os.environ.get("TEST_DB_HOST", "127.0.0.1"),
"port": int(os.environ.get("TEST_DB_PORT", "5433")),
}
def sqlalchemy_url(database: str = TEST_DB_NAME) -> str:
"""URL тестовой БД для SQLAlchemy."""
p = database_parts()
return "postgresql+asyncpg://%s:%s@%s:%d/%s" % (
p["user"],
p["password"],
p["host"],
p["port"],
database,
)
@pytest.fixture(scope="session", autouse=True)
def test_database():
"""Проверить доступность PostgreSQL и создать тестовую БД."""
p = database_parts()
async def prepare():
conn = await asyncpg.connect(
user=p["user"],
password=p["password"],
host=p["host"],
port=p["port"],
database="postgres",
timeout=5,
)
try:
exists = await conn.fetchval(
"SELECT 1 FROM pg_database WHERE datname = $1", TEST_DB_NAME
)
if not exists:
await conn.execute(
"CREATE DATABASE \"%s\" TEMPLATE template0 ENCODING 'UTF8'"
% TEST_DB_NAME
)
finally:
await conn.close()
try:
asyncio.run(prepare())
async def migrate():
engine = create_engine(make_settings())
try:
await run_migrations(engine)
finally:
await engine.dispose()
asyncio.run(migrate())
except Exception as error:
pytest.exit(
"PostgreSQL недоступен на %s:%s (%s). Запустите БД: "
"docker compose --env-file .env up -d db"
% (p["host"], p["port"], type(error).__name__),
returncode=2,
)
CACHE_URL = os.environ.get("TEST_CACHE_URL", "")
def make_settings(**overrides) -> Settings:
"""Настройки приложения для тестов с переопределением полей."""
base = Settings.from_env(
{
"DATABASE_URL": sqlalchemy_url(),
"DB_STARTUP_WAIT_SECONDS": "5",
"LOG_LEVEL": "INFO",
"CACHE_URL": CACHE_URL,
}
)
return Settings(**{**base.__dict__, **overrides})
def run_sql(query: str, *args):
"""Выполнить SQL в тестовой БД напрямую и вернуть строки."""
p = database_parts()
async def go():
conn = await asyncpg.connect(
user=p["user"],
password=p["password"],
host=p["host"],
port=p["port"],
database=TEST_DB_NAME,
timeout=5,
)
try:
return await conn.fetch(query, *args)
finally:
await conn.close()
return asyncio.run(go())
@pytest.fixture(scope="session")
def client(test_database):
"""Клиент приложения, общий для всего прогона."""
with TestClient(
create_app(make_settings()), raise_server_exceptions=False
) as test_client:
yield test_client
class Person:
"""Зарегистрированный пользователь с токеном и заголовками."""
def __init__(self, data: dict, password: str, token: str):
self.data = data
self.id = data["id"]
self.username = data["username"]
self.password = password
self.token = token
self._headers = {"Authorization": "Bearer " + token}
@property
def headers(self):
"""Новый ключ на новую операцию; тесты повторов задают ключ явно."""
return {**self._headers, "Idempotency-Key": uuid.uuid4().hex}
def basic_header(username: str, password: str) -> dict:
"""Заголовок Authorization: Basic."""
raw = (username + ":" + password).encode("utf-8")
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
def register_and_login(client: TestClient, name: str = "") -> Person:
"""Зарегистрировать уникального пользователя и войти."""
username = ("u_" + name + "_" + uuid.uuid4().hex[:10]).lower()
password = "T3st-pass-" + uuid.uuid4().hex
created = client.post(
"/api/v1/users",
json={
"username": username,
"display_name": "Тест " + name,
"password": password,
},
)
assert created.status_code == 201, created.text
session = client.post(
"/api/v1/auth/sessions", headers=basic_header(username, password)
)
assert session.status_code == 201, session.text
return Person(created.json(), password, session.json()["token"])
@pytest.fixture
def make_user(client):
"""Фабрика пользователей."""
return lambda name="": register_and_login(client, name)
@pytest.fixture
def make_chat(client):
"""Фабрика чатов."""
def factory(owner: Person, *others: Person, title: str = "Чат") -> dict:
members = [owner.id] + [p.id for p in others]
reply = client.post(
"/api/v1/chats",
json={"title": title, "member_ids": members},
headers=owner.headers,
)
assert reply.status_code == 201, reply.text
return reply.json()
return factory
@pytest.fixture
def alice(make_user):
"""Пользователь alice."""
return make_user("alice")
@pytest.fixture
def bob(make_user):
"""Пользователь bob."""
return make_user("bob")
@pytest.fixture
def eve(make_user):
"""Пользователь eve, не состоящий в чате."""
return make_user("eve")
@pytest.fixture
def chat(make_chat, alice, bob):
"""Чат alice и bob."""
return make_chat(alice, bob)
@pytest.fixture
def log_lines():
"""Собрать сообщения лога приложения."""
import logging
lines = []
class Collector(logging.Handler):
def emit(self, record):
lines.append(record.getMessage())
handler = Collector()
logger = logging.getLogger("messenger")
logger.addHandler(handler)
yield lines
logger.removeHandler(handler)
def assert_error(reply, status: int, code: str):
"""Проверить статус, код и формат тела ошибки."""
assert reply.status_code == status, reply.text
body = reply.json()
assert set(body) == {"error"}
assert set(body["error"]) == {"code", "message", "request_id"}
assert body["error"]["code"] == code
assert body["error"]["message"]
assert body["error"]["request_id"] == reply.headers["X-Request-Id"]
+193
View File
@@ -0,0 +1,193 @@
"""Регистрация, вход по Basic, доступ по Bearer и выход."""
import base64
import uuid
import pytest
from conftest import assert_error, basic_header, register_and_login
BAD_BASIC = [
"Basic",
"Basic !!!not-base64!!!",
"Basic " + base64.b64encode(b"nocolon").decode(),
"Basic " + base64.b64encode("имя:password-123456".encode()).decode(),
"Basic " + base64.b64encode(b"user:\xff\xfe-bad-utf8").decode(),
"Bearer abc",
"",
]
def test_register_returns_user_without_secrets(client):
reply = client.post(
"/api/v1/users",
json={
"username": "reg_" + uuid.uuid4().hex[:8],
"display_name": "Имя",
"password": "long-enough-pass",
},
)
assert reply.status_code == 201
assert set(reply.json()) == {"id", "username", "display_name", "created_at"}
assert "password" not in reply.text and "hash" not in reply.text
@pytest.mark.parametrize(
"password", [None, "", "short", "a" * 11, "a" * 129, 123456789012, "пароль"]
)
def test_register_password_rules(client, password):
body = {"username": "pw_" + uuid.uuid4().hex[:8], "display_name": "x"}
if password is not None:
body["password"] = password
assert_error(client.post("/api/v1/users", json=body), 400, "invalid_request")
def test_register_password_border_lengths(client):
for password in ["a" * 12, "я" * 128, "p:a:s:s:w:o:r:d:1:2:3"]:
body = {
"username": "pb_" + uuid.uuid4().hex[:8],
"display_name": "x",
"password": password,
}
assert client.post("/api/v1/users", json=body).status_code == 201
def test_login_success_shape(client, alice):
reply = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
)
assert reply.status_code == 201
data = reply.json()
assert set(data) == {"token", "token_type", "expires_at", "user"}
assert data["token_type"] == "Bearer" and len(data["token"]) >= 32
assert data["user"] == alice.data
assert data["expires_at"].endswith("Z")
def test_each_login_gives_new_token(client, alice):
second = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
).json()["token"]
assert second != alice.token
def test_wrong_password_and_unknown_user_look_the_same(client, alice):
wrong = client.post(
"/api/v1/auth/sessions",
headers=basic_header(alice.username, "wrong-password-123"),
)
unknown = client.post(
"/api/v1/auth/sessions",
headers=basic_header("no_such_user_x", "wrong-password-123"),
)
assert_error(wrong, 401, "unauthorized")
assert_error(unknown, 401, "unauthorized")
assert wrong.headers["WWW-Authenticate"] == unknown.headers["WWW-Authenticate"]
assert wrong.headers["WWW-Authenticate"].startswith('Basic realm="messenger"')
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
@pytest.mark.parametrize("header", BAD_BASIC)
def test_malformed_basic_is_401(client, header):
reply = client.post("/api/v1/auth/sessions", headers={"Authorization": header})
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"].startswith("Basic")
def test_login_without_header_is_401(client):
assert_error(client.post("/api/v1/auth/sessions"), 401, "unauthorized")
def test_password_with_colon_and_unicode_works(client):
for password in ["pass:with:colons:123", "пароль-с-юникодом-😀-123"]:
username = "uc_" + uuid.uuid4().hex[:8]
client.post(
"/api/v1/users",
json={"username": username, "display_name": "x", "password": password},
)
reply = client.post(
"/api/v1/auth/sessions", headers=basic_header(username, password)
)
assert reply.status_code == 201, password
def test_bearer_token_gives_access(client, alice):
reply = client.get("/api/v1/users/me", headers=alice.headers)
assert reply.status_code == 200 and reply.json() == alice.data
def test_business_endpoint_rejects_basic(client, alice):
reply = client.get(
"/api/v1/users/me", headers=basic_header(alice.username, alice.password)
)
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
@pytest.mark.parametrize(
"header",
["", "Bearer", "Bearer short", "Bearer " + "x" * 43, "Token abc", "bearer"],
)
def test_bad_or_unknown_bearer_is_401(client, header):
headers = {"Authorization": header} if header else {}
reply = client.get("/api/v1/users/me", headers=headers)
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
def test_x_user_id_alone_gives_no_access(client, alice):
assert_error(
client.get("/api/v1/users/me", headers={"X-User-Id": alice.id}),
401,
"unauthorized",
)
def test_x_user_id_does_not_change_owner_of_session(client, alice, bob):
reply = client.get(
"/api/v1/users/me", headers={**alice.headers, "X-User-Id": bob.id}
)
assert reply.json()["id"] == alice.id
def test_logout_revokes_token_and_repeat_is_401(client, alice):
first = client.delete("/api/v1/auth/sessions/current", headers=alice.headers)
assert first.status_code == 204 and first.content == b""
assert_error(
client.get("/api/v1/users/me", headers=alice.headers), 401, "unauthorized"
)
assert_error(
client.delete("/api/v1/auth/sessions/current", headers=alice.headers),
401,
"unauthorized",
)
def test_logout_without_token_is_401(client):
assert_error(client.delete("/api/v1/auth/sessions/current"), 401, "unauthorized")
def test_logout_revokes_only_current_session(client, alice):
second = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
).json()["token"]
client.delete("/api/v1/auth/sessions/current", headers=alice.headers)
assert (
client.get(
"/api/v1/users/me", headers={"Authorization": "Bearer " + second}
).status_code
== 200
)
def test_session_lives_longer_than_300_seconds(client, alice):
"""Сессия по умолчанию живёт не меньше 300 секунд."""
from datetime import datetime, timezone
data = client.post(
"/api/v1/auth/sessions", headers=basic_header(alice.username, alice.password)
).json()
left = datetime.fromisoformat(data["expires_at"][:-1] + "+00:00") - datetime.now(
timezone.utc
)
assert left.total_seconds() > 300
+258
View File
@@ -0,0 +1,258 @@
"""Кэш сессий в Redis: попадания, TTL, отзыв и недоступность Redis."""
import hashlib
import json
import time
import uuid
from dataclasses import replace
import pytest
import redis
from fastapi.testclient import TestClient
from redis.asyncio import Redis as AsyncRedis
from app.main import create_app
from conftest import CACHE_URL, assert_error, make_settings, register_and_login, run_sql
pytestmark = pytest.mark.skipif(
not CACHE_URL, reason="TEST_CACHE_URL не задан (запускайте тесты в контейнере)"
)
DEAD_REDIS = "redis://127.0.0.1:1/0"
def key_for(person) -> str:
"""Ключ Redis для токена пользователя."""
return "session:" + hashlib.sha256(person.token.encode()).hexdigest()
@pytest.fixture
def store():
"""Синхронный клиент тестовой базы Redis."""
client = redis.Redis.from_url(CACHE_URL, decode_responses=True)
client.flushdb()
yield client
client.close()
@pytest.fixture
def cached(store):
"""Клиент приложения с включённым кэшем."""
with TestClient(create_app(make_settings()), raise_server_exceptions=False) as app_client:
yield app_client
def test_user_profile_is_served_from_cache_with_bounded_ttl(cached, store):
person = register_and_login(cached, "cache")
stats = cached.app.state.cache.stats
assert cached.get("/api/v1/users/me", headers=person.headers).status_code == 200
assert stats["misses"] == 1 and stats["hits"] == 0
ttl_ms = store.pttl(key_for(person))
assert 0 < ttl_ms <= 60_000
value = json.loads(store.get(key_for(person)))
assert set(value) == {"id", "username", "display_name", "created_at"}
assert (value["id"], value["username"]) == (person.id, person.username)
for _ in range(5):
reply = cached.get("/api/v1/users/me", headers=person.headers)
assert reply.status_code == 200 and reply.json() == person.data
assert stats["hits"] == 5
def test_cache_never_stores_raw_tokens_or_passwords(cached, store):
person = register_and_login(cached, "secret")
cached.get("/api/v1/users/me", headers=person.headers)
dump = " ".join(k + "=" + (store.get(k) or "") for k in store.scan_iter())
assert person.token not in dump
assert person.password not in dump
assert "scrypt" not in dump
def test_logout_revokes_cached_session(cached, store):
person = register_and_login(cached, "logout")
assert cached.get("/api/v1/users/me", headers=person.headers).status_code == 200
assert store.get(key_for(person)) is not None
assert cached.delete("/api/v1/auth/sessions/current", headers=person.headers).status_code == 204
assert store.get(key_for(person)) == "revoked"
assert_error(cached.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
assert_error(
cached.delete("/api/v1/auth/sessions/current", headers=person.headers), 401, "unauthorized"
)
def test_late_cache_fill_cannot_resurrect_revoked_session(cached, store):
"""Запоздалая запись в кэш не отменяет отзыв сессии."""
person = register_and_login(cached, "race")
cached.delete("/api/v1/auth/sessions/current", headers=person.headers)
token_hash = hashlib.sha256(person.token.encode()).hexdigest()
stale = {k: person.data[k] for k in ("id", "username", "display_name", "created_at")}
cached.portal.call(cached.app.state.cache.put, token_hash, stale, 3600.0)
assert store.get(key_for(person)) == "revoked"
assert_error(cached.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
def test_flushed_cache_loses_nothing(cached, store):
"""После очистки Redis сессия читается из PostgreSQL."""
person = register_and_login(cached, "flush")
cached.get("/api/v1/users/me", headers=person.headers)
store.flushdb()
assert cached.get("/api/v1/users/me", headers=person.headers).status_code == 200
assert store.exists(key_for(person))
def test_cache_does_not_extend_short_session():
"""TTL записи в кэше не больше остатка сессии."""
settings = make_settings(session_ttl_seconds=1)
with TestClient(create_app(settings), raise_server_exceptions=False) as short:
person = register_and_login(short, "short")
assert short.get("/api/v1/users/me", headers=person.headers).status_code == 200
time.sleep(2.2)
reply = short.get("/api/v1/users/me", headers=person.headers)
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
def test_staleness_after_out_of_band_delete_is_bounded_by_cache_ttl(store):
"""Удаление сессии мимо API видно не позже CACHE_TTL_SECONDS."""
settings = make_settings(cache_ttl_seconds=1)
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
person = register_and_login(app_client, "bounded")
assert app_client.get("/api/v1/users/me", headers=person.headers).status_code == 200
run_sql("DELETE FROM sessions WHERE token_hash = $1",
hashlib.sha256(person.token.encode()).hexdigest())
time.sleep(1.3)
assert_error(app_client.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
def test_redis_down_requests_bypass_cache_and_stay_fast():
settings = make_settings(cache_url=DEAD_REDIS)
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
assert app_client.get("/health/ready").status_code == 200
alice = register_and_login(app_client, "nocache_a")
bob = register_and_login(app_client, "nocache_b")
started = time.monotonic()
assert app_client.get("/api/v1/users/me", headers=alice.headers).json() == alice.data
chat = app_client.post(
"/api/v1/chats", json={"title": "без кэша", "member_ids": [alice.id, bob.id]},
headers=alice.headers,
)
assert chat.status_code == 201
path = "/api/v1/chats/%s/messages" % chat.json()["id"]
assert app_client.post(path, json={"text": "привет"}, headers=alice.headers).status_code == 201
assert len(app_client.get(path, headers=bob.headers).json()["items"]) == 1
assert time.monotonic() - started < 3
assert app_client.app.state.cache.stats["errors"] >= 1
assert app_client.delete("/api/v1/auth/sessions/current", headers=alice.headers).status_code == 204
assert_error(app_client.get("/api/v1/users/me", headers=alice.headers), 401, "unauthorized")
def test_redis_down_never_trusts_anonymous_or_unknown_tokens():
settings = make_settings(cache_url=DEAD_REDIS)
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
person = register_and_login(app_client, "anon")
for headers in (
{},
{"X-User-Id": person.id},
{"Authorization": "Bearer " + "B" * 43},
{"Authorization": "Basic " + "eDp5"},
):
reply = app_client.get("/api/v1/users/me", headers=headers)
assert_error(reply, 401, "unauthorized")
def test_revocation_lost_while_redis_down_is_flushed_on_recovery(cached, store):
"""Отзыв, потерянный при сбое Redis, приводит к очистке кэша."""
cache = cached.app.state.cache
person = register_and_login(cached, "lost")
assert cached.get("/api/v1/users/me", headers=person.headers).status_code == 200
assert store.exists(key_for(person))
working = cache.client
cache.client = AsyncRedis.from_url(DEAD_REDIS, socket_connect_timeout=0.2, socket_timeout=0.2)
cache.retry_seconds = 0
assert cached.delete("/api/v1/auth/sessions/current", headers=person.headers).status_code == 204
assert cache.dirty is True
assert store.exists(key_for(person)), "старая запись осталась в Redis -- ровно опасный случай"
cache.client = working
assert_error(cached.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
assert cache.dirty is False
assert not store.exists(key_for(person))
def test_without_cache_url_cache_is_off():
settings = replace(make_settings(), cache_url="")
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
assert app_client.app.state.cache.enabled is False
person = register_and_login(app_client, "off")
assert app_client.get("/api/v1/users/me", headers=person.headers).status_code == 200
@pytest.mark.parametrize("redis_down_at_startup", [False, True])
def test_lost_revocation_survives_api_restart(store, redis_down_at_startup):
"""Старый ключ Redis не даёт читать и писать после потери флага dirty."""
settings = make_settings(cache_retry_seconds=0)
with TestClient(create_app(settings), raise_server_exceptions=False) as first:
person = register_and_login(first, "restart")
chat_reply = first.post(
"/api/v1/chats", json={"title": "Отзыв", "member_ids": [person.id]},
headers=person.headers,
)
assert chat_reply.status_code == 201
chat_id = chat_reply.json()["id"]
cache = first.app.state.cache
stale = store.get(key_for(person))
assert stale is not None and stale != "revoked"
working = cache.client
failed = AsyncRedis.from_url(DEAD_REDIS, socket_connect_timeout=0.2, socket_timeout=0.2)
cache.client = failed
try:
assert first.delete(
"/api/v1/auth/sessions/current", headers=person.headers
).status_code == 204
assert cache.dirty is True
assert store.get(key_for(person)) == stale
assert not run_sql(
"SELECT 1 FROM sessions WHERE token_hash = $1",
hashlib.sha256(person.token.encode()).hexdigest(),
)
finally:
first.portal.call(failed.aclose)
cache.client = working
restarted_settings = replace(settings, cache_url=DEAD_REDIS) if redis_down_at_startup else settings
with TestClient(create_app(restarted_settings), raise_server_exceptions=False) as restarted:
cache = restarted.app.state.cache
assert cache.dirty is False
if redis_down_at_startup:
assert_error(restarted.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
restarted.portal.call(cache.client.aclose)
cache.client = AsyncRedis.from_url(CACHE_URL, decode_responses=True)
assert store.get(key_for(person)) == stale
assert store.pttl(key_for(person)) > 0
assert_error(restarted.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
assert_error(
restarted.post(
f"/api/v1/chats/{chat_id}/messages", json={"text": "Не записывать"},
headers=person.headers,
),
401, "unauthorized",
)
assert_error(
restarted.delete("/api/v1/auth/sessions/current", headers=person.headers),
401, "unauthorized",
)
assert not run_sql("SELECT 1 FROM messages WHERE chat_id = $1", uuid.UUID(chat_id))
assert store.get(key_for(person)) == stale
def test_cached_session_deleted_in_database_is_rejected_immediately(cached, store):
person = register_and_login(cached, "deleted")
assert cached.get("/api/v1/users/me", headers=person.headers).status_code == 200
run_sql("DELETE FROM sessions WHERE token_hash = $1",
hashlib.sha256(person.token.encode()).hexdigest())
assert store.pttl(key_for(person)) > 0
assert_error(cached.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
+61
View File
@@ -0,0 +1,61 @@
"""Параллельная запись: сообщения не теряются и не дублируются."""
import threading
from concurrent.futures import ThreadPoolExecutor
CLIENTS = 10
PER_CLIENT = 10
def test_100_messages_from_10_clients_in_parallel(client, make_user, make_chat):
people = [make_user("c%d" % n) for n in range(CLIENTS)]
chat = make_chat(people[0], *people[1:])
url = "/api/v1/chats/" + chat["id"] + "/messages"
start_together = threading.Barrier(CLIENTS)
def worker(index):
start_together.wait()
return [
client.post(
url,
json={"text": "c%d-m%d" % (index, n)},
headers=people[index].headers,
).status_code
for n in range(PER_CLIENT)
]
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
results = list(pool.map(worker, range(CLIENTS)))
assert all(code == 201 for codes in results for code in codes)
page = client.get(url + "?limit=100", headers=people[0].headers).json()
items = page["items"]
assert len(items) == 100 and page["next_cursor"] is None
assert len({m["id"] for m in items}) == 100
assert {m["text"] for m in items} == {
"c%d-m%d" % (c, n) for c in range(CLIENTS) for n in range(PER_CLIENT)
}
stamps = [m["created_at"] for m in items]
assert stamps == sorted(stamps)
for index in range(CLIENTS):
own = [m["text"] for m in items if m["sender_id"] == people[index].id]
assert own == ["c%d-m%d" % (index, n) for n in range(PER_CLIENT)]
def test_parallel_chat_creation_and_reading(client, make_user):
owner, friend = make_user("owner"), make_user("friend")
def create(number):
made = client.post(
"/api/v1/chats",
json={"title": "n%d" % number, "member_ids": [owner.id, friend.id]},
headers=owner.headers,
)
listing = client.get("/api/v1/chats?limit=100", headers=friend.headers)
return made.status_code, listing.status_code
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(create, range(30)))
assert all(r == (201, 200) for r in results)
final = client.get("/api/v1/chats?limit=100", headers=friend.headers).json()
assert len(final["items"]) == 30 and len({c["id"] for c in final["items"]}) == 30
+95
View File
@@ -0,0 +1,95 @@
"""Общие свойства API: заголовки, формат ошибок, health и логи."""
import re
from conftest import assert_error
def test_health_endpoints(client):
assert client.get("/health/live").json() == {"status": "ok"}
assert client.get("/health/ready").json() == {"status": "ok"}
def test_every_response_has_unique_request_id(client, alice):
seen = set()
for reply in [
client.get("/health/live"),
client.get("/health/ready"),
client.get("/api/v1/users/me", headers=alice.headers),
client.get("/api/v1/users/me"),
client.get("/no/such/page"),
client.delete("/api/v1/chats"),
]:
assert reply.headers.get("X-Request-Id")
seen.add(reply.headers["X-Request-Id"])
assert len(seen) == 6
def test_unknown_path_is_404_in_common_format(client):
assert_error(client.get("/api/v1/nothing"), 404, "not_found")
def test_trailing_slash_is_not_redirected(client, alice):
assert_error(
client.get("/api/v1/chats/", headers=alice.headers, follow_redirects=False),
404,
"not_found",
)
def test_wrong_method_is_405_in_common_format(client):
assert_error(client.delete("/api/v1/users"), 405, "invalid_request")
def test_two_users_one_chat_two_messages(client, alice, bob, eve, chat):
"""Двое переписываются, посторонний получает 404."""
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert (
client.post(
url, json={"text": "Привет, Боб!"}, headers=alice.headers
).status_code
== 201
)
assert (
client.post(
url, json={"text": "Привет, Алиса!"}, headers=bob.headers
).status_code
== 201
)
history = client.get(url, headers=alice.headers).json()["items"]
assert [m["text"] for m in history] == ["Привет, Боб!", "Привет, Алиса!"]
assert [m["sender_id"] for m in history] == [alice.id, bob.id]
assert client.get(url, headers=eve.headers).status_code == 404
def test_chat_response_shape(client, alice, bob, chat):
assert set(chat) == {"id", "title", "member_ids", "created_at"}
assert set(chat["member_ids"]) == {alice.id, bob.id}
assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}Z", chat["created_at"])
assert client.get("/api/v1/chats/" + chat["id"], headers=bob.headers).json() == chat
def test_unexpected_exception_gives_500_without_details(client, log_lines):
async def boom():
raise RuntimeError("ТАЙНЫЙ-ТЕКСТ-ИЗ-ОШИБКИ")
client.app.add_api_route("/boom", boom)
reply = client.get("/boom")
assert_error(reply, 500, "internal_error")
assert "ТАЙНЫЙ" not in reply.text
assert not any("ТАЙНЫЙ" in line for line in log_lines)
assert any("unhandled_error" in line for line in log_lines)
def test_logs_have_requests_but_no_secrets(client, alice, chat, log_lines):
"""В логе есть запросы, но нет текста сообщений, паролей и токенов."""
secret = "ОЧЕНЬ-СЕКРЕТНОЕ-СООБЩЕНИЕ-12345"
url = "/api/v1/chats/" + chat["id"] + "/messages"
client.post(url, json={"text": secret}, headers=alice.headers)
client.get(url, headers=alice.headers)
joined = "\n".join(log_lines)
assert (
"method=POST" in joined and "status=201" in joined and "request_id=" in joined
)
for hidden in (secret, alice.token, alice.password):
assert hidden not in joined
+173
View File
@@ -0,0 +1,173 @@
"""Содержимое PostgreSQL: хеши, ограничения, миграции и атомарность."""
import asyncio
import uuid
import asyncpg
import pytest
from app.db import create_engine
from app.migrate import run_migrations
from conftest import make_settings, run_sql
def test_password_is_stored_as_scrypt_hash_not_plaintext(client, make_user):
one, two = make_user("hash1"), make_user("hash2")
rows = run_sql(
"SELECT username, password_hash FROM users WHERE username = ANY($1)",
[one.username, two.username],
)
hashes = {row["username"]: row["password_hash"] for row in rows}
assert hashes[one.username].startswith("scrypt$")
assert one.password not in hashes[one.username]
assert hashes[one.username] != hashes[two.username]
def test_same_password_gives_different_hashes(client):
password = "same-password-for-both"
for _ in range(2):
client.post(
"/api/v1/users",
json={
"username": "sp_" + uuid.uuid4().hex[:10],
"display_name": "x",
"password": password,
},
)
rows = run_sql("SELECT password_hash FROM users ORDER BY created_at DESC LIMIT 2")
assert rows[0]["password_hash"] != rows[1]["password_hash"]
def test_session_table_keeps_token_hash_not_token(client, alice):
rows = run_sql(
"SELECT token_hash FROM sessions WHERE user_id = $1", uuid.UUID(alice.id)
)
assert len(rows) == 1
assert len(rows[0]["token_hash"]) == 64 and rows[0]["token_hash"] != alice.token
assert alice.token not in rows[0]["token_hash"]
def test_message_is_really_in_the_database(client, alice, chat):
client.post(
"/api/v1/chats/" + chat["id"] + "/messages",
json={"text": "в базе"},
headers=alice.headers,
)
rows = run_sql(
"SELECT text, sender_id FROM messages WHERE chat_id = $1", uuid.UUID(chat["id"])
)
assert [(r["text"], str(r["sender_id"])) for r in rows] == [("в базе", alice.id)]
def test_migrations_can_run_again_without_duplicating_anything(client, alice):
users_before = run_sql("SELECT count(*) AS n FROM users")[0]["n"]
versions_before = [
r["version"]
for r in run_sql("SELECT version FROM schema_migrations ORDER BY version")
]
async def twice():
engine = create_engine(make_settings())
try:
return [await run_migrations(engine), await run_migrations(engine)]
finally:
await engine.dispose()
first, second = asyncio.run(twice())
assert first == [] and second == []
assert run_sql("SELECT count(*) AS n FROM users")[0]["n"] == users_before
assert [
r["version"]
for r in run_sql("SELECT version FROM schema_migrations ORDER BY version")
] == versions_before
assert versions_before == ["0001_init.sql", "0002_message_requests.sql"]
def test_expected_tables_and_indexes_exist(client):
tables = {
r["tablename"]
for r in run_sql("SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
}
assert {
"users",
"chats",
"chat_members",
"messages",
"sessions",
"schema_migrations",
"message_requests",
} <= tables
indexes = {
r["indexname"]
for r in run_sql("SELECT indexname FROM pg_indexes WHERE schemaname = 'public'")
}
assert "messages_chat_created_idx" in indexes
def count_constraints(table: str, kind: str) -> int:
"""Число ограничений заданного типа у таблицы."""
rows = run_sql(
"SELECT count(*) AS n FROM pg_constraint WHERE conrelid = $1::regclass AND contype::text = $2",
table,
kind,
)
return rows[0]["n"]
def test_primary_and_foreign_keys_are_declared(client):
for table in ("users", "chats", "chat_members", "messages", "sessions"):
assert count_constraints(table, "p") == 1, table
assert count_constraints("users", "u") == 1
assert count_constraints("chat_members", "f") == 2
assert count_constraints("messages", "f") == 2
assert count_constraints("sessions", "f") == 1
def test_database_itself_rejects_bad_rows(client, alice, chat):
chat_id, user_id = uuid.UUID(chat["id"]), uuid.UUID(alice.id)
with pytest.raises(asyncpg.ForeignKeyViolationError):
run_sql(
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, 'x')",
uuid.uuid4(),
uuid.uuid4(),
user_id,
)
with pytest.raises(asyncpg.CheckViolationError):
run_sql(
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, '')",
uuid.uuid4(),
chat_id,
user_id,
)
with pytest.raises(asyncpg.UniqueViolationError):
run_sql(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
chat_id,
user_id,
)
with pytest.raises(asyncpg.CheckViolationError):
run_sql(
"INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, 'BadName', 'x', 'h')",
uuid.uuid4(),
)
def test_chat_creation_is_atomic(client, alice):
"""Неизвестный участник: ни чата, ни участников в БД."""
title = "atomic-" + uuid.uuid4().hex
reply = client.post(
"/api/v1/chats",
json={"title": title, "member_ids": [alice.id, str(uuid.uuid4())]},
headers=alice.headers,
)
assert reply.status_code == 400
assert (
run_sql("SELECT count(*) AS n FROM chats WHERE title = $1", title)[0]["n"] == 0
)
def test_successful_chat_has_all_members_in_database(client, alice, bob, chat):
rows = run_sql(
"SELECT user_id FROM chat_members WHERE chat_id = $1", uuid.UUID(chat["id"])
)
assert {str(r["user_id"]) for r in rows} == {alice.id, bob.id}
+78
View File
@@ -0,0 +1,78 @@
"""Недоступная БД: ответ 503 и отказ анонимным запросам."""
from dataclasses import replace
import pytest
from fastapi.testclient import TestClient
from app.db import create_engine, create_sessionmaker
from app.main import create_app
from conftest import CACHE_URL, assert_error, make_settings, register_and_login
def test_database_down_gives_503_and_never_trusts_anyone():
settings = make_settings(cache_url="")
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
person = register_and_login(app_client, "down")
assert (
app_client.get("/api/v1/users/me", headers=person.headers).status_code
== 200
)
dead = replace(
settings,
database_url="postgresql+asyncpg://x:y@127.0.0.1:1/none",
db_pool_timeout=1,
)
app_client.app.state.sessionmaker = create_sessionmaker(create_engine(dead))
assert app_client.get("/health/live").status_code == 200
assert_error(app_client.get("/health/ready"), 503, "unavailable")
assert_error(
app_client.get("/api/v1/users/me", headers=person.headers),
503,
"unavailable",
)
assert_error(
app_client.post(
"/api/v1/users",
json={
"username": "abcdef",
"display_name": "x",
"password": "long-enough-password",
},
),
503,
"unavailable",
)
reply = app_client.get("/api/v1/chats")
assert reply.status_code in (401, 503) and reply.status_code != 200
def test_database_down_with_cache_up_still_needs_database_for_data():
"""При живом Redis операции с данными без БД всё равно дают 503."""
if not CACHE_URL:
pytest.skip("TEST_CACHE_URL не задан (тест для контейнера с Redis)")
settings = make_settings()
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
person = register_and_login(app_client, "down_cache")
assert app_client.get("/api/v1/users/me", headers=person.headers).status_code == 200
dead = replace(
settings,
database_url="postgresql+asyncpg://x:y@127.0.0.1:1/none",
db_pool_timeout=1,
)
app_client.app.state.sessionmaker = create_sessionmaker(create_engine(dead))
assert_error(app_client.get("/health/ready"), 503, "unavailable")
assert_error(app_client.get("/api/v1/users/me", headers=person.headers), 503, "unavailable")
assert_error(app_client.get("/api/v1/chats", headers=person.headers), 503, "unavailable")
assert_error(
app_client.post("/api/v1/chats", json={"title": "x", "member_ids": [person.id]},
headers=person.headers),
503, "unavailable",
)
assert_error(app_client.get("/api/v1/chats"), 401, "unauthorized")
unknown = {"Authorization": "Bearer " + "A" * 43}
assert app_client.get("/api/v1/users/me", headers=unknown).status_code == 503
+45
View File
@@ -0,0 +1,45 @@
"""Повторный username: 409, в том числе при одновременной регистрации."""
import uuid
from concurrent.futures import ThreadPoolExecutor
from conftest import assert_error, run_sql
def body(username: str, display_name: str = "Имя") -> dict:
"""Тело регистрации."""
return {"username": username, "display_name": display_name, "password": "long-enough-password"}
def test_second_registration_with_same_username_is_409(client):
name = "dup_" + uuid.uuid4().hex[:10]
assert client.post("/api/v1/users", json=body(name)).status_code == 201
assert_error(client.post("/api/v1/users", json=body(name, "Другое имя")), 409, "conflict")
def test_duplicate_does_not_replace_original_user(client):
name = "dup_" + uuid.uuid4().hex[:10]
first = client.post("/api/v1/users", json=body(name, "Первый")).json()
client.post("/api/v1/users", json=body(name, "Второй"))
rows = run_sql("SELECT display_name FROM users WHERE username = $1", name)
assert [row["display_name"] for row in rows] == ["Первый"]
assert first["display_name"] == "Первый"
def test_username_is_case_sensitive_lowercase_only(client):
name = "dup_" + uuid.uuid4().hex[:10]
assert client.post("/api/v1/users", json=body(name)).status_code == 201
assert_error(client.post("/api/v1/users", json=body(name.upper())), 400, "invalid_request")
def test_parallel_registration_of_same_username_creates_exactly_one(client):
name = "race_" + uuid.uuid4().hex[:10]
def register(_):
return client.post("/api/v1/users", json=body(name)).status_code
with ThreadPoolExecutor(max_workers=10) as pool:
codes = list(pool.map(register, range(10)))
assert codes.count(201) == 1
assert codes.count(409) == 9
assert len(run_sql("SELECT 1 FROM users WHERE username = $1", name)) == 1
+73
View File
@@ -0,0 +1,73 @@
"""Текст сообщения: пустые строки, длина и Unicode."""
import pytest
from conftest import assert_error
@pytest.mark.parametrize("text", ["", " ", " ", "\n", "\t \n", " ", " "])
def test_blank_text_is_rejected(client, alice, chat, text):
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert_error(
client.post(url, json={"text": text}, headers=alice.headers),
400,
"invalid_request",
)
assert client.get(url, headers=alice.headers).json()["items"] == []
@pytest.mark.parametrize(
"body", [{}, {"text": None}, {"text": 123}, {"text": ["a"]}, {"message": "hi"}]
)
def test_missing_or_wrong_type_text_is_rejected(client, alice, chat, body):
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert_error(
client.post(url, json=body, headers=alice.headers), 400, "invalid_request"
)
def test_text_length_is_counted_in_characters(client, alice, chat):
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert (
client.post(url, json={"text": "я" * 4000}, headers=alice.headers).status_code
== 201
)
assert (
client.post(url, json={"text": "😀" * 4000}, headers=alice.headers).status_code
== 201
)
assert_error(
client.post(url, json={"text": "я" * 4001}, headers=alice.headers),
400,
"invalid_request",
)
def test_nul_character_is_400_not_500(client, alice, chat):
"""Символ NUL отклоняется с 400."""
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert_error(
client.post(url, json={"text": "a\x00b"}, headers=alice.headers),
400,
"invalid_request",
)
def test_unicode_survives_the_database(client, alice, bob, chat):
url = "/api/v1/chats/" + chat["id"] + "/messages"
text = " Привет, мир 👋 你好 ✓ é "
sent = client.post(url, json={"text": text}, headers=alice.headers)
assert sent.status_code == 201 and sent.json()["text"] == text
assert client.get(url, headers=bob.headers).json()["items"][0]["text"] == text
assert sent.headers["content-type"].split(";")[0] == "application/json"
def test_message_has_correct_fields(client, alice, chat):
data = client.post(
"/api/v1/chats/" + chat["id"] + "/messages",
json={"text": "hi"},
headers=alice.headers,
).json()
assert set(data) == {"id", "chat_id", "sender_id", "text", "created_at"}
assert data["chat_id"] == chat["id"] and data["sender_id"] == alice.id
assert data["created_at"].endswith("Z")
+52
View File
@@ -0,0 +1,52 @@
"""План запроса истории на 10 000 сообщениях: индекс без полного сканирования."""
import asyncio
import asyncpg
import pytest
from app import explain
from app.crud import history_query
from conftest import database_parts, make_settings, TEST_DB_NAME
from app.db import create_engine
def plan_for(cursor_offset):
"""Заполнить данные и вернуть число сообщений и план запроса страницы."""
p = database_parts()
async def go():
conn = await asyncpg.connect(database=TEST_DB_NAME, timeout=5, **p)
try:
await explain.seed(conn, 30000)
count = await conn.fetchval(
"SELECT count(*) FROM messages WHERE chat_id = $1", explain.BIG_CHAT
)
after = None
if cursor_offset:
row = await conn.fetchrow(
"SELECT created_at, id FROM messages WHERE chat_id = $1"
" ORDER BY created_at, id OFFSET $2 LIMIT 1",
explain.BIG_CHAT, cursor_offset,
)
after = (row["created_at"], row["id"])
engine = create_engine(make_settings())
query = history_query(explain.BIG_CHAT, after, 50).compile(dialect=engine.dialect)
await engine.dispose()
params = [query.params[name] for name in query.positiontup]
rows = await conn.fetch("EXPLAIN (ANALYZE, BUFFERS) " + query.string, *params)
return count, "\n".join(r[0] for r in rows)
finally:
await conn.close()
return asyncio.run(go())
@pytest.mark.parametrize("cursor_offset", [0, 9000])
def test_history_page_uses_index_without_full_scan(cursor_offset):
count, plan = plan_for(cursor_offset)
assert count >= 10000
assert "Index Scan using messages_chat_created_idx" in plan, plan
assert "Seq Scan" not in plan, plan
assert "Sort" not in plan, plan
assert "rows=51 loops=1" in plan, plan
+65
View File
@@ -0,0 +1,65 @@
"""Доступ к чужому чату: 404 для посторонних, 401 без токена."""
import uuid
from conftest import assert_error
def test_outsider_cannot_read_chat(client, eve, chat):
assert_error(client.get("/api/v1/chats/" + chat["id"], headers=eve.headers), 404, "not_found")
def test_outsider_cannot_read_history(client, alice, eve, chat):
client.post("/api/v1/chats/" + chat["id"] + "/messages", json={"text": "секрет"}, headers=alice.headers)
reply = client.get("/api/v1/chats/" + chat["id"] + "/messages", headers=eve.headers)
assert_error(reply, 404, "not_found")
assert "секрет" not in reply.text
def test_outsider_cannot_write(client, alice, eve, chat):
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert_error(client.post(url, json={"text": "чужое"}, headers=eve.headers), 404, "not_found")
assert client.get(url, headers=alice.headers).json()["items"] == []
def test_outsider_gets_404_even_with_bad_body(client, eve, chat):
"""Проверка доступа выполняется раньше проверки тела."""
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert_error(client.post(url, json={"text": ""}, headers=eve.headers), 404, "not_found")
def test_unknown_chat_looks_the_same_as_foreign(client, eve, chat):
foreign = client.get("/api/v1/chats/" + chat["id"], headers=eve.headers)
missing = client.get("/api/v1/chats/" + str(uuid.uuid4()), headers=eve.headers)
assert foreign.status_code == missing.status_code == 404
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
def test_chat_list_shows_only_own_chats(client, bob, eve, chat):
mine = client.get("/api/v1/chats", headers=bob.headers).json()["items"]
others = client.get("/api/v1/chats", headers=eve.headers).json()["items"]
assert [c["id"] for c in mine] == [chat["id"]]
assert others == []
def test_bad_chat_id_is_400(client, alice):
assert_error(client.get("/api/v1/chats/not-a-uuid", headers=alice.headers), 400, "invalid_request")
def test_no_token_is_401_everywhere(client, chat):
chat_url = "/api/v1/chats/" + chat["id"]
for url in ["/api/v1/users/me", "/api/v1/chats", chat_url, chat_url + "/messages"]:
assert_error(client.get(url), 401, "unauthorized")
assert_error(client.post("/api/v1/chats", json={"title": "x", "member_ids": []}), 401, "unauthorized")
assert_error(client.post(chat_url + "/messages", json={"text": "x"}), 401, "unauthorized")
def test_401_comes_before_404(client, chat):
"""Без токена существование чата не раскрывается."""
assert_error(client.get("/api/v1/chats/" + chat["id"] + "/messages"), 401, "unauthorized")
def test_member_can_read_and_write(client, alice, bob, chat):
url = "/api/v1/chats/" + chat["id"] + "/messages"
assert client.post(url, json={"text": "от Боба"}, headers=bob.headers).status_code == 201
assert client.get(url, headers=alice.headers).json()["items"][0]["text"] == "от Боба"
+122
View File
@@ -0,0 +1,122 @@
"""Общая идемпотентность PostgreSQL: конкурентные реплики, rollback, expiry."""
from concurrent.futures import ThreadPoolExecutor
import threading
import uuid
from fastapi.testclient import TestClient
import pytest
from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncSession
from app.main import create_app
from app.models import MessageRequest
from conftest import assert_error, make_settings, run_sql
def message_path(chat):
return "/api/v1/chats/" + chat["id"] + "/messages"
def headers(person, key):
return {"Authorization": "Bearer " + person.token, "Idempotency-Key": key}
@pytest.mark.parametrize("key", [None, "", "a b", "a?b", "x" * 129, "a,b", "a/b"])
def test_key_is_required_and_validated(client, alice, chat, key):
h = {"Authorization": "Bearer " + alice.token}
if key is not None:
h["Idempotency-Key"] = key
assert_error(client.post(message_path(chat), json={"text": "hello"}, headers=h), 400, "invalid_request")
assert not run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
def test_duplicate_headers_are_invalid(client, alice, chat):
h = [("Authorization", "Bearer " + alice.token), ("Idempotency-Key", "a"), ("Idempotency-Key", "b")]
assert_error(client.post(message_path(chat), json={"text": "hi"}, headers=h), 400, "invalid_request")
def test_replay_and_conflict_preserve_original_result(client, alice, chat):
h = headers(alice, uuid.uuid4().hex)
first = client.post(message_path(chat), json={"text": "original"}, headers=h)
replay = client.post(message_path(chat), json={"attachment_ids": [], "text": "original"}, headers=h)
assert first.status_code == replay.status_code == 201
assert first.json() == replay.json()
assert_error(client.post(message_path(chat), json={"text": "changed"}, headers=h), 409, "conflict")
again = client.post(message_path(chat), json={"text": "original"}, headers=h)
assert again.status_code == 201 and again.json() == first.json()
rows = run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
assert [str(row["id"]) for row in rows] == [first.json()["id"]]
def test_parallel_same_key_across_two_applications(client, alice, chat):
h = headers(alice, uuid.uuid4().hex)
barrier = threading.Barrier(8)
with TestClient(create_app(make_settings()), raise_server_exceptions=False) as other:
def send(n):
barrier.wait()
return (client if n % 2 else other).post(message_path(chat), json={"text": "one"}, headers=h)
with ThreadPoolExecutor(max_workers=8) as pool:
replies = list(pool.map(send, range(8)))
assert all(reply.status_code == 201 for reply in replies)
assert len({reply.json()["id"] for reply in replies}) == 1
assert len({reply.headers["X-Instance-Id"] for reply in replies}) == 2
assert len(run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))) == 1
def test_key_scope_includes_user_and_chat(client, alice, bob, chat, make_chat):
other = make_chat(alice, bob)
key = uuid.uuid4().hex
replies = [client.post(message_path(room), json={"text": "hi"}, headers=headers(person, key))
for person, room in [(alice, chat), (bob, chat), (alice, other)]]
assert all(reply.status_code == 201 for reply in replies)
assert len({reply.json()["id"] for reply in replies}) == 3
def test_expired_result_allows_new_message(client, alice, chat):
key = uuid.uuid4().hex
h = headers(alice, key)
first = client.post(message_path(chat), json={"text": "old"}, headers=h)
run_sql("UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=$1 AND chat_id=$2 AND key=$3",
uuid.UUID(alice.id), uuid.UUID(chat["id"]), key)
second = client.post(message_path(chat), json={"text": "new"}, headers=h)
assert first.status_code == second.status_code == 201
assert first.json()["id"] != second.json()["id"]
def test_failure_between_message_and_result_rolls_back(client, alice, chat, monkeypatch):
key = uuid.uuid4().hex
h = headers(alice, key)
real = AsyncSession.execute
async def fail_result(self, statement, *args, **kwargs):
if getattr(getattr(statement, "table", None), "name", None) == MessageRequest.__tablename__:
raise OperationalError("", {}, Exception("injected result failure"))
return await real(self, statement, *args, **kwargs)
with monkeypatch.context() as patch:
patch.setattr(AsyncSession, "execute", fail_result)
assert_error(client.post(message_path(chat), json={"text": "once"}, headers=h), 503, "unavailable")
assert not run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
assert not run_sql("SELECT message_id FROM message_requests WHERE chat_id=$1", uuid.UUID(chat["id"]))
assert client.post(message_path(chat), json={"text": "once"}, headers=h).status_code == 201
def test_committed_but_lost_response_is_safe_to_retry(client, alice, chat, monkeypatch):
from app import routes
key = uuid.uuid4().hex
h = headers(alice, key)
with monkeypatch.context() as patch:
patch.setattr(routes, "message_out", lambda row: (_ for _ in ()).throw(RuntimeError("lost after commit")))
assert_error(client.post(message_path(chat), json={"text": "one"}, headers=h), 500, "internal_error")
replay = client.post(message_path(chat), json={"text": "one"}, headers=h)
assert replay.status_code == 201
rows = run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
assert [str(row["id"]) for row in rows] == [replay.json()["id"]]
def test_replay_rechecks_session_and_chat_access(client, alice, eve, chat):
key = uuid.uuid4().hex
h = headers(alice, key)
assert client.post(message_path(chat), json={"text": "one"}, headers=h).status_code == 201
assert_error(client.post(message_path(chat), json={"text": "one"}, headers=headers(eve, key)), 404, "not_found")
assert client.delete("/api/v1/auth/sessions/current", headers=alice.headers).status_code == 204
assert_error(client.post(message_path(chat), json={"text": "one"}, headers=h), 401, "unauthorized")
+115
View File
@@ -0,0 +1,115 @@
"""Некорректный JSON и поля: 400, 413 и 415."""
import uuid
import pytest
from conftest import assert_error
JSON = {"Content-Type": "application/json"}
PASSWORD = "long-enough-password"
def valid(**changes) -> dict:
"""Корректное тело регистрации с изменёнными полями."""
body = {"username": "j_" + uuid.uuid4().hex[:10], "display_name": "Имя", "password": PASSWORD}
body.update(changes)
return {key: value for key, value in body.items() if value is not None}
@pytest.mark.parametrize(
"raw",
[
b"{",
b"not json at all",
b"",
b'{"username": "abc",}',
b"\xff\xfe\x00",
b'{"username": NaN}',
b'["username"]',
b'"text"',
b"null",
],
)
def test_registration_rejects_broken_json(client, raw):
assert_error(client.post("/api/v1/users", content=raw, headers=JSON), 400, "invalid_request")
@pytest.mark.parametrize(
"changes",
[
{"username": None},
{"display_name": None},
{"password": None},
{"username": 123},
{"display_name": 5},
{"display_name": None, "extra_field": 1},
{"role": "admin"},
{"username": "ab"},
{"username": "a" * 33},
{"username": "Alice"},
{"username": "al ice"},
{"username": "алиса"},
{"username": "alice\n"},
{"display_name": ""},
{"display_name": " "},
{"display_name": "я" * 101},
{"display_name": "a\x00b"},
],
)
def test_registration_rejects_bad_fields(client, changes):
assert_error(client.post("/api/v1/users", json=valid(**changes)), 400, "invalid_request")
def test_border_values_are_accepted(client):
assert client.post("/api/v1/users", json=valid(display_name="я" * 100)).status_code == 201
assert client.post("/api/v1/users", json=valid(username=uuid.uuid4().hex, display_name="😀")).status_code == 201
def test_lone_surrogate_is_400_not_500(client):
raw = b'{"username": "abcdef", "display_name": "\\ud800", "password": "long-enough-password"}'
assert_error(client.post("/api/v1/users", content=raw, headers=JSON), 400, "invalid_request")
def test_wrong_or_missing_content_type_is_415(client):
body = b'{"username":"abc","display_name":"x","password":"long-enough-password"}'
assert_error(client.post("/api/v1/users", content=body, headers={"Content-Type": "text/plain"}), 415, "unsupported_media_type")
assert_error(client.post("/api/v1/users", content=body), 415, "unsupported_media_type")
def test_huge_body_is_413(client):
big = b'{"username": "abc", "display_name": "' + b"x" * (300 * 1024) + b'"}'
assert_error(client.post("/api/v1/users", content=big, headers=JSON), 413, "payload_too_large")
def test_broken_json_in_message_and_chat(client, alice, chat):
headers = {**JSON, **alice.headers}
assert_error(client.post("/api/v1/chats/" + chat["id"] + "/messages", content=b"{oops", headers=headers), 400, "invalid_request")
assert_error(client.post("/api/v1/chats", content=b"[", headers=headers), 400, "invalid_request")
def test_sender_id_in_message_is_rejected(client, alice, bob, chat):
"""Поле sender_id в теле сообщения запрещено."""
reply = client.post(
"/api/v1/chats/" + chat["id"] + "/messages", json={"text": "привет", "sender_id": bob.id}, headers=alice.headers
)
assert_error(reply, 400, "invalid_request")
def test_chat_body_validation(client, alice, bob):
unknown = str(uuid.uuid4())
cases = [
{"title": "x", "member_ids": []},
{"title": "", "member_ids": [alice.id]},
{"title": " ", "member_ids": [alice.id]},
{"title": "x" * 101, "member_ids": [alice.id]},
{"title": "x", "member_ids": [alice.id, alice.id]},
{"title": "x", "member_ids": [alice.id, unknown]},
{"title": "x", "member_ids": [bob.id]},
{"title": "x", "member_ids": ["не-uuid"]},
{"title": "x", "member_ids": alice.id},
{"title": "x"},
{"title": "x", "member_ids": [alice.id], "extra": 1},
]
for body in cases:
assert_error(client.post("/api/v1/chats", json=body, headers=alice.headers), 400, "invalid_request")
+193
View File
@@ -0,0 +1,193 @@
"""Пагинация истории и списка чатов по keyset-курсору."""
from urllib.parse import quote
import pytest
from app.cursor import encode_cursor
from app.timeutil import MAX_TIMESTAMP_MICROS
from conftest import assert_error
def send_many(client, person, chat, count, prefix="msg"):
"""Отправить несколько сообщений в чат."""
url = "/api/v1/chats/" + chat["id"] + "/messages"
for number in range(count):
reply = client.post(
url, json={"text": "%s-%02d" % (prefix, number)}, headers=person.headers
)
assert reply.status_code == 201
def walk(client, person, chat, limit):
"""Пройти историю страницами; вернуть элементы и число страниц."""
url = "/api/v1/chats/" + chat["id"] + "/messages"
items, pages, cursor = [], 0, None
while True:
query = "?limit=%d" % limit + (
"&cursor=" + quote(cursor, safe="") if cursor else ""
)
data = client.get(url + query, headers=person.headers).json()
assert set(data) == {"items", "next_cursor"} and len(data["items"]) <= limit
items += data["items"]
pages += 1
cursor = data["next_cursor"]
if cursor is None:
return items, pages
assert pages < 1000, "бесконечный обход"
def test_walk_25_messages_by_7(client, alice, bob, chat):
send_many(client, alice, chat, 25)
items, pages = walk(client, bob, chat, 7)
assert pages == 4
assert [m["text"] for m in items] == ["msg-%02d" % n for n in range(25)]
assert len({m["id"] for m in items}) == 25
def test_exact_multiple_has_no_empty_extra_page(client, alice, chat):
send_many(client, alice, chat, 10)
items, pages = walk(client, alice, chat, 5)
assert len(items) == 10 and pages == 2
def test_limit_one_walks_everything(client, alice, chat):
send_many(client, alice, chat, 6)
items, pages = walk(client, alice, chat, 1)
assert len(items) == 6 and pages == 6
def test_default_limit_is_50_and_max_is_100(client, alice, chat):
send_many(client, alice, chat, 120)
url = "/api/v1/chats/" + chat["id"] + "/messages"
default = client.get(url, headers=alice.headers).json()
assert len(default["items"]) == 50 and default["next_cursor"]
biggest = client.get(url + "?limit=100", headers=alice.headers).json()
assert len(biggest["items"]) == 100 and biggest["next_cursor"]
def test_empty_history(client, alice, chat):
data = client.get(
"/api/v1/chats/" + chat["id"] + "/messages", headers=alice.headers
).json()
assert data == {"items": [], "next_cursor": None}
def test_limit_can_change_between_pages(client, alice, chat):
send_many(client, alice, chat, 9)
url = "/api/v1/chats/" + chat["id"] + "/messages"
first = client.get(url + "?limit=2", headers=alice.headers).json()
second = client.get(
url + "?limit=100&cursor=" + quote(first["next_cursor"], safe=""),
headers=alice.headers,
).json()
assert [m["text"] for m in first["items"] + second["items"]] == [
"msg-%02d" % n for n in range(9)
]
assert second["next_cursor"] is None
def test_messages_sent_during_walk_appear_at_the_end(client, alice, chat):
send_many(client, alice, chat, 4)
url = "/api/v1/chats/" + chat["id"] + "/messages"
first = client.get(url + "?limit=2", headers=alice.headers).json()
send_many(client, alice, chat, 1, prefix="late")
rest = client.get(
url + "?limit=10&cursor=" + quote(first["next_cursor"], safe=""),
headers=alice.headers,
).json()
texts = [m["text"] for m in first["items"] + rest["items"]]
assert texts == ["msg-00", "msg-01", "msg-02", "msg-03", "late-00"]
def test_created_at_is_increasing_and_utc(client, alice, chat):
send_many(client, alice, chat, 30)
items, _ = walk(client, alice, chat, 100)
stamps = [m["created_at"] for m in items]
assert stamps == sorted(stamps) and len(set(stamps)) == 30
assert all(s.endswith("Z") and "T" in s for s in stamps)
def test_bad_limit_values(client, alice, chat):
url = "/api/v1/chats/" + chat["id"] + "/messages"
for bad in ["0", "101", "-1", "abc", "1.5", "", "+5", " 5", "٣"]:
assert_error(
client.get(url + "?limit=" + quote(bad), headers=alice.headers),
400,
"invalid_request",
)
assert client.get(url + "?limit=1", headers=alice.headers).status_code == 200
assert client.get(url + "?limit=100", headers=alice.headers).status_code == 200
def test_garbage_cursor_is_400(client, alice, chat):
url = "/api/v1/chats/" + chat["id"] + "/messages"
for bad in ["garbage", "!!!", "e30", "a" * 600, "eyJzIjoibWVzc2FnZXM6eCJ9"]:
assert_error(
client.get(url + "?cursor=" + quote(bad), headers=alice.headers),
400,
"invalid_request",
)
def test_cursor_from_another_chat_is_400(client, alice, bob, make_chat, chat):
other = make_chat(alice, bob, title="Второй чат")
send_many(client, alice, chat, 5)
send_many(client, alice, other, 5)
first = client.get(
"/api/v1/chats/" + chat["id"] + "/messages?limit=2", headers=alice.headers
).json()
reply = client.get(
"/api/v1/chats/"
+ other["id"]
+ "/messages?cursor="
+ quote(first["next_cursor"], safe=""),
headers=alice.headers,
)
assert_error(reply, 400, "invalid_request")
def test_chat_list_pagination(client, alice, bob, make_chat):
created = [make_chat(alice, bob, title="Чат %02d" % n)["id"] for n in range(5)]
seen, cursor = [], None
while True:
query = "?limit=2" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
data = client.get("/api/v1/chats" + query, headers=bob.headers).json()
seen += [c["id"] for c in data["items"]]
cursor = data["next_cursor"]
if cursor is None:
break
assert seen == created
def test_chat_list_cursor_cannot_be_used_for_messages(
client, alice, bob, make_chat, chat
):
make_chat(alice, bob, title="ещё")
cursor = client.get("/api/v1/chats?limit=1", headers=alice.headers).json()[
"next_cursor"
]
reply = client.get(
"/api/v1/chats/" + chat["id"] + "/messages?cursor=" + quote(cursor, safe=""),
headers=alice.headers,
)
assert_error(reply, 400, "invalid_request")
@pytest.mark.parametrize("stamp", [-1, 10**30, MAX_TIMESTAMP_MICROS + 1, True, 1.5, "1", None])
@pytest.mark.parametrize("resource", ["messages", "chats"])
def test_invalid_cursor_timestamp_is_400(client, alice, chat, stamp, resource):
scope = "messages:" + chat["id"] if resource == "messages" else "chats:" + alice.id
path = "/api/v1/chats/" + chat["id"] + "/messages" if resource == "messages" else "/api/v1/chats"
cursor = encode_cursor(scope, (stamp, chat["id"]))
assert_error(client.get(path, params={"cursor": cursor}, headers=alice.headers), 400, "invalid_request")
@pytest.mark.parametrize("stamp", [0, MAX_TIMESTAMP_MICROS])
@pytest.mark.parametrize("resource", ["messages", "chats"])
def test_cursor_timestamp_boundaries_are_valid(client, alice, chat, stamp, resource):
scope = "messages:" + chat["id"] if resource == "messages" else "chats:" + alice.id
path = "/api/v1/chats/" + chat["id"] + "/messages" if resource == "messages" else "/api/v1/chats"
cursor = encode_cursor(scope, (stamp, chat["id"]))
reply = client.get(path, params={"cursor": cursor}, headers=alice.headers)
assert reply.status_code == 200, reply.text
+56
View File
@@ -0,0 +1,56 @@
"""Истечение сессий."""
import time
from fastapi.testclient import TestClient
from app.main import create_app
from conftest import assert_error, make_settings, register_and_login
def test_session_expires_after_ttl():
with TestClient(
create_app(make_settings(session_ttl_seconds=1)), raise_server_exceptions=False
) as short:
person = register_and_login(short, "ttl")
assert short.get("/api/v1/users/me", headers=person.headers).status_code == 200
time.sleep(2.2)
reply = short.get("/api/v1/users/me", headers=person.headers)
assert_error(reply, 401, "unauthorized")
assert reply.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
def test_expired_sessions_are_cleaned_on_next_login():
"""Истёкшие сессии удаляются при следующем входе."""
from conftest import basic_header, run_sql
import uuid
with TestClient(
create_app(make_settings(session_ttl_seconds=1)), raise_server_exceptions=False
) as short:
person = register_and_login(short, "clean")
time.sleep(1.5)
short.post(
"/api/v1/auth/sessions",
headers=basic_header(person.username, person.password),
)
rows = run_sql(
"SELECT token_hash FROM sessions WHERE user_id = $1", uuid.UUID(person.id)
)
assert len(rows) == 1
def test_short_ttl_from_environment_variable():
"""Короткий SESSION_TTL_SECONDS из окружения."""
from conftest import CACHE_URL, sqlalchemy_url
from app.config import Settings
settings = Settings.from_env(
{"DATABASE_URL": sqlalchemy_url(), "SESSION_TTL_SECONDS": "2", "CACHE_URL": CACHE_URL}
)
assert settings.session_ttl_seconds == 2
with TestClient(create_app(settings), raise_server_exceptions=False) as short:
person = register_and_login(short, "envttl")
assert short.get("/api/v1/users/me", headers=person.headers).status_code == 200
time.sleep(2.5)
assert_error(short.get("/api/v1/users/me", headers=person.headers), 401, "unauthorized")
+69
View File
@@ -0,0 +1,69 @@
"""Транзакции, пул соединений и таймауты."""
import time
import uuid
import httpx
from fastapi.testclient import TestClient
from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncSession
from app.main import create_app
from app.models import ChatMember
from conftest import assert_error, make_settings, register_and_login, run_sql
def test_failure_after_chat_insert_rolls_back_whole_operation(client, alice, bob, monkeypatch):
"""Сбой после вставки чата откатывает всю операцию."""
real_execute = AsyncSession.execute
async def failing_execute(self, statement, *args, **kwargs):
if getattr(getattr(statement, "table", None), "name", None) == ChatMember.__tablename__:
raise OperationalError("INSERT INTO chat_members", {}, Exception("injected"))
return await real_execute(self, statement, *args, **kwargs)
monkeypatch.setattr(AsyncSession, "execute", failing_execute)
title = "rollback-" + uuid.uuid4().hex
reply = client.post(
"/api/v1/chats", json={"title": title, "member_ids": [alice.id, bob.id]},
headers=alice.headers,
)
monkeypatch.undo()
assert_error(reply, 503, "unavailable")
assert "injected" not in reply.text and "chat_members" not in reply.text
assert run_sql("SELECT count(*) AS n FROM chats WHERE title = $1", title)[0]["n"] == 0
assert run_sql(
"SELECT count(*) AS n FROM chat_members m JOIN chats c ON c.id = m.chat_id"
" WHERE c.title = $1", title,
)[0]["n"] == 0
def test_pool_is_bounded_by_settings():
settings = make_settings(db_pool_size=3, db_max_overflow=2, db_pool_timeout=4)
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
pool = app_client.app.state.engine.pool
assert pool.size() == 3
assert pool._max_overflow == 2
assert pool._timeout == 4
def test_exhausted_pool_gives_fast_503():
"""Занятый пул даёт 503 за время DB_POOL_TIMEOUT."""
settings = make_settings(db_pool_size=1, db_max_overflow=0, db_pool_timeout=1, cache_url="")
with TestClient(create_app(settings), raise_server_exceptions=False) as app_client:
person = register_and_login(app_client, "pool")
app = app_client.app
async def scenario():
async with app.state.engine.connect():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as http:
started = time.monotonic()
reply = await http.get("/api/v1/users/me", headers=person.headers)
return reply, time.monotonic() - started
reply, elapsed = app_client.portal.call(scenario)
assert_error(reply, 503, "unavailable")
assert elapsed < 3
assert app_client.get("/api/v1/users/me", headers=person.headers).status_code == 200