forked from mtusi2026/mtusi2026lab3
feat: перенос core-логики 2 лабы
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import auth, basic, unique_password, unique_username
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
|
||||
|
||||
REQUEST_TIMEOUT_SEC = 10
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def base_url() -> str:
|
||||
return os.environ.get("BASE_URL") or DEFAULT_BASE_URL
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def api(base_url: str) -> Iterator[httpx.Client]:
|
||||
with httpx.Client(base_url=base_url, timeout=REQUEST_TIMEOUT_SEC) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def register_and_login(
|
||||
client: httpx.Client, label: str, display_name: str | None = None
|
||||
) -> dict:
|
||||
"""Регистрация и вход; в словаре User плюс token и password для тестов"""
|
||||
username = unique_username(label)
|
||||
password = unique_password()
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": display_name or f"Студент {label}",
|
||||
"password": password,
|
||||
}
|
||||
response = client.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201, response.text
|
||||
user = response.json()
|
||||
session = client.post("/api/v1/auth/sessions", headers=basic(username, password))
|
||||
assert session.status_code == 201, session.text
|
||||
return {**user, "token": session.json()["token"], "password": password}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_user(api: httpx.Client) -> Callable[..., dict]:
|
||||
def create(label: str = "user", display_name: str | None = None) -> dict:
|
||||
return register_and_login(api, label, display_name)
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_chat(api: httpx.Client) -> Callable[..., dict]:
|
||||
def create(owner: dict, members: list[dict], title: str = "Тестовый чат") -> dict:
|
||||
body = {"title": title, "member_ids": [member["id"] for member in members]}
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(owner))
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def send_message(api: httpx.Client) -> Callable[..., dict]:
|
||||
def send(user: dict, chat: dict, text: str) -> dict:
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=auth(user),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
return send
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Общие проверки для собственных black-box тестов"""
|
||||
|
||||
import base64
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
USER_FIELDS = ("id", "username", "display_name", "created_at")
|
||||
|
||||
|
||||
def unique_username(label: str) -> str:
|
||||
return f"st_{label}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def unique_password() -> str:
|
||||
return f"Pw-{uuid.uuid4().hex}"
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
"""Authorization: Basic; пароль кодируется в UTF-8"""
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
||||
|
||||
|
||||
def auth(user: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {user['token']}"}
|
||||
|
||||
|
||||
def public_user(user: dict) -> dict:
|
||||
"""User из ответа API без тестовых полей token/password"""
|
||||
return {field: user[field] for field in USER_FIELDS}
|
||||
|
||||
|
||||
def assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
"""Код ответа и единый формат ошибки: request_id совпадает с заголовком"""
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
error = response.json()["error"]
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def assert_unauthorized(response: httpx.Response, scheme: str = "Bearer") -> None:
|
||||
"""401 с challenge нужной схемы"""
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert response.headers["WWW-Authenticate"].startswith(scheme)
|
||||
|
||||
|
||||
def read_all_messages(
|
||||
api: httpx.Client, user: dict, chat_id: str, limit: int
|
||||
) -> tuple[list[dict], int]:
|
||||
"""Обход истории по next_cursor; возвращает сообщения и число страниц"""
|
||||
items: list[dict] = []
|
||||
pages = 0
|
||||
params: dict[str, str | int] = {"limit": limit}
|
||||
while True:
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_id}/messages", params=params, headers=auth(user)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
items.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
return items, pages
|
||||
params = {"limit": limit, "cursor": page["next_cursor"]}
|
||||
|
||||
|
||||
def compose(*args: str, stdin: str | None = None) -> str:
|
||||
"""docker compose из корня репозитория; вывод не печатается (может быть секретен)"""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
"""Запрос в PostgreSQL стенда изнутри контейнера; порт БД наружу не открыт"""
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
stdin=sql,
|
||||
).strip()
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Вход по Basic, opaque Bearer-сессия, неверный пароль и logout"""
|
||||
|
||||
import base64
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_unauthorized,
|
||||
auth,
|
||||
basic,
|
||||
psql,
|
||||
public_user,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
SESSIONS_PATH = "/api/v1/auth/sessions"
|
||||
CURRENT_SESSION_PATH = "/api/v1/auth/sessions/current"
|
||||
|
||||
|
||||
def test_login_returns_opaque_bearer_session(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
response = api.post(
|
||||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
session = response.json()
|
||||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert session["user"] == public_user(alice)
|
||||
assert len(session["token"]) >= 43 # 32 байта в base64url
|
||||
assert alice["id"] not in session["token"]
|
||||
assert alice["username"] not in session["token"]
|
||||
assert session["token"] != alice["token"]
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
assert expires_at > datetime.now(UTC)
|
||||
|
||||
|
||||
def test_wrong_password_and_unknown_user_are_indistinguishable(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
wrong = api.post(SESSIONS_PATH, headers=basic(alice["username"], "Wrong-pass-123"))
|
||||
unknown = api.post(
|
||||
SESSIONS_PATH, headers=basic(unique_username("ghost"), "Wrong-pass-123")
|
||||
)
|
||||
for response in (wrong, unknown):
|
||||
assert_unauthorized(response, scheme="Basic")
|
||||
assert 'realm="messenger"' in response.headers["WWW-Authenticate"]
|
||||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"authorization",
|
||||
[
|
||||
None,
|
||||
"",
|
||||
"Basic",
|
||||
"Basic !!!not-base64!!!",
|
||||
"Basic " + base64.b64encode(b"no-colon-here").decode(),
|
||||
"Basic " + base64.b64encode(b"\xff\xfe:password").decode(),
|
||||
"Bearer some-token",
|
||||
],
|
||||
)
|
||||
def test_malformed_basic_is_unauthorized(
|
||||
api: httpx.Client, authorization: str | None
|
||||
) -> None:
|
||||
headers = {} if authorization is None else {"Authorization": authorization}
|
||||
assert_unauthorized(api.post(SESSIONS_PATH, headers=headers), scheme="Basic")
|
||||
|
||||
|
||||
def test_utf8_password_with_colon(api: httpx.Client) -> None:
|
||||
username = unique_username("utf")
|
||||
password = "пароль:с:двоеточием 🔐"
|
||||
body = {"username": username, "display_name": "x", "password": password}
|
||||
assert api.post("/api/v1/users", json=body).status_code == 201
|
||||
assert api.post(SESSIONS_PATH, headers=basic(username, password)).status_code == 201
|
||||
assert_unauthorized(
|
||||
api.post(SESSIONS_PATH, headers=basic(username, "пароль:с:двоеточием")),
|
||||
scheme="Basic",
|
||||
)
|
||||
|
||||
|
||||
def test_basic_is_rejected_on_business_endpoints(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
headers = basic(alice["username"], alice["password"])
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
|
||||
|
||||
|
||||
def test_logout_revokes_only_current_session(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
second = api.post(
|
||||
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
|
||||
)
|
||||
other_session = {**alice, "token": second.json()["token"]}
|
||||
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
response = api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||||
assert response.status_code == 204
|
||||
assert response.content == b""
|
||||
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH, headers=auth(alice)))
|
||||
assert api.get("/api/v1/users/me", headers=auth(other_session)).status_code == 200
|
||||
|
||||
|
||||
def test_logout_without_token(api: httpx.Client) -> None:
|
||||
assert_unauthorized(api.delete(CURRENT_SESSION_PATH))
|
||||
assert_unauthorized(
|
||||
api.delete(CURRENT_SESSION_PATH, headers={"Authorization": "Bearer unknown"})
|
||||
)
|
||||
|
||||
|
||||
def test_relogin_after_logout(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
|
||||
again = api.post(SESSIONS_PATH, headers=basic(alice["username"], alice["password"]))
|
||||
assert again.status_code == 201
|
||||
renewed = {**alice, "token": again.json()["token"]}
|
||||
assert api.get("/api/v1/users/me", headers=auth(renewed)).status_code == 200
|
||||
|
||||
|
||||
def test_password_is_not_stored_in_plaintext(make_user) -> None:
|
||||
"""Проверка в БД стенда: в users лежит PHC-строка Argon2id, а не пароль"""
|
||||
alice = make_user("alice")
|
||||
stored = psql(
|
||||
f"SELECT password_hash FROM users WHERE username = '{alice['username']}';"
|
||||
)
|
||||
assert stored.startswith("$argon2id$")
|
||||
assert alice["password"] not in stored
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Защита состояния от гонок: 100 сообщений от 10 параллельных клиентов"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
import httpx
|
||||
from helpers import auth, read_all_messages
|
||||
|
||||
CLIENTS = 10
|
||||
MESSAGES_PER_CLIENT = 10
|
||||
TOTAL_MESSAGES = CLIENTS * MESSAGES_PER_CLIENT
|
||||
PAGE_LIMIT = 30
|
||||
|
||||
|
||||
async def _send_concurrently(
|
||||
base_url: str, chat_id: str, users: list[dict]
|
||||
) -> list[int]:
|
||||
"""Каждый клиент — отдельный пользователь и пул соединений; старт по сигналу"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def client_worker(user: dict) -> list[int]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, headers=auth(user), timeout=30
|
||||
) as client:
|
||||
await start.wait()
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": f"{user['username']}#{n}"},
|
||||
)
|
||||
for n in range(MESSAGES_PER_CLIENT)
|
||||
)
|
||||
)
|
||||
return [response.status_code for response in responses]
|
||||
|
||||
workers = [asyncio.create_task(client_worker(user)) for user in users]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
results = await asyncio.gather(*workers)
|
||||
return [status for statuses in results for status in statuses]
|
||||
|
||||
|
||||
def test_parallel_messages_are_not_lost_or_duplicated(
|
||||
api: httpx.Client, base_url: str, make_user, make_chat
|
||||
) -> None:
|
||||
users = [make_user(f"c{n}") for n in range(CLIENTS)]
|
||||
chat = make_chat(users[0], users)
|
||||
|
||||
started = time.perf_counter()
|
||||
statuses = asyncio.run(_send_concurrently(base_url, chat["id"], users))
|
||||
elapsed = time.perf_counter() - started
|
||||
|
||||
items, pages = read_all_messages(api, users[-1], chat["id"], PAGE_LIMIT)
|
||||
expected_texts = {
|
||||
f"{user['username']}#{n}" for user in users for n in range(MESSAGES_PER_CLIENT)
|
||||
}
|
||||
summary = {
|
||||
"clients": CLIENTS,
|
||||
"messages_sent": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"messages_read": len(items),
|
||||
"unique_ids": len({item["id"] for item in items}),
|
||||
"unique_texts": len({item["text"] for item in items}),
|
||||
"pages_read": pages,
|
||||
"send_seconds": round(elapsed, 3),
|
||||
}
|
||||
print("\nCONCURRENCY RESULT:", json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
assert statuses == [201] * TOTAL_MESSAGES
|
||||
assert len(items) == TOTAL_MESSAGES
|
||||
assert summary["unique_ids"] == TOTAL_MESSAGES
|
||||
assert {item["text"] for item in items} == expected_texts
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
assert len(set(keys)) == TOTAL_MESSAGES
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Отказы зависимостей: Valkey и PostgreSQL останавливаются через docker compose.
|
||||
|
||||
Тесты меняют состояние стенда (stop/start контейнеров, volumes сохраняются),
|
||||
поэтому запускаются только явно: make test-failures (RUN_FAILURE_TESTS=1).
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, assert_unauthorized, auth, basic, compose
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("RUN_FAILURE_TESTS") != "1",
|
||||
reason="останавливает контейнеры стенда: запускайте через make test-failures",
|
||||
)
|
||||
|
||||
READY_TIMEOUT_SEC = 60
|
||||
# Ответ при упавшей зависимости должен быть быстрым, а не висеть до таймаута клиента
|
||||
BOUNDED_RESPONSE_SEC = 3
|
||||
|
||||
|
||||
def wait_ready(api: httpx.Client) -> None:
|
||||
deadline = time.monotonic() + READY_TIMEOUT_SEC
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if api.get("/health/ready").status_code == 200:
|
||||
return
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("API не стал готов после восстановления зависимости")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valkey_stopped(api: httpx.Client) -> Iterator[None]:
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
wait_ready(api)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def postgres_stopped(api: httpx.Client) -> Iterator[None]:
|
||||
compose("stop", "postgres")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
compose("up", "-d", "--wait", "postgres")
|
||||
wait_ready(api)
|
||||
|
||||
|
||||
def test_valkey_down_cache_is_bypassed(
|
||||
api: httpx.Client, make_user, make_chat, send_message, valkey_stopped
|
||||
) -> None:
|
||||
"""Без Valkey всё работает через PostgreSQL: вход, Bearer, запись, logout"""
|
||||
alice = make_user("alice")
|
||||
started = time.monotonic()
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200, me.text
|
||||
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
|
||||
|
||||
chat = make_chat(alice, [alice])
|
||||
send_message(alice, chat, "без кэша")
|
||||
assert api.get("/health/ready").status_code == 200
|
||||
|
||||
assert (
|
||||
api.delete("/api/v1/auth/sessions/current", headers=auth(alice)).status_code
|
||||
== 204
|
||||
)
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(api.get("/api/v1/users/me"))
|
||||
|
||||
|
||||
def test_logout_during_valkey_outage_is_not_resurrected(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
"""
|
||||
Сессия попала в кэш, затем Valkey упал и пользователь вышел. После подъёма
|
||||
Valkey (без persistence — пустой) отозванный токен не принимается.
|
||||
"""
|
||||
alice = make_user("alice")
|
||||
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
response = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
assert response.status_code == 204
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
wait_ready(api)
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
|
||||
|
||||
def test_postgres_down_returns_bounded_503_and_no_anonymous_access(
|
||||
api: httpx.Client, make_user, postgres_stopped
|
||||
) -> None:
|
||||
alice_token_unused = {"token": "x" * 43}
|
||||
|
||||
started = time.monotonic()
|
||||
ready = api.get("/health/ready")
|
||||
assert_error(ready, 503, "unavailable")
|
||||
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
|
||||
|
||||
# Анонимный запрос остаётся 401, неизвестный токен не принимается как доверенный
|
||||
assert_unauthorized(api.get("/api/v1/users/me"))
|
||||
unknown = api.get("/api/v1/users/me", headers=auth(alice_token_unused))
|
||||
assert_error(unknown, 503, "unavailable")
|
||||
assert "asyncpg" not in unknown.text and "postgres" not in unknown.text.lower()
|
||||
|
||||
body = {"username": "st_pg_down", "display_name": "x", "password": "P" * 12}
|
||||
assert_error(api.post("/api/v1/users", json=body), 503, "unavailable")
|
||||
login = api.post("/api/v1/auth/sessions", headers=basic("st_pg_down", "P" * 12))
|
||||
assert_error(login, 503, "unavailable")
|
||||
|
||||
|
||||
def test_session_survives_postgres_restart(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
compose("restart", "postgres")
|
||||
wait_ready(api)
|
||||
chats = api.get("/api/v1/chats", headers=auth(alice))
|
||||
assert chats.status_code == 200, chats.text
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
Истечение сессии при коротком SESSION_TTL_SECONDS.
|
||||
|
||||
Нужен отдельный API с SESSION_TTL_SECONDS=2: make test-expiry поднимает
|
||||
api-short-ttl на :8081 поверх тех же PostgreSQL и Valkey.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from conftest import register_and_login
|
||||
from helpers import assert_unauthorized, auth, basic
|
||||
|
||||
EXPIRY_BASE_URL = os.environ.get("EXPIRY_BASE_URL")
|
||||
SHORT_TTL_SEC = 2
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not EXPIRY_BASE_URL, reason="EXPIRY_BASE_URL не задан: запустите make test-expiry"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def short_api() -> httpx.Client:
|
||||
assert EXPIRY_BASE_URL is not None
|
||||
with httpx.Client(base_url=EXPIRY_BASE_URL, timeout=10) as client:
|
||||
yield client
|
||||
|
||||
|
||||
def test_session_expires_after_short_ttl(short_api: httpx.Client) -> None:
|
||||
alice = register_and_login(short_api, "ttl")
|
||||
me = short_api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200, me.text
|
||||
|
||||
time.sleep(SHORT_TTL_SEC + 1)
|
||||
|
||||
# Сессия уже лежала в кэше после первого запроса: истечь должна и там
|
||||
assert_unauthorized(short_api.get("/api/v1/users/me", headers=auth(alice)))
|
||||
assert_unauthorized(short_api.get("/api/v1/chats", headers=auth(alice)))
|
||||
assert_unauthorized(
|
||||
short_api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
|
||||
)
|
||||
|
||||
|
||||
def test_expires_at_matches_short_ttl(short_api: httpx.Client) -> None:
|
||||
before = datetime.now(UTC)
|
||||
alice = register_and_login(short_api, "ttl")
|
||||
session = short_api.post(
|
||||
"/api/v1/auth/sessions", headers=basic(alice["username"], alice["password"])
|
||||
).json()
|
||||
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
lifetime = (expires_at - before).total_seconds()
|
||||
assert 0 < lifetime <= SHORT_TTL_SEC + 1
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Чужой чат: посторонний получает 404, существование чата не раскрывается"""
|
||||
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth
|
||||
|
||||
|
||||
def test_outsider_cannot_access_chat(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
send_message(alice, chat, "секрет")
|
||||
path = f"/api/v1/chats/{chat['id']}"
|
||||
|
||||
assert_error(api.get(path, headers=auth(eve)), 404, "not_found")
|
||||
assert_error(api.get(f"{path}/messages", headers=auth(eve)), 404, "not_found")
|
||||
response = api.post(f"{path}/messages", json={"text": "чужое"}, headers=auth(eve))
|
||||
assert_error(response, 404, "not_found")
|
||||
|
||||
history = api.get(f"{path}/messages", headers=auth(bob)).json()
|
||||
assert [item["text"] for item in history["items"]] == ["секрет"]
|
||||
|
||||
|
||||
def test_foreign_and_missing_chat_are_indistinguishable(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
foreign = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(eve)).json()
|
||||
missing = api.get(f"/api/v1/chats/{uuid.uuid4()}", headers=auth(eve)).json()
|
||||
assert foreign["error"]["code"] == missing["error"]["code"] == "not_found"
|
||||
assert foreign["error"]["message"] == missing["error"]["message"]
|
||||
|
||||
|
||||
def test_chat_list_contains_only_own_chats(
|
||||
api: httpx.Client, make_user, make_chat
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
chat = make_chat(alice, [alice])
|
||||
own = api.get("/api/v1/chats", headers=auth(eve)).json()
|
||||
assert own == {"items": [], "next_cursor": None}
|
||||
listed = api.get("/api/v1/chats", headers=auth(alice)).json()
|
||||
assert [item["id"] for item in listed["items"]] == [chat["id"]]
|
||||
@@ -0,0 +1,15 @@
|
||||
import httpx
|
||||
from helpers import assert_error
|
||||
|
||||
|
||||
def test_health_endpoints_have_request_id(api: httpx.Client) -> None:
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
response = api.get(path)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def test_unknown_route_uses_error_format(api: httpx.Client) -> None:
|
||||
assert_error(api.get("/api/v1/unknown"), 404, "not_found")
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Неверный JSON и неверная структура тела — 400 invalid_request"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth
|
||||
|
||||
PASSWORD = "Valid-password-123"
|
||||
|
||||
MALFORMED_BODIES = [
|
||||
b'{"username": "abc",',
|
||||
b"not json at all",
|
||||
b'{"text": "\xff\xfe"}',
|
||||
b"",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", MALFORMED_BODIES)
|
||||
def test_malformed_json_on_register(api: httpx.Client, raw: bytes) -> None:
|
||||
response = api.post(
|
||||
"/api/v1/users", content=raw, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", MALFORMED_BODIES)
|
||||
def test_malformed_json_on_create_chat_and_message(
|
||||
api: httpx.Client, make_user, make_chat, raw: bytes
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
headers = {**auth(alice), "Content-Type": "application/json"}
|
||||
assert_error(
|
||||
api.post("/api/v1/chats", content=raw, headers=headers), 400, "invalid_request"
|
||||
)
|
||||
assert_error(
|
||||
api.post(f"/api/v1/chats/{chat['id']}/messages", content=raw, headers=headers),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
[],
|
||||
"alice",
|
||||
{"username": "valid_name", "password": PASSWORD},
|
||||
{"username": 123, "display_name": "x", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": None, "password": PASSWORD},
|
||||
{
|
||||
"username": "valid_name",
|
||||
"display_name": "x",
|
||||
"password": PASSWORD,
|
||||
"is_admin": True,
|
||||
},
|
||||
{"username": "Upper_Case", "display_name": "x", "password": PASSWORD},
|
||||
{"username": "ab", "display_name": "x", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": " ", "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": "я" * 101, "password": PASSWORD},
|
||||
{"username": "valid_name", "display_name": "a\u0000b", "password": PASSWORD},
|
||||
],
|
||||
)
|
||||
def test_invalid_user_payload(api: httpx.Client, body: object) -> None:
|
||||
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"text": 42},
|
||||
{"text": "привет", "sender_id": "11111111-1111-4111-8111-111111111111"},
|
||||
{},
|
||||
],
|
||||
)
|
||||
def test_invalid_message_payload(
|
||||
api: httpx.Client, make_user, make_chat, body: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=auth(alice)
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_invalid_chat_payload(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
cases = [
|
||||
{"title": "t", "member_ids": [bob["id"]]},
|
||||
{"title": "t", "member_ids": [alice["id"], alice["id"]]},
|
||||
{
|
||||
"title": "t",
|
||||
"member_ids": [alice["id"], "11111111-1111-4111-8111-111111111111"],
|
||||
},
|
||||
{"title": "t", "member_ids": [alice["id"], "not-a-uuid"]},
|
||||
{"title": "t", "member_ids": []},
|
||||
{"title": " ", "member_ids": [alice["id"]]},
|
||||
]
|
||||
for body in cases:
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Пустые сообщения, границы длины и Unicode"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", " ", " \n\t ", " "])
|
||||
def test_empty_or_blank_message_is_rejected(
|
||||
api: httpx.Client, make_user, make_chat, text: str
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=auth(alice)
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
history = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice))
|
||||
assert history.json()["items"] == []
|
||||
|
||||
|
||||
def test_message_length_is_counted_in_code_points(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
longest = "😀" * 4000
|
||||
assert send_message(alice, chat, longest)["text"] == longest
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "😀" * 4001},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_unicode_is_preserved(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
name = "Алиса 👩💻 é"
|
||||
alice = make_user("alice", display_name=name)
|
||||
assert alice["display_name"] == name
|
||||
chat = make_chat(alice, [alice], title="Чат 🚀 中文")
|
||||
assert chat["title"] == "Чат 🚀 中文"
|
||||
text = "Привет, мир 👋 — «кавычки» \t\n и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
|
||||
message = send_message(alice, chat, text)
|
||||
assert message["text"] == text
|
||||
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice)).json()
|
||||
assert page["items"][0]["text"] == text
|
||||
|
||||
|
||||
def test_nul_character_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
|
||||
"""PostgreSQL text не хранит U+0000: отказ 400 до записи, а не 500"""
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "до\u0000после"},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
response = api.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "a\u0000b", "member_ids": [alice["id"]]},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_sender_is_taken_from_session(make_user, make_chat, send_message) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
message = send_message(bob, chat, "от Боба")
|
||||
assert message["sender_id"] == bob["id"]
|
||||
assert message["chat_id"] == chat["id"]
|
||||
assert message["created_at"].endswith("Z")
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Обход нескольких страниц истории и списка чатов по cursor"""
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import assert_error, auth, read_all_messages
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("total", "limit", "expected_pages"),
|
||||
[(7, 3, 3), (6, 3, 2), (5, 1, 5), (3, 100, 1)],
|
||||
)
|
||||
def test_walk_message_pages(
|
||||
api: httpx.Client,
|
||||
make_user,
|
||||
make_chat,
|
||||
send_message,
|
||||
total: int,
|
||||
limit: int,
|
||||
expected_pages: int,
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
chat = make_chat(alice, [alice, bob])
|
||||
sent = [send_message(alice if n % 2 else bob, chat, f"m{n}") for n in range(total)]
|
||||
|
||||
items, pages = read_all_messages(api, bob, chat["id"], limit)
|
||||
|
||||
assert pages == expected_pages
|
||||
assert items == sent
|
||||
assert len({item["id"] for item in items}) == total
|
||||
keys = [(item["created_at"], item["id"]) for item in items]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
def test_limit_can_change_between_pages(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
sent = [send_message(alice, chat, f"m{n}") for n in range(6)]
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
first = api.get(path, params={"limit": 2}, headers=auth(alice)).json()
|
||||
second = api.get(
|
||||
path, params={"limit": 4, "cursor": first["next_cursor"]}, headers=auth(alice)
|
||||
).json()
|
||||
|
||||
assert first["items"] + second["items"] == sent
|
||||
assert second["next_cursor"] is None
|
||||
|
||||
|
||||
def test_new_message_appears_after_cursor(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
send_message(alice, chat, "m0")
|
||||
send_message(alice, chat, "m1")
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
first = api.get(path, params={"limit": 1}, headers=auth(alice)).json()
|
||||
late = send_message(alice, chat, "m2")
|
||||
rest = api.get(
|
||||
path, params={"limit": 10, "cursor": first["next_cursor"]}, headers=auth(alice)
|
||||
).json()
|
||||
assert [item["text"] for item in rest["items"]] == ["m1", "m2"]
|
||||
assert rest["items"][-1] == late
|
||||
|
||||
|
||||
def test_cursor_is_bound_to_chat(
|
||||
api: httpx.Client, make_user, make_chat, send_message
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat_a = make_chat(alice, [alice], title="A")
|
||||
chat_b = make_chat(alice, [alice], title="B")
|
||||
for n in range(3):
|
||||
send_message(alice, chat_a, f"a{n}")
|
||||
cursor = api.get(
|
||||
f"/api/v1/chats/{chat_a['id']}/messages",
|
||||
params={"limit": 1},
|
||||
headers=auth(alice),
|
||||
).json()["next_cursor"]
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_b['id']}/messages",
|
||||
params={"cursor": cursor},
|
||||
headers=auth(alice),
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"params",
|
||||
[
|
||||
{"limit": 0},
|
||||
{"limit": 101},
|
||||
{"limit": "abc"},
|
||||
{"cursor": ""},
|
||||
{"cursor": "not-a-cursor"},
|
||||
{"cursor": "eyJzY29wZSI6IDF9"},
|
||||
],
|
||||
)
|
||||
def test_invalid_limit_or_cursor(
|
||||
api: httpx.Client, make_user, make_chat, params: dict
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
chat = make_chat(alice, [alice])
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages", params=params, headers=auth(alice)
|
||||
)
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_walk_chat_list_pages(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
created = [make_chat(alice, [alice], title=f"chat {n}") for n in range(5)]
|
||||
listed: list[dict] = []
|
||||
params: dict[str, str | int] = {"limit": 2}
|
||||
pages = 0
|
||||
while True:
|
||||
page = api.get("/api/v1/chats", params=params, headers=auth(alice)).json()
|
||||
listed.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
break
|
||||
params = {"limit": 2, "cursor": page["next_cursor"]}
|
||||
assert pages == 3
|
||||
assert listed == created
|
||||
|
||||
|
||||
def test_chat_cursor_is_bound_to_user(api: httpx.Client, make_user, make_chat) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
for n in range(2):
|
||||
make_chat(alice, [alice, bob], title=f"chat {n}")
|
||||
cursor = api.get("/api/v1/chats", params={"limit": 1}, headers=auth(alice)).json()[
|
||||
"next_cursor"
|
||||
]
|
||||
response = api.get("/api/v1/chats", params={"cursor": cursor}, headers=auth(bob))
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Гонка регистрации одинакового username и rollback создания чата"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from helpers import assert_error, auth, psql, unique_password, unique_username
|
||||
|
||||
PARALLEL_REGISTRATIONS = 20
|
||||
|
||||
|
||||
async def _register_concurrently(base_url: str, username: str) -> list[int]:
|
||||
"""Все запросы стартуют по одному сигналу, у каждого свой пароль"""
|
||||
start = asyncio.Event()
|
||||
|
||||
async def register(client: httpx.AsyncClient) -> int:
|
||||
await start.wait()
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "Гонка",
|
||||
"password": unique_password(),
|
||||
}
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
return response.status_code
|
||||
|
||||
limits = httpx.Limits(max_connections=PARALLEL_REGISTRATIONS)
|
||||
async with httpx.AsyncClient(
|
||||
base_url=base_url, timeout=30, limits=limits
|
||||
) as client:
|
||||
tasks = [
|
||||
asyncio.create_task(register(client)) for _ in range(PARALLEL_REGISTRATIONS)
|
||||
]
|
||||
await asyncio.sleep(0)
|
||||
start.set()
|
||||
return list(await asyncio.gather(*tasks))
|
||||
|
||||
|
||||
def test_same_username_race_creates_exactly_one_user(base_url: str) -> None:
|
||||
username = unique_username("race")
|
||||
statuses = asyncio.run(_register_concurrently(base_url, username))
|
||||
stored = psql(f"SELECT count(*) FROM users WHERE username = '{username}';")
|
||||
print(
|
||||
"\nREGISTRATION RACE:",
|
||||
json.dumps(
|
||||
{
|
||||
"requests": len(statuses),
|
||||
"status_201": statuses.count(201),
|
||||
"status_409": statuses.count(409),
|
||||
"rows_in_db": int(stored),
|
||||
}
|
||||
),
|
||||
)
|
||||
assert statuses.count(201) == 1
|
||||
assert statuses.count(409) == PARALLEL_REGISTRATIONS - 1
|
||||
assert stored == "1"
|
||||
|
||||
|
||||
def test_failed_chat_creation_is_rolled_back(api: httpx.Client, make_user) -> None:
|
||||
"""
|
||||
Строка chats вставляется первой, затем участники нарушают FK (неизвестный
|
||||
пользователь в конце списка). После 400 в БД не должно остаться ни чата
|
||||
с этим title, ни его участников: откатилась вся транзакция.
|
||||
"""
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"rollback-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}
|
||||
|
||||
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
|
||||
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert psql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0"
|
||||
orphan_members = psql(
|
||||
"SELECT count(*) FROM chat_members m "
|
||||
"LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL;"
|
||||
)
|
||||
assert orphan_members == "0"
|
||||
listed = api.get("/api/v1/chats", params={"limit": 100}, headers=auth(alice))
|
||||
assert all(chat["title"] != title for chat in listed.json()["items"])
|
||||
|
||||
|
||||
def test_successful_chat_creation_commits_all_members(
|
||||
api: httpx.Client, make_user
|
||||
) -> None:
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
title = f"commit-{uuid.uuid4().hex}"
|
||||
body = {"title": title, "member_ids": [bob["id"], alice["id"]]}
|
||||
chat = api.post("/api/v1/chats", json=body, headers=auth(alice)).json()
|
||||
assert chat["member_ids"] == [bob["id"], alice["id"]]
|
||||
members = psql(f"SELECT count(*) FROM chat_members WHERE chat_id = '{chat['id']}';")
|
||||
assert members == "2"
|
||||
again = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(bob)).json()
|
||||
assert again == chat
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Регистрация, дубликат username и идентификация только через Bearer"""
|
||||
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from helpers import (
|
||||
assert_error,
|
||||
assert_unauthorized,
|
||||
auth,
|
||||
public_user,
|
||||
unique_password,
|
||||
unique_username,
|
||||
)
|
||||
|
||||
|
||||
def test_duplicate_username_is_conflict(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("dup")
|
||||
body = {
|
||||
"username": alice["username"],
|
||||
"display_name": "B",
|
||||
"password": unique_password(),
|
||||
}
|
||||
assert_error(api.post("/api/v1/users", json=body), 409, "conflict")
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.json()["display_name"] == alice["display_name"]
|
||||
|
||||
|
||||
def test_registration_never_returns_password(api: httpx.Client) -> None:
|
||||
password = unique_password()
|
||||
body = {
|
||||
"username": unique_username("pw"),
|
||||
"display_name": "x",
|
||||
"password": password,
|
||||
}
|
||||
response = api.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201
|
||||
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
|
||||
assert password not in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"password",
|
||||
[None, "", "короткий", "x" * 11, "x" * 129, 123456789012],
|
||||
)
|
||||
def test_invalid_password_is_rejected(api: httpx.Client, password: object) -> None:
|
||||
body: dict[str, object] = {"username": unique_username("pw"), "display_name": "x"}
|
||||
if password is not None:
|
||||
body["password"] = password
|
||||
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
|
||||
|
||||
def test_password_length_is_counted_in_code_points(api: httpx.Client) -> None:
|
||||
for password in ("😀" * 12, "😀" * 128):
|
||||
body = {
|
||||
"username": unique_username("pw"),
|
||||
"display_name": "x",
|
||||
"password": password,
|
||||
}
|
||||
assert api.post("/api/v1/users", json=body).status_code == 201
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[
|
||||
{},
|
||||
{"Authorization": ""},
|
||||
{"Authorization": "Bearer"},
|
||||
{"Authorization": "Bearer not-a-real-token"},
|
||||
{"Authorization": "Bearer " + "x" * 5000},
|
||||
{"Authorization": "Token abc"},
|
||||
],
|
||||
)
|
||||
def test_missing_or_unknown_token_is_unauthorized(
|
||||
api: httpx.Client, headers: dict
|
||||
) -> None:
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
|
||||
|
||||
|
||||
def test_x_user_id_gives_no_access(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
eve = make_user("eve")
|
||||
assert_unauthorized(api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}))
|
||||
me = api.get("/api/v1/users/me", headers={**auth(alice), "X-User-Id": eve["id"]})
|
||||
assert me.json()["id"] == alice["id"]
|
||||
unknown = {"X-User-Id": str(uuid.uuid4())}
|
||||
assert_unauthorized(api.get("/api/v1/chats", headers=unknown))
|
||||
|
||||
|
||||
def test_current_user(api: httpx.Client, make_user) -> None:
|
||||
alice = make_user("alice")
|
||||
me = api.get("/api/v1/users/me", headers=auth(alice))
|
||||
assert me.status_code == 200
|
||||
assert me.json() == public_user(alice)
|
||||
Reference in New Issue
Block a user