init commit: create skeleton from lab1
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
"""Фикстуры для тестов с РЕАЛЬНОЙ PostgreSQL (SQLite не подходит — см. README лабы).
|
||||
|
||||
Перед запуском поднимите БД и создайте тестовую базу:
|
||||
make db-up # docker compose up -d postgres + createdb messenger_test
|
||||
Переменные:
|
||||
TEST_DATABASE_URL по умолчанию postgresql+psycopg://messenger:messenger@localhost:5432/messenger_test
|
||||
TEST_USE_MIGRATIONS=1 строить схему через `alembic upgrade head` вместо Base.metadata.create_all
|
||||
"""
|
||||
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.main import create_app
|
||||
from app.models import Base
|
||||
|
||||
DEFAULT_TEST_DATABASE_URL = (
|
||||
"postgresql+psycopg://messenger:messenger@localhost:5432/messenger_test"
|
||||
)
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
return os.environ.get("TEST_DATABASE_URL", DEFAULT_TEST_DATABASE_URL)
|
||||
|
||||
|
||||
def _alembic_config(url: str) -> Config:
|
||||
config = Config("alembic.ini")
|
||||
config.set_main_option("sqlalchemy.url", url.replace("%", "%%"))
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def database_url() -> str:
|
||||
return _database_url()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def db_engine(database_url: str) -> Iterator[Engine]:
|
||||
engine = create_engine(database_url)
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
except Exception as error: # noqa: BLE001
|
||||
pytest.exit(
|
||||
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
|
||||
f"{type(error).__name__}. Выполните `make db-up`.",
|
||||
returncode=2,
|
||||
)
|
||||
|
||||
# Чистая схема на старте сессии: тесты не зависят от прошлых запусков.
|
||||
Base.metadata.drop_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
|
||||
if os.environ.get("TEST_USE_MIGRATIONS") == "1":
|
||||
command.upgrade(_alembic_config(database_url), "head")
|
||||
else:
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
yield engine
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_db(db_engine: Engine) -> Iterator[None]:
|
||||
"""Пустые таблицы перед каждым тестом (приложение коммитит, откат не годится)."""
|
||||
names = ", ".join(f'"{table.name}"' for table in Base.metadata.sorted_tables)
|
||||
if names:
|
||||
with db_engine.begin() as connection:
|
||||
connection.execute(text(f"TRUNCATE {names} RESTART IDENTITY CASCADE"))
|
||||
yield
|
||||
|
||||
|
||||
def build_settings(database_url: str, **overrides: object) -> Settings:
|
||||
values: dict[str, object] = {
|
||||
"app_host": "127.0.0.1",
|
||||
"app_port": 8080,
|
||||
"app_env": "test",
|
||||
"max_messages": 1000,
|
||||
"max_in_flight": 32,
|
||||
"log_level": "CRITICAL",
|
||||
"database_url": database_url,
|
||||
"session_ttl_seconds": 300,
|
||||
"db_pool_size": 10,
|
||||
"db_max_overflow": 10,
|
||||
}
|
||||
values.update(overrides)
|
||||
return Settings(_env_file=None, **values) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def settings(database_url: str) -> Settings:
|
||||
return build_settings(database_url)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_settings(database_url: str) -> Callable[..., Settings]:
|
||||
"""Settings с переопределениями: make_settings(session_ttl_seconds=1)."""
|
||||
|
||||
def factory(**overrides: object) -> Settings:
|
||||
return build_settings(database_url, **overrides)
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(settings: Settings):
|
||||
application = create_app(settings)
|
||||
|
||||
@application.get("/__test__/explode", include_in_schema=False)
|
||||
def explode() -> None:
|
||||
raise RuntimeError("test-secret")
|
||||
|
||||
return application
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app) -> Iterator[TestClient]:
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client_no_raise(app) -> Iterator[TestClient]:
|
||||
with TestClient(app, raise_server_exceptions=False) as test_client:
|
||||
yield test_client
|
||||
@@ -0,0 +1,81 @@
|
||||
import base64
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
PASSWORD = "Correct-horse-battery-1" # синтетический пароль, только для тестов
|
||||
|
||||
|
||||
def basic_header(username: str, password: str) -> dict[str, str]:
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
||||
|
||||
|
||||
def bearer(actor: dict) -> dict[str, str]:
|
||||
return {"Authorization": "Bearer " + actor["token"]}
|
||||
|
||||
|
||||
def register(
|
||||
client: TestClient,
|
||||
username: str | None = None,
|
||||
display_name: str = "Тестовый пользователь",
|
||||
password: str = PASSWORD,
|
||||
) -> dict:
|
||||
"""Регистрация без входа. Возвращает User + password (нужен для login)."""
|
||||
actual_username = username or "user_" + uuid4().hex[:12]
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": actual_username,
|
||||
"display_name": display_name,
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return {**response.json(), "password": password}
|
||||
|
||||
|
||||
def login(client: TestClient, user: dict) -> dict:
|
||||
response = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return {**user, "token": response.json()["token"]}
|
||||
|
||||
|
||||
def create_user(client: TestClient, **kwargs) -> dict:
|
||||
"""Регистрация + вход: актор с полями id, username, token, ..."""
|
||||
return login(client, register(client, **kwargs))
|
||||
|
||||
|
||||
def create_chat(
|
||||
client: TestClient,
|
||||
user: dict,
|
||||
*members: dict,
|
||||
title: str = "Тестовый чат",
|
||||
) -> dict:
|
||||
member_ids = [user["id"], *(member["id"] for member in members)]
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(user),
|
||||
json={"title": title, "member_ids": member_ids},
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def send_message(client: TestClient, user: dict, chat: dict, text: str):
|
||||
return client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=bearer(user),
|
||||
json={"text": text},
|
||||
)
|
||||
|
||||
|
||||
def assert_request_id(response) -> str:
|
||||
header_id = response.headers.get("X-Request-Id")
|
||||
assert header_id
|
||||
if response.status_code >= 400:
|
||||
assert response.json()["error"]["request_id"] == header_id
|
||||
return header_id
|
||||
@@ -0,0 +1,175 @@
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import create_app
|
||||
from tests.helpers import (
|
||||
PASSWORD,
|
||||
assert_request_id,
|
||||
basic_header,
|
||||
bearer,
|
||||
create_user,
|
||||
login,
|
||||
register,
|
||||
)
|
||||
|
||||
|
||||
def test_login_returns_opaque_bearer_session(client: TestClient):
|
||||
user = register(client)
|
||||
|
||||
response = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], user["password"]),
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
body = response.json()
|
||||
assert set(body) == {"token", "token_type", "expires_at", "user"}
|
||||
assert body["token_type"] == "Bearer"
|
||||
assert len(body["token"]) >= 43 # 256 бит в base64url
|
||||
assert body["token"] not in (user["id"], user["username"])
|
||||
assert body["user"]["id"] == user["id"]
|
||||
assert body["expires_at"].endswith("Z")
|
||||
assert datetime.fromisoformat(body["expires_at"].replace("Z", "+00:00"))
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_each_login_issues_a_different_token(client: TestClient):
|
||||
user = register(client)
|
||||
first = login(client, user)
|
||||
second = login(client, user)
|
||||
|
||||
assert first["token"] != second["token"]
|
||||
|
||||
|
||||
def test_password_with_colon_works(client: TestClient):
|
||||
user = register(client, password="pass:with:colons-123")
|
||||
|
||||
assert login(client, user)["token"]
|
||||
|
||||
|
||||
def test_unicode_password_works(client: TestClient):
|
||||
user = register(client, password="Пароль-с-юникодом-🔑-123")
|
||||
|
||||
assert login(client, user)["token"]
|
||||
|
||||
|
||||
def test_wrong_password_and_unknown_user_look_identical(client: TestClient):
|
||||
user = register(client)
|
||||
|
||||
wrong_password = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header(user["username"], "wrong-password-123"),
|
||||
)
|
||||
unknown_user = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic_header("no_such_user", "wrong-password-123"),
|
||||
)
|
||||
|
||||
for response in (wrong_password, unknown_user):
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert response.headers["WWW-Authenticate"].startswith('Basic realm="messenger"')
|
||||
assert_request_id(response)
|
||||
assert wrong_password.json()["error"]["message"] == unknown_user.json()["error"]["message"]
|
||||
|
||||
|
||||
def test_login_requires_basic_scheme(client: TestClient):
|
||||
user = register(client)
|
||||
session = login(client, user)
|
||||
|
||||
for headers in ({}, bearer(session), {"Authorization": "Basic !!!not-base64"}):
|
||||
response = client.post("/api/v1/auth/sessions", headers=headers)
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"].startswith("Basic")
|
||||
|
||||
|
||||
def test_business_endpoints_require_bearer(client: TestClient):
|
||||
user = register(client)
|
||||
|
||||
for headers in (
|
||||
{},
|
||||
basic_header(user["username"], user["password"]),
|
||||
{"Authorization": "Bearer "},
|
||||
{"Authorization": "Bearer unknown-token-value"},
|
||||
{"X-User-Id": user["id"]},
|
||||
):
|
||||
response = client.get("/api/v1/users/me", headers=headers)
|
||||
assert response.status_code == 401, headers
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert response.headers["WWW-Authenticate"].startswith('Bearer realm="messenger"')
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_x_user_id_cannot_override_bearer_identity(client: TestClient):
|
||||
alice = create_user(client)
|
||||
eve = create_user(client)
|
||||
|
||||
response = client.get(
|
||||
"/api/v1/users/me",
|
||||
headers={**bearer(alice), "X-User-Id": eve["id"]},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == alice["id"]
|
||||
|
||||
|
||||
def test_logout_revokes_only_current_session(client: TestClient):
|
||||
user = register(client)
|
||||
first = login(client, user)
|
||||
second = login(client, user)
|
||||
|
||||
assert client.delete("/api/v1/auth/sessions/current", headers=bearer(first)).status_code == 204
|
||||
|
||||
assert client.get("/api/v1/users/me", headers=bearer(first)).status_code == 401
|
||||
assert client.get("/api/v1/users/me", headers=bearer(second)).status_code == 200
|
||||
|
||||
|
||||
def test_logout_twice_returns_401(client: TestClient):
|
||||
session = create_user(client)
|
||||
|
||||
first = client.delete("/api/v1/auth/sessions/current", headers=bearer(session))
|
||||
again = client.delete("/api/v1/auth/sessions/current", headers=bearer(session))
|
||||
|
||||
assert first.status_code == 204
|
||||
assert first.content == b""
|
||||
assert again.status_code == 401
|
||||
|
||||
|
||||
def test_session_expires_after_ttl(make_settings):
|
||||
app = create_app(make_settings(session_ttl_seconds=2))
|
||||
with TestClient(app) as client:
|
||||
session = create_user(client)
|
||||
assert client.get("/api/v1/users/me", headers=bearer(session)).status_code == 200
|
||||
|
||||
time.sleep(3)
|
||||
|
||||
response = client.get("/api/v1/users/me", headers=bearer(session))
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"].startswith("Bearer")
|
||||
|
||||
|
||||
def test_token_is_not_stored_in_plaintext(client: TestClient, db_engine):
|
||||
from sqlalchemy import text
|
||||
|
||||
session = create_user(client)
|
||||
|
||||
with db_engine.connect() as connection:
|
||||
stored = connection.execute(text("SELECT token_hash FROM sessions")).scalars().all()
|
||||
|
||||
assert stored and session["token"] not in stored
|
||||
|
||||
|
||||
def test_password_is_not_stored_in_plaintext(client: TestClient, db_engine):
|
||||
from sqlalchemy import text
|
||||
|
||||
register(client, username="hash_check")
|
||||
|
||||
with db_engine.connect() as connection:
|
||||
stored = connection.execute(
|
||||
text("SELECT password_hash FROM users WHERE username = 'hash_check'")
|
||||
).scalar_one()
|
||||
|
||||
assert PASSWORD not in stored
|
||||
assert stored.startswith("$argon2id$")
|
||||
@@ -0,0 +1,185 @@
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.helpers import assert_request_id, bearer, create_chat, create_user
|
||||
|
||||
|
||||
def test_create_and_get_chat(client: TestClient):
|
||||
alice = create_user(client)
|
||||
bob = create_user(client)
|
||||
chat = create_chat(client, alice, bob)
|
||||
|
||||
response = client.get(
|
||||
f"/api/v1/chats/{chat['id']}",
|
||||
headers=bearer(bob),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == chat
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_chat_is_not_visible_to_outsider(client: TestClient):
|
||||
alice = create_user(client)
|
||||
bob = create_user(client)
|
||||
eve = create_user(client)
|
||||
chat = create_chat(client, alice, bob)
|
||||
|
||||
response = client.get(
|
||||
f"/api/v1/chats/{chat['id']}",
|
||||
headers=bearer(eve),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_chat_creation_requires_creator_in_members(client: TestClient):
|
||||
alice = create_user(client)
|
||||
bob = create_user(client)
|
||||
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [bob["id"]]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"title": "", "member_ids": []},
|
||||
{"title": " ", "member_ids": []},
|
||||
],
|
||||
)
|
||||
def test_chat_payload_boundaries(client: TestClient, payload: dict):
|
||||
alice = create_user(client)
|
||||
payload["member_ids"] = [alice["id"]]
|
||||
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json=payload,
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_duplicate_members_are_rejected(client: TestClient):
|
||||
alice = create_user(client)
|
||||
bob = create_user(client)
|
||||
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [alice["id"], bob["id"], bob["id"]]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_unknown_member_is_rejected(client: TestClient):
|
||||
alice = create_user(client)
|
||||
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_chat_exact_title_limit_is_accepted(client: TestClient):
|
||||
alice = create_user(client)
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "x" * 100, "member_ids": [alice["id"]]},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert len(response.json()["title"]) == 100
|
||||
|
||||
|
||||
def test_chat_list_hides_chats_without_membership(client: TestClient):
|
||||
alice = create_user(client)
|
||||
bob = create_user(client)
|
||||
chat_for_bob = create_chat(client, bob, title="Only Bob")
|
||||
chat_for_alice = create_chat(client, alice, title="Only Alice")
|
||||
|
||||
response = client.get(
|
||||
"/api/v1/chats?limit=100",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
ids = {item["id"] for item in response.json()["items"]}
|
||||
assert chat_for_alice["id"] in ids
|
||||
assert chat_for_bob["id"] not in ids
|
||||
|
||||
|
||||
def test_nonexistent_chat_returns_404(client: TestClient):
|
||||
alice = create_user(client)
|
||||
|
||||
response = client.get(
|
||||
"/api/v1/chats/00000000-0000-4000-8000-000000000000",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_failed_chat_creation_leaves_no_partial_data(client: TestClient, db_engine):
|
||||
"""Атомарность: неизвестный участник -> нет ни чата, ни записей членства."""
|
||||
from sqlalchemy import text
|
||||
|
||||
alice = create_user(client)
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
with db_engine.connect() as connection:
|
||||
assert connection.execute(text("SELECT count(*) FROM chats")).scalar_one() == 0
|
||||
assert (
|
||||
connection.execute(text("SELECT count(*) FROM chat_members")).scalar_one() == 0
|
||||
)
|
||||
|
||||
|
||||
def test_chat_list_pagination_and_order(client: TestClient):
|
||||
alice = create_user(client)
|
||||
chats = [create_chat(client, alice, title=f"chat-{i}") for i in range(5)]
|
||||
|
||||
page1 = client.get("/api/v1/chats?limit=2", headers=bearer(alice)).json()
|
||||
page2 = client.get(
|
||||
f"/api/v1/chats?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
).json()
|
||||
page3 = client.get(
|
||||
f"/api/v1/chats?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
).json()
|
||||
|
||||
ids = [c["id"] for page in (page1, page2, page3) for c in page["items"]]
|
||||
assert ids == [c["id"] for c in chats]
|
||||
assert page3["next_cursor"] is None
|
||||
|
||||
|
||||
def test_chat_endpoints_require_bearer(client: TestClient):
|
||||
assert client.get("/api/v1/chats").status_code == 401
|
||||
assert client.post("/api/v1/chats", json={"title": "x", "member_ids": []}).status_code in (401, 400)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Конкурентность на реальной БД: гонка регистрации и параллельная запись."""
|
||||
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import create_app
|
||||
from tests.helpers import PASSWORD, bearer, create_chat, create_user
|
||||
|
||||
|
||||
def test_parallel_registration_of_same_username_creates_exactly_one_user(make_settings):
|
||||
"""Источник истины для уникальности — UNIQUE в БД, а не проверка «SELECT, потом INSERT»."""
|
||||
app = create_app(make_settings(max_in_flight=64, db_pool_size=20, db_max_overflow=20))
|
||||
|
||||
async def scenario() -> list[int]:
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app),
|
||||
base_url="http://testserver",
|
||||
timeout=30,
|
||||
) as client:
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": "race_user",
|
||||
"display_name": "Race",
|
||||
"password": PASSWORD,
|
||||
},
|
||||
)
|
||||
for _ in range(16)
|
||||
)
|
||||
)
|
||||
return [response.status_code for response in responses]
|
||||
|
||||
statuses = Counter(asyncio.run(scenario()))
|
||||
|
||||
assert statuses == Counter({201: 1, 409: 15}), statuses # ни одного 500
|
||||
|
||||
|
||||
def test_100_messages_from_10_clients(make_settings):
|
||||
app = create_app(
|
||||
make_settings(
|
||||
max_messages=1000, max_in_flight=100, db_pool_size=20, db_max_overflow=20
|
||||
)
|
||||
)
|
||||
|
||||
with TestClient(app) as setup:
|
||||
users = [create_user(setup, username=f"load_{i}_{uuid4().hex[:6]}") for i in range(10)]
|
||||
chat = setup.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(users[0]),
|
||||
json={"title": "Concurrency", "member_ids": [u["id"] for u in users]},
|
||||
).json()
|
||||
|
||||
async def scenario() -> None:
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app),
|
||||
base_url="http://testserver",
|
||||
timeout=30,
|
||||
) as client:
|
||||
|
||||
async def worker(index: int, user: dict) -> list[dict]:
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=bearer(user),
|
||||
json={"text": f"client-{index}-message-{n}"},
|
||||
)
|
||||
for n in range(10)
|
||||
)
|
||||
)
|
||||
assert all(r.status_code == 201 for r in responses), [
|
||||
r.text for r in responses if r.status_code != 201
|
||||
]
|
||||
return [r.json() for r in responses]
|
||||
|
||||
results = await asyncio.gather(*(worker(i, u) for i, u in enumerate(users)))
|
||||
messages = [m for batch in results for m in batch]
|
||||
|
||||
assert len(messages) == 100
|
||||
assert len({m["id"] for m in messages}) == 100
|
||||
assert Counter(m["sender_id"] for m in messages) == Counter(
|
||||
{u["id"]: 10 for u in users}
|
||||
)
|
||||
|
||||
history = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=bearer(users[0])
|
||||
)
|
||||
items = history.json()["items"]
|
||||
assert len(items) == 100
|
||||
assert len({m["id"] for m in items}) == 100
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_chat_creation_in_parallel_is_atomic(make_settings, db_engine):
|
||||
from sqlalchemy import text
|
||||
|
||||
app = create_app(make_settings(max_in_flight=32, db_pool_size=20, db_max_overflow=20))
|
||||
with TestClient(app) as setup:
|
||||
alice = create_user(setup)
|
||||
bob = create_user(setup)
|
||||
|
||||
async def scenario() -> None:
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app),
|
||||
base_url="http://testserver",
|
||||
timeout=30,
|
||||
) as client:
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/chats",
|
||||
headers=bearer(alice),
|
||||
json={"title": f"c{i}", "member_ids": [alice["id"], bob["id"]]},
|
||||
)
|
||||
for i in range(10)
|
||||
)
|
||||
)
|
||||
assert all(r.status_code == 201 for r in responses)
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
with db_engine.connect() as connection:
|
||||
chats = connection.execute(text("SELECT count(*) FROM chats")).scalar_one()
|
||||
members = connection.execute(text("SELECT count(*) FROM chat_members")).scalar_one()
|
||||
assert chats == 10 and members == 20
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Ограничения на уровне БД: приложение — не единственный защитник данных."""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from tests.helpers import create_chat, create_user
|
||||
|
||||
|
||||
def test_duplicate_username_is_rejected_by_database(client, db_engine):
|
||||
create_user(client, username="unique_name")
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
with db_engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (gen_random_uuid(), 'unique_name', 'Other', 'hash')"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_message_requires_existing_chat(client, db_engine):
|
||||
alice = create_user(client)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
with db_engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text) "
|
||||
"VALUES (gen_random_uuid(), gen_random_uuid(), :sender, 'x')"
|
||||
),
|
||||
{"sender": alice["id"]},
|
||||
)
|
||||
|
||||
|
||||
def test_duplicate_membership_is_rejected_by_database(client, db_engine):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
with db_engine.begin() as connection:
|
||||
connection.execute(
|
||||
text("INSERT INTO chat_members (chat_id, user_id) VALUES (:c, :u)"),
|
||||
{"c": chat["id"], "u": alice["id"]},
|
||||
)
|
||||
@@ -0,0 +1,74 @@
|
||||
import logging
|
||||
import json
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.helpers import assert_request_id
|
||||
|
||||
|
||||
def test_missing_token_returns_401(client: TestClient):
|
||||
response = client.get("/api/v1/users/me")
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_garbage_token_returns_401(client: TestClient):
|
||||
response = client.get(
|
||||
"/api/v1/users/me", headers={"Authorization": "Bearer garbage"}
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_malformed_json_returns_400(client: TestClient):
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
content='{"username":"alice",',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_not_found_returns_404(client: TestClient):
|
||||
response = client.get("/no-such-path")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_method_not_allowed_preserves_405(client: TestClient):
|
||||
response = client.delete("/api/v1/users")
|
||||
|
||||
assert response.status_code == 405
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_unhandled_exception_is_hidden_from_client(client_no_raise: TestClient, caplog):
|
||||
with caplog.at_level(logging.ERROR, logger="app.errors.handlers"):
|
||||
response = client_no_raise.get("/__test__/explode")
|
||||
|
||||
assert response.status_code == 500
|
||||
payload = response.json()
|
||||
assert payload["error"]["code"] == "internal_error"
|
||||
assert payload["error"]["message"] == "Внутренняя ошибка сервера"
|
||||
assert "test-secret" not in json.dumps(payload, ensure_ascii=False)
|
||||
assert "Traceback" not in json.dumps(payload, ensure_ascii=False)
|
||||
assert "Unhandled error request_id=" in caplog.text
|
||||
assert "test-secret" in caplog.text
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_success_response_contains_request_id(client: TestClient):
|
||||
response = client.get("/health/live")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers.get("X-Request-Id")
|
||||
@@ -0,0 +1,61 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import create_app
|
||||
from tests.helpers import assert_request_id
|
||||
|
||||
|
||||
def test_liveness(client: TestClient):
|
||||
response = client.get("/health/live")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_readiness(client: TestClient):
|
||||
response = client.get("/health/ready")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_readiness_is_503_when_database_is_down(make_settings):
|
||||
"""БД недоступна: live по-прежнему 200, ready — ограниченный 503."""
|
||||
app = create_app(
|
||||
make_settings(
|
||||
database_url="postgresql+psycopg://nobody:nopass@127.0.0.1:1/none",
|
||||
db_connect_timeout_seconds=1,
|
||||
)
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/health/live").status_code == 200
|
||||
|
||||
ready = client.get("/health/ready")
|
||||
assert ready.status_code == 503
|
||||
assert ready.json()["error"]["code"] == "unavailable"
|
||||
assert_request_id(ready)
|
||||
|
||||
|
||||
def test_business_request_is_503_when_database_is_down(make_settings):
|
||||
"""Недоступность БД не превращается в 500 и не раскрывает детали подключения."""
|
||||
app = create_app(
|
||||
make_settings(
|
||||
database_url="postgresql+psycopg://nobody:secretpass@127.0.0.1:1/none",
|
||||
db_connect_timeout_seconds=1,
|
||||
)
|
||||
)
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": "alice",
|
||||
"display_name": "Alice",
|
||||
"password": "Correct-horse-battery-1",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert "secretpass" not in response.text
|
||||
assert_request_id(response)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Остаток трека «управляемая деградация»: MAX_IN_FLIGHT -> 429, MAX_MESSAGES -> 503."""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import create_app
|
||||
from tests.helpers import assert_request_id, bearer, create_chat, create_user
|
||||
|
||||
|
||||
def _assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
assert response.status_code == status
|
||||
body = response.json()
|
||||
assert body["error"]["code"] == code
|
||||
assert response.headers.get("X-Request-Id") == body["error"]["request_id"]
|
||||
|
||||
|
||||
def test_message_limit_rejects_without_deleting_confirmed_messages(make_settings):
|
||||
app = create_app(make_settings(max_messages=2))
|
||||
with TestClient(app) as client:
|
||||
user = create_user(client)
|
||||
chat = create_chat(client, user)
|
||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
for index in range(2):
|
||||
ok = client.post(url, headers=bearer(user), json={"text": f"confirmed-{index}"})
|
||||
assert ok.status_code == 201
|
||||
|
||||
rejected = client.post(url, headers=bearer(user), json={"text": "rejected"})
|
||||
_assert_error(rejected, 503, "unavailable")
|
||||
|
||||
history = client.get(f"{url}?limit=100", headers=bearer(user))
|
||||
assert history.status_code == 200
|
||||
assert [m["text"] for m in history.json()["items"]] == ["confirmed-0", "confirmed-1"]
|
||||
|
||||
|
||||
def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypatch):
|
||||
import app.endpoints.messages as message_endpoint
|
||||
|
||||
app = create_app(make_settings(max_in_flight=2))
|
||||
|
||||
original_send_message = message_endpoint.send_message
|
||||
accepted_count = 0
|
||||
accepted_lock = threading.Lock()
|
||||
all_slots_taken = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def blocking_send_message(*args, **kwargs):
|
||||
nonlocal accepted_count
|
||||
with accepted_lock:
|
||||
accepted_count += 1
|
||||
if accepted_count == 2:
|
||||
all_slots_taken.set()
|
||||
if not release.wait(timeout=5):
|
||||
raise AssertionError("test release event was not set")
|
||||
return original_send_message(*args, **kwargs)
|
||||
|
||||
# Подготовка данных до подмены (на ней же проверяем, что слоты освобождаются).
|
||||
with TestClient(app) as setup_client:
|
||||
user = create_user(setup_client)
|
||||
chat = create_chat(setup_client, user)
|
||||
|
||||
monkeypatch.setattr(message_endpoint, "send_message", blocking_send_message)
|
||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
async def scenario() -> None:
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app),
|
||||
base_url="http://testserver",
|
||||
timeout=10,
|
||||
) as client:
|
||||
held = [
|
||||
asyncio.create_task(
|
||||
client.post(url, headers=bearer(user), json={"text": f"held-{i}"})
|
||||
)
|
||||
for i in range(2)
|
||||
]
|
||||
|
||||
assert await asyncio.to_thread(all_slots_taken.wait, 2)
|
||||
|
||||
rejected = await asyncio.gather(
|
||||
*(
|
||||
client.post(url, headers=bearer(user), json={"text": f"rejected-{i}"})
|
||||
for i in range(4)
|
||||
)
|
||||
)
|
||||
for response in rejected:
|
||||
_assert_error(response, 429, "rate_limited")
|
||||
assert response.headers.get("Retry-After") == "1"
|
||||
|
||||
# Health не ограничивается лимитом.
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
|
||||
release.set()
|
||||
assert all(r.status_code == 201 for r in await asyncio.gather(*held))
|
||||
|
||||
recovered = await client.post(url, headers=bearer(user), json={"text": "after"})
|
||||
assert recovered.status_code == 201
|
||||
assert_request_id(recovered)
|
||||
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,216 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.helpers import (
|
||||
assert_request_id,
|
||||
bearer,
|
||||
create_chat,
|
||||
create_user,
|
||||
send_message,
|
||||
)
|
||||
|
||||
|
||||
def _message(client: TestClient, user: dict, chat: dict, text: str):
|
||||
return send_message(client, user, chat, text)
|
||||
|
||||
|
||||
def test_send_and_list_message(client: TestClient):
|
||||
alice = create_user(client)
|
||||
bob = create_user(client)
|
||||
chat = create_chat(client, alice, bob)
|
||||
|
||||
created = _message(client, alice, chat, "Привет, мир 👋")
|
||||
|
||||
assert created.status_code == 201
|
||||
message = created.json()
|
||||
assert message["sender_id"] == alice["id"]
|
||||
assert message["chat_id"] == chat["id"]
|
||||
assert_request_id(created)
|
||||
|
||||
listed = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1",
|
||||
headers=bearer(bob),
|
||||
)
|
||||
|
||||
assert listed.status_code == 200
|
||||
assert listed.json()["items"] == [message]
|
||||
assert listed.json()["next_cursor"] is None
|
||||
assert_request_id(listed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", "x" * 4001])
|
||||
def test_invalid_message_text(client: TestClient, text: str):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
|
||||
response = _message(client, alice, chat, text)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_extra_message_field_is_rejected(client: TestClient):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
|
||||
response = client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=bearer(alice),
|
||||
json={"text": "hello", "sender_id": alice["id"]},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_messages_are_private_to_chat_members(client: TestClient):
|
||||
alice = create_user(client)
|
||||
eve = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
_message(client, alice, chat, "секрет")
|
||||
|
||||
response = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers=bearer(eve),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
def test_pagination_has_no_duplicates(client: TestClient):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
|
||||
created = [
|
||||
_message(client, alice, chat, f"message-{index}").json() for index in range(5)
|
||||
]
|
||||
|
||||
page1 = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=2",
|
||||
headers=bearer(alice),
|
||||
).json()
|
||||
page2 = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
).json()
|
||||
page3 = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
).json()
|
||||
|
||||
ids = [item["id"] for page in (page1, page2, page3) for item in page["items"]]
|
||||
assert ids == [item["id"] for item in created]
|
||||
assert len(ids) == len(set(ids)) == 5
|
||||
assert len(page1["items"]) == 2
|
||||
assert len(page2["items"]) == 2
|
||||
assert len(page3["items"]) == 1
|
||||
assert page3["next_cursor"] is None
|
||||
|
||||
|
||||
def test_cursor_cannot_be_used_for_another_chat(client: TestClient):
|
||||
alice = create_user(client)
|
||||
chat_a = create_chat(client, alice, title="A")
|
||||
chat_b = create_chat(client, alice, title="B")
|
||||
|
||||
_message(client, alice, chat_a, "a1")
|
||||
_message(client, alice, chat_a, "a2")
|
||||
_message(client, alice, chat_b, "b1")
|
||||
_message(client, alice, chat_b, "b2")
|
||||
|
||||
page = client.get(
|
||||
f"/api/v1/chats/{chat_a['id']}/messages?limit=1",
|
||||
headers=bearer(alice),
|
||||
).json()
|
||||
|
||||
response = client.get(
|
||||
f"/api/v1/chats/{chat_b['id']}/messages?limit=1&cursor={quote(page['next_cursor'], safe='')}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"limit, expected_status", [(0, 400), (1, 200), (100, 200), (101, 400)]
|
||||
)
|
||||
def test_limit_boundaries(client: TestClient, limit: int, expected_status: int):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
_message(client, alice, chat, "one")
|
||||
|
||||
response = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit={limit}",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == expected_status
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_message_exact_max_length_is_accepted(client: TestClient):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
|
||||
response = _message(client, alice, chat, "x" * 4000)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert len(response.json()["text"]) == 4000
|
||||
|
||||
|
||||
def test_nonexistent_chat_messages_return_404(client: TestClient):
|
||||
alice = create_user(client)
|
||||
|
||||
response = client.get(
|
||||
"/api/v1/chats/00000000-0000-4000-8000-000000000000/messages",
|
||||
headers=bearer(alice),
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_unauthenticated_requests_are_rejected(client: TestClient):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
assert client.get(url).status_code == 401
|
||||
assert client.post(url, json={"text": "hi"}).status_code == 401
|
||||
|
||||
|
||||
def test_messages_survive_new_login(client: TestClient):
|
||||
"""Сообщения принадлежат пользователю, а не сессии: после logout/login видны."""
|
||||
from tests.helpers import login
|
||||
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
message = _message(client, alice, chat, "до выхода").json()
|
||||
client.delete("/api/v1/auth/sessions/current", headers=bearer(alice))
|
||||
|
||||
alice_again = login(client, alice)
|
||||
listed = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages", headers=bearer(alice_again)
|
||||
)
|
||||
|
||||
assert listed.json()["items"] == [message]
|
||||
|
||||
|
||||
def test_history_order_is_created_at_then_id(client: TestClient):
|
||||
alice = create_user(client)
|
||||
chat = create_chat(client, alice)
|
||||
created = [_message(client, alice, chat, f"m{i}").json() for i in range(10)]
|
||||
|
||||
listed = client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=bearer(alice)
|
||||
).json()["items"]
|
||||
|
||||
assert [m["id"] for m in listed] == [m["id"] for m in created]
|
||||
keys = [(m["created_at"], m["id"]) for m in listed]
|
||||
assert keys == sorted(keys)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Миграции с нуля: «миграции с нуля и повторный запуск без дублирования данных»."""
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
from app.models import Base
|
||||
from tests.conftest import _alembic_config
|
||||
|
||||
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "sessions"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def migrated_engine(database_url, db_engine):
|
||||
# db_engine гарантирует, что БД доступна; переключаем схему на «только миграции».
|
||||
engine = create_engine(database_url)
|
||||
Base.metadata.drop_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
|
||||
command.upgrade(_alembic_config(database_url), "head")
|
||||
yield engine
|
||||
|
||||
Base.metadata.drop_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
Base.metadata.create_all(engine) # вернуть схему для остальных тестов
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_upgrade_creates_all_tables(migrated_engine):
|
||||
assert EXPECTED_TABLES <= set(inspect(migrated_engine).get_table_names())
|
||||
|
||||
|
||||
def test_upgrade_twice_is_idempotent_and_keeps_data(migrated_engine, database_url):
|
||||
with migrated_engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (gen_random_uuid(), 'keep_me', 'Keep', 'hash')"
|
||||
)
|
||||
)
|
||||
|
||||
command.upgrade(_alembic_config(database_url), "head") # повторный запуск
|
||||
|
||||
with migrated_engine.connect() as connection:
|
||||
count = connection.execute(
|
||||
text("SELECT count(*) FROM users WHERE username = 'keep_me'")
|
||||
).scalar_one()
|
||||
assert count == 1
|
||||
|
||||
|
||||
def test_models_and_migrations_are_in_sync(migrated_engine):
|
||||
"""Нет расхождений между ORM-моделями и схемой, созданной миграциями."""
|
||||
with migrated_engine.connect() as connection:
|
||||
context = MigrationContext.configure(connection, opts={"compare_type": True})
|
||||
diff = compare_metadata(context, Base.metadata)
|
||||
|
||||
assert diff == [], f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
||||
@@ -0,0 +1,103 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.helpers import PASSWORD, assert_request_id, bearer, create_user, register
|
||||
|
||||
|
||||
def test_register_does_not_leak_password(client: TestClient):
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "alice", "display_name": "Алиса 👋", "password": PASSWORD},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
body = response.json()
|
||||
assert set(body) == {"id", "username", "display_name", "created_at"}
|
||||
assert PASSWORD not in response.text
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_get_current_user(client: TestClient):
|
||||
user = create_user(client, display_name="Алиса 👋")
|
||||
|
||||
response = client.get("/api/v1/users/me", headers=bearer(user))
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["id"] == user["id"]
|
||||
assert response.json()["username"] == user["username"]
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"username": "alice", "display_name": "", "password": PASSWORD},
|
||||
{"username": "alice", "display_name": " ", "password": PASSWORD},
|
||||
{"username": "alice", "display_name": "a" * 101, "password": PASSWORD},
|
||||
{"username": "ab", "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "alice-123", "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "AlicE", "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "a" * 33, "display_name": "Alice", "password": PASSWORD},
|
||||
{"username": "alice", "display_name": "Alice"}, # нет пароля
|
||||
{"username": "alice", "display_name": "Alice", "password": "x" * 11},
|
||||
{"username": "alice", "display_name": "Alice", "password": "x" * 129},
|
||||
],
|
||||
)
|
||||
def test_invalid_user_payloads(client: TestClient, body: dict):
|
||||
response = client.post("/api/v1/users", json=body)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_password_length_boundaries_are_accepted(client: TestClient):
|
||||
for index, password in enumerate(["x" * 12, "y" * 128, " " * 12, "п" * 12]):
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": f"pw_user_{index}",
|
||||
"display_name": "Alice",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 201, (index, response.text)
|
||||
|
||||
|
||||
def test_extra_user_field_is_rejected(client: TestClient):
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": "alice",
|
||||
"display_name": "Alice",
|
||||
"password": PASSWORD,
|
||||
"extra": True,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_duplicate_username_returns_conflict(client: TestClient):
|
||||
user = register(client, username="duplicate_user")
|
||||
|
||||
response = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": user["username"],
|
||||
"display_name": "Другой",
|
||||
"password": PASSWORD,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 409
|
||||
assert response.json()["error"]["code"] == "conflict"
|
||||
assert_request_id(response)
|
||||
|
||||
|
||||
def test_user_exact_length_boundaries_are_accepted(client: TestClient):
|
||||
for length in (3, 32):
|
||||
user = register(client, username=("a" * length), display_name="d" * 100)
|
||||
assert len(user["username"]) == length
|
||||
assert len(user["display_name"]) == 100
|
||||
Reference in New Issue
Block a user