add tests
This commit is contained in:
@@ -1,22 +1,47 @@
|
|||||||
-include .env
|
-include .env
|
||||||
|
|
||||||
PYTHON ?= python3
|
PYTHON ?= $(if $(wildcard venv/bin/python),venv/bin/python,python3)
|
||||||
BASE_URL ?= http://localhost:8080
|
BASE_URL ?= http://localhost:8080
|
||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
TEST_DATABASE_URL ?= postgresql+asyncpg://$(DB_USER):$(DB_PASSWORD)@localhost:5432/$(DB_NAME)_test
|
COMPOSE = docker compose --env-file .env
|
||||||
export TEST_DATABASE_URL
|
|
||||||
|
TEST_PROJECT ?= $(notdir $(CURDIR))-test
|
||||||
|
TEST_API_PORT ?= 18080
|
||||||
|
TEST_DB_PORT ?= 15432
|
||||||
|
TEST_REDIS_PORT ?= 16379
|
||||||
|
TEST_BASE_URL = http://localhost:$(TEST_API_PORT)
|
||||||
|
TEST_ENV = COMPOSE_PROJECT_NAME=$(TEST_PROJECT) API_HOST_PORT=$(TEST_API_PORT) \
|
||||||
|
DB_HOST_PORT=$(TEST_DB_PORT) REDIS_HOST_PORT=$(TEST_REDIS_PORT)
|
||||||
|
TEST_COMPOSE = $(TEST_ENV) $(COMPOSE)
|
||||||
|
|
||||||
|
TEST_DATABASE_URL ?= postgresql+asyncpg://$(DB_USER):$(DB_PASSWORD)@localhost:$(TEST_DB_PORT)/$(DB_NAME)_test
|
||||||
|
TEST_REDIS_HOST ?= localhost
|
||||||
|
TEST_REDIS_PASSWORD ?= $(REDIS_PASSWORD)
|
||||||
|
TEST_REDIS_DB ?= 15
|
||||||
|
export TEST_DATABASE_URL TEST_REDIS_HOST TEST_REDIS_PORT TEST_REDIS_PASSWORD TEST_REDIS_DB
|
||||||
|
|
||||||
|
define wait_ready
|
||||||
|
@for i in $$(seq 1 90); do \
|
||||||
|
curl -sf "$(1)/health/ready" >/dev/null && exit 0; sleep 1; \
|
||||||
|
done; echo "API $(1) не готов за 90 секунд" >&2; exit 1
|
||||||
|
endef
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence \
|
.PHONY: help check validate test load test-persistence \
|
||||||
up down logs db-up migrate migration \
|
up down restart ps logs migrate migration \
|
||||||
test-own test-limits test-concurrency test-migrations
|
test-stand-up test-stand-down test-stand-destroy test-stand-ps \
|
||||||
|
test-stand-smoke test-stand-persistence db-up \
|
||||||
|
test-own test-docker test-limits test-concurrency test-migrations test-all
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "Курс: check | validate | test (smoke по BASE_URL) | load | test-persistence ACTION_SCRIPT=scripts/restart.sh"
|
@echo "Курс: check | validate | test (smoke по BASE_URL) | load | test-persistence ACTION_SCRIPT=scripts/restart.sh"
|
||||||
@echo "Стенд: up | down | logs | db-up (только PostgreSQL + тестовая БД) | migrate"
|
@echo "Основной: up | down | restart | ps | logs | migrate | migration m='описание'"
|
||||||
@echo "Свои: test-own | test-limits | test-concurrency | test-migrations | migration m='описание'"
|
@echo "Тестовый: test-stand-up | test-stand-down | test-stand-destroy | test-stand-ps"
|
||||||
|
@echo " test-stand-smoke | test-stand-persistence"
|
||||||
|
@echo "Тесты: test-own | test-docker | test-limits | test-concurrency | test-migrations"
|
||||||
|
@echo "Всё: test-all (стенд + pytest + smoke + persistence на тестовом стенде)"
|
||||||
|
|
||||||
check:
|
check:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(PYTHON) scripts/check_contract.py
|
||||||
@@ -35,27 +60,58 @@ test-persistence:
|
|||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
up:
|
up:
|
||||||
docker compose --env-file .env up -d --build
|
$(COMPOSE) up -d --build
|
||||||
|
$(call wait_ready,$(BASE_URL))
|
||||||
|
|
||||||
down:
|
down:
|
||||||
docker compose down
|
$(COMPOSE) down
|
||||||
|
|
||||||
|
restart:
|
||||||
|
scripts/restart.sh
|
||||||
|
$(call wait_ready,$(BASE_URL))
|
||||||
|
|
||||||
|
ps:
|
||||||
|
$(COMPOSE) ps
|
||||||
|
|
||||||
logs:
|
logs:
|
||||||
docker compose logs -f api
|
$(COMPOSE) logs -f api
|
||||||
|
|
||||||
db-up:
|
|
||||||
docker compose up -d --wait postgres
|
|
||||||
docker compose exec -T postgres sh -c 'createdb -U "$$POSTGRES_USER" "$$POSTGRES_DB"_test 2>&1 | grep -v "already exists"; true'
|
|
||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
docker compose run --rm migrate
|
$(COMPOSE) run --rm --build migrate
|
||||||
|
|
||||||
migration:
|
migration:
|
||||||
$(PYTHON) -m alembic revision --autogenerate -m "$(m)"
|
DB_HOST=localhost $(PYTHON) -m alembic revision --autogenerate -m "$(m)"
|
||||||
|
|
||||||
|
test-stand-up:
|
||||||
|
$(TEST_COMPOSE) up -d --build
|
||||||
|
$(call wait_ready,$(TEST_BASE_URL))
|
||||||
|
$(TEST_COMPOSE) exec -T postgres sh -c 'createdb -U "$$POSTGRES_USER" "$$POSTGRES_DB"_test 2>&1 | grep -v "already exists"; true'
|
||||||
|
|
||||||
|
db-up: test-stand-up
|
||||||
|
|
||||||
|
test-stand-down:
|
||||||
|
$(TEST_COMPOSE) down
|
||||||
|
|
||||||
|
test-stand-destroy:
|
||||||
|
$(TEST_COMPOSE) down -v
|
||||||
|
|
||||||
|
test-stand-ps:
|
||||||
|
$(TEST_COMPOSE) ps
|
||||||
|
|
||||||
|
test-stand-smoke:
|
||||||
|
$(PYTHON) tests/smoke.py --base-url "$(TEST_BASE_URL)"
|
||||||
|
|
||||||
|
test-stand-persistence:
|
||||||
|
$(TEST_COMPOSE) ps
|
||||||
|
$(TEST_ENV) $(PYTHON) tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url "$(TEST_BASE_URL)"
|
||||||
|
$(TEST_COMPOSE) ps
|
||||||
|
|
||||||
test-own:
|
test-own:
|
||||||
$(PYTHON) -m pytest tests -q
|
$(PYTHON) -m pytest tests -q
|
||||||
|
|
||||||
|
test-docker:
|
||||||
|
$(TEST_ENV) DOCKER_TESTS=1 $(PYTHON) -m pytest tests -q
|
||||||
|
|
||||||
test-limits:
|
test-limits:
|
||||||
$(PYTHON) -m pytest tests/test_limits.py -q
|
$(PYTHON) -m pytest tests/test_limits.py -q
|
||||||
|
|
||||||
@@ -64,3 +120,5 @@ test-concurrency:
|
|||||||
|
|
||||||
test-migrations:
|
test-migrations:
|
||||||
$(PYTHON) -m pytest tests/test_migrations.py -q
|
$(PYTHON) -m pytest tests/test_migrations.py -q
|
||||||
|
|
||||||
|
test-all: test-stand-up test-docker test-stand-smoke test-stand-persistence
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
[alembic]
|
[alembic]
|
||||||
script_location = migrations
|
script_location = migrations
|
||||||
prepend_sys_path = .
|
prepend_sys_path = .
|
||||||
|
path_separator = os
|
||||||
|
|
||||||
[loggers]
|
[loggers]
|
||||||
keys = root,sqlalchemy,alembic
|
keys = root,sqlalchemy,alembic
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
"""Общие типы слоя хранения."""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
# Позиция в keyset-пагинации: (created_at, id) последнего виденного элемента.
|
|
||||||
Position = tuple[datetime, UUID]
|
Position = tuple[datetime, UUID]
|
||||||
|
|||||||
+3
-3
@@ -9,7 +9,7 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- pgdata:/var/lib/postgresql/data
|
- pgdata:/var/lib/postgresql/data
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:5432:5432"
|
- "127.0.0.1:${DB_HOST_PORT:-5432}:5432"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
@@ -34,7 +34,7 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- redisdata:/data
|
- redisdata:/data
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:6379:6379"
|
- "127.0.0.1:${REDIS_HOST_PORT:-6379}:6379"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep -q PONG"]
|
test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep -q PONG"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
@@ -57,7 +57,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
env_file: .env
|
env_file: .env
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8080:8080"
|
- "127.0.0.1:${API_HOST_PORT:-8080}:8080"
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""add counters
|
||||||
|
|
||||||
|
Revision ID: abd273076068
|
||||||
|
Revises: db06fd3126ff
|
||||||
|
Create Date: 2026-10-26 22:01:01.910396
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision: str = 'abd273076068'
|
||||||
|
down_revision: Union[str, None] = 'db06fd3126ff'
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('counters',
|
||||||
|
sa.Column('name', sa.String(length=64), nullable=False),
|
||||||
|
sa.Column('value', sa.BigInteger(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('name', name=op.f('pk_counters'))
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table('counters')
|
||||||
|
# ### end Alembic commands ###
|
||||||
+2
-1
@@ -46,4 +46,5 @@ argon2-cffi==25.1.0
|
|||||||
redis==8.1.0
|
redis==8.1.0
|
||||||
greenlet
|
greenlet
|
||||||
pydantic-settings
|
pydantic-settings
|
||||||
pytest-asyncio
|
pytest-asyncio==1.4.1
|
||||||
|
httpx==0.28.1
|
||||||
|
|||||||
+22
-2
@@ -2,5 +2,25 @@
|
|||||||
set -eu
|
set -eu
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
docker compose restart postgres
|
compose() {
|
||||||
docker compose restart api
|
docker compose --env-file .env "$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_healthy() {
|
||||||
|
for service in "$@"; do
|
||||||
|
attempts=0
|
||||||
|
until [ "$(compose ps --format '{{.Health}}' "$service")" = "healthy" ]; do
|
||||||
|
attempts=$((attempts + 1))
|
||||||
|
if [ "$attempts" -ge 60 ]; then
|
||||||
|
echo "$service не стал healthy за 60 секунд" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
compose restart postgres redis
|
||||||
|
wait_healthy postgres redis
|
||||||
|
compose restart api
|
||||||
|
wait_healthy api
|
||||||
|
|||||||
+60
-14
@@ -1,12 +1,11 @@
|
|||||||
"""Фикстуры для async-тестов с РЕАЛЬНОЙ PostgreSQL (SQLite не подходит).
|
"""Фикстуры async-тестов на реальных PostgreSQL и Redis.
|
||||||
|
|
||||||
Перед запуском: `make db-up` (postgres + база <DB_NAME>_test).
|
Перед запуском: `make test-stand-up` (тестовый стенд и база <DB_NAME>_test).
|
||||||
Переменные:
|
Переменные:
|
||||||
TEST_DATABASE_URL по умолчанию postgresql+asyncpg://messenger:messenger@localhost:5432/messenger_test
|
TEST_DATABASE_URL по умолчанию postgresql+asyncpg://messenger:messenger@localhost:5432/messenger_test
|
||||||
TEST_USE_MIGRATIONS=1 строить схему через `alembic upgrade head` вместо Base.metadata.create_all
|
TEST_USE_MIGRATIONS=1 строить схему через `alembic upgrade head` вместо Base.metadata.create_all
|
||||||
|
TEST_REDIS_HOST/PORT/PASSWORD/DB по умолчанию localhost:6379, база 15
|
||||||
Все тесты и async-фикстуры живут в ОДНОМ event loop (pytest.ini: loop_scope=session),
|
DOCKER_TESTS=1 включить тесты, которые перезапускают контейнеры compose
|
||||||
поэтому пул соединений, созданный в фикстуре, можно использовать в тестах.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
@@ -17,11 +16,16 @@ import httpx
|
|||||||
import pytest
|
import pytest
|
||||||
from alembic import command
|
from alembic import command
|
||||||
from alembic.config import Config
|
from alembic.config import Config
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from redis.asyncio import Redis
|
||||||
|
from redis.exceptions import RedisError
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||||
from sqlalchemy.pool import NullPool
|
from sqlalchemy.pool import NullPool
|
||||||
|
|
||||||
from app.core.config import Settings
|
from app.core.config import Settings
|
||||||
|
from app.core.redis import create_redis_client
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
from app.models import Base
|
from app.models import Base
|
||||||
|
|
||||||
@@ -34,6 +38,15 @@ def _database_url() -> str:
|
|||||||
return os.environ.get("TEST_DATABASE_URL", DEFAULT_TEST_DATABASE_URL)
|
return os.environ.get("TEST_DATABASE_URL", DEFAULT_TEST_DATABASE_URL)
|
||||||
|
|
||||||
|
|
||||||
|
def _redis_settings() -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"redis_host": os.environ.get("TEST_REDIS_HOST", "localhost"),
|
||||||
|
"redis_port": int(os.environ.get("TEST_REDIS_PORT", "6379")),
|
||||||
|
"redis_password": os.environ.get("TEST_REDIS_PASSWORD") or None,
|
||||||
|
"redis_db": int(os.environ.get("TEST_REDIS_DB", "15")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def _alembic_config(url: str) -> Config:
|
def _alembic_config(url: str) -> Config:
|
||||||
config = Config("alembic.ini")
|
config = Config("alembic.ini")
|
||||||
config.set_main_option("sqlalchemy.url", url.replace("%", "%%"))
|
config.set_main_option("sqlalchemy.url", url.replace("%", "%%"))
|
||||||
@@ -51,6 +64,12 @@ async def reset_schema(engine: AsyncEngine) -> None:
|
|||||||
await connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
await connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||||
|
|
||||||
|
|
||||||
|
async def close_app(app: FastAPI) -> None:
|
||||||
|
"""ASGITransport не запускает lifespan, поэтому ресурсы приложения закрываются явно."""
|
||||||
|
await app.state.redis.aclose()
|
||||||
|
await app.state.engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="session")
|
@pytest.fixture(scope="session")
|
||||||
def database_url() -> str:
|
def database_url() -> str:
|
||||||
return _database_url()
|
return _database_url()
|
||||||
@@ -62,10 +81,10 @@ async def db_engine(database_url: str) -> AsyncIterator[AsyncEngine]:
|
|||||||
try:
|
try:
|
||||||
async with engine.connect() as connection:
|
async with engine.connect() as connection:
|
||||||
await connection.execute(text("SELECT 1"))
|
await connection.execute(text("SELECT 1"))
|
||||||
except Exception as error: # noqa: BLE001
|
except (SQLAlchemyError, OSError) as error:
|
||||||
pytest.exit(
|
pytest.exit(
|
||||||
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
|
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
|
||||||
f"{type(error).__name__}. Выполните `make db-up`.",
|
f"{type(error).__name__}. Выполните `make test-stand-up`.",
|
||||||
returncode=2,
|
returncode=2,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -81,12 +100,33 @@ async def db_engine(database_url: str) -> AsyncIterator[AsyncEngine]:
|
|||||||
await engine.dispose()
|
await engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session")
|
||||||
|
async def redis_client() -> AsyncIterator[Redis]:
|
||||||
|
settings = build_settings(_database_url())
|
||||||
|
if settings.redis_db == 0:
|
||||||
|
pytest.exit("TEST_REDIS_DB=0 запрещён: тесты очищают базу Redis.", returncode=2)
|
||||||
|
|
||||||
|
client = create_redis_client(settings)
|
||||||
|
try:
|
||||||
|
await client.ping()
|
||||||
|
except (RedisError, OSError) as error:
|
||||||
|
pytest.exit(
|
||||||
|
f"Redis недоступен: {type(error).__name__}. Выполните `make test-stand-up`.",
|
||||||
|
returncode=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
yield client
|
||||||
|
await client.flushdb()
|
||||||
|
await client.aclose()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
async def clean_db(db_engine: AsyncEngine) -> None:
|
async def clean_db(db_engine: AsyncEngine, redis_client: Redis) -> None:
|
||||||
names = ", ".join(f'"{table.name}"' for table in Base.metadata.sorted_tables)
|
names = ", ".join(f'"{table.name}"' for table in Base.metadata.sorted_tables)
|
||||||
if names:
|
if names:
|
||||||
async with db_engine.begin() as connection:
|
async with db_engine.begin() as connection:
|
||||||
await connection.execute(text(f"TRUNCATE {names} RESTART IDENTITY CASCADE"))
|
await connection.execute(text(f"TRUNCATE {names} RESTART IDENTITY CASCADE"))
|
||||||
|
await redis_client.flushdb()
|
||||||
|
|
||||||
|
|
||||||
def build_settings(database_url: str, **overrides: object) -> Settings:
|
def build_settings(database_url: str, **overrides: object) -> Settings:
|
||||||
@@ -101,6 +141,7 @@ def build_settings(database_url: str, **overrides: object) -> Settings:
|
|||||||
"session_ttl_seconds": 300,
|
"session_ttl_seconds": 300,
|
||||||
"db_pool_size": 10,
|
"db_pool_size": 10,
|
||||||
"db_max_overflow": 10,
|
"db_max_overflow": 10,
|
||||||
|
**_redis_settings(),
|
||||||
}
|
}
|
||||||
values.update(overrides)
|
values.update(overrides)
|
||||||
return Settings(_env_file=None, **values) # type: ignore[arg-type]
|
return Settings(_env_file=None, **values) # type: ignore[arg-type]
|
||||||
@@ -114,15 +155,20 @@ def settings(database_url: str) -> Settings:
|
|||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def make_settings(database_url: str) -> Callable[..., Settings]:
|
def make_settings(database_url: str) -> Callable[..., Settings]:
|
||||||
def factory(**overrides: object) -> Settings:
|
def factory(**overrides: object) -> Settings:
|
||||||
return build_settings(database_url, **overrides)
|
url = str(overrides.pop("database_url", database_url))
|
||||||
|
return build_settings(url, **overrides)
|
||||||
|
|
||||||
return factory
|
return factory
|
||||||
|
|
||||||
|
|
||||||
def make_client(app, *, raise_app_exceptions: bool = True, timeout: float = 30) -> httpx.AsyncClient:
|
def make_client(
|
||||||
"""ASGITransport не запускает lifespan, поэтому engine закрывает вызывающий (см. fixtures)."""
|
app, *, raise_app_exceptions: bool = True, timeout: float = 30
|
||||||
|
) -> httpx.AsyncClient:
|
||||||
|
"""ASGITransport не запускает lifespan, поэтому ресурсы закрывает вызывающий (close_app)."""
|
||||||
return httpx.AsyncClient(
|
return httpx.AsyncClient(
|
||||||
transport=httpx.ASGITransport(app=app, raise_app_exceptions=raise_app_exceptions),
|
transport=httpx.ASGITransport(
|
||||||
|
app=app, raise_app_exceptions=raise_app_exceptions
|
||||||
|
),
|
||||||
base_url="http://testserver",
|
base_url="http://testserver",
|
||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
)
|
)
|
||||||
@@ -143,11 +189,11 @@ def app(settings: Settings):
|
|||||||
async def client(app) -> AsyncIterator[httpx.AsyncClient]:
|
async def client(app) -> AsyncIterator[httpx.AsyncClient]:
|
||||||
async with make_client(app) as test_client:
|
async with make_client(app) as test_client:
|
||||||
yield test_client
|
yield test_client
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
async def client_no_raise(app) -> AsyncIterator[httpx.AsyncClient]:
|
async def client_no_raise(app) -> AsyncIterator[httpx.AsyncClient]:
|
||||||
async with make_client(app, raise_app_exceptions=False) as test_client:
|
async with make_client(app, raise_app_exceptions=False) as test_client:
|
||||||
yield test_client
|
yield test_client
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ from uuid import uuid4
|
|||||||
|
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
|
||||||
PASSWORD = "Correct-horse-battery-1" # синтетический пароль, только для тестов
|
PASSWORD = "Correct-horse-battery-1"
|
||||||
|
|
||||||
|
|
||||||
def basic_header(username: str, password: str) -> dict[str, str]:
|
def basic_header(username: str, password: str) -> dict[str, str]:
|
||||||
|
|||||||
+106
-20
@@ -1,10 +1,11 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
import hashlib
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
from tests.conftest import make_client
|
from tests.conftest import close_app, make_client
|
||||||
from tests.helpers import (
|
from tests.helpers import (
|
||||||
PASSWORD,
|
PASSWORD,
|
||||||
assert_request_id,
|
assert_request_id,
|
||||||
@@ -28,11 +29,11 @@ async def test_login_returns_opaque_bearer_session(client: AsyncClient):
|
|||||||
body = response.json()
|
body = response.json()
|
||||||
assert set(body) == {"token", "token_type", "expires_at", "user"}
|
assert set(body) == {"token", "token_type", "expires_at", "user"}
|
||||||
assert body["token_type"] == "Bearer"
|
assert body["token_type"] == "Bearer"
|
||||||
assert len(body["token"]) >= 43 # 256 бит в base64url
|
assert len(body["token"]) >= 43
|
||||||
assert body["token"] not in (user["id"], user["username"])
|
assert body["token"] not in (user["id"], user["username"])
|
||||||
assert body["user"]["id"] == user["id"]
|
assert body["user"]["id"] == user["id"]
|
||||||
assert body["expires_at"].endswith("Z")
|
assert body["expires_at"].endswith("Z")
|
||||||
assert datetime.fromisoformat(body["expires_at"].replace("Z", "+00:00"))
|
assert datetime.fromisoformat(body["expires_at"])
|
||||||
assert_request_id(response)
|
assert_request_id(response)
|
||||||
|
|
||||||
|
|
||||||
@@ -71,9 +72,14 @@ async def test_wrong_password_and_unknown_user_look_identical(client: AsyncClien
|
|||||||
for response in (wrong_password, unknown_user):
|
for response in (wrong_password, unknown_user):
|
||||||
assert response.status_code == 401
|
assert response.status_code == 401
|
||||||
assert response.json()["error"]["code"] == "unauthorized"
|
assert response.json()["error"]["code"] == "unauthorized"
|
||||||
assert response.headers["WWW-Authenticate"].startswith('Basic realm="messenger"')
|
assert response.headers["WWW-Authenticate"].startswith(
|
||||||
|
'Basic realm="messenger"'
|
||||||
|
)
|
||||||
assert_request_id(response)
|
assert_request_id(response)
|
||||||
assert wrong_password.json()["error"]["message"] == unknown_user.json()["error"]["message"]
|
assert (
|
||||||
|
wrong_password.json()["error"]["message"]
|
||||||
|
== unknown_user.json()["error"]["message"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def test_login_requires_basic_scheme(client: AsyncClient):
|
async def test_login_requires_basic_scheme(client: AsyncClient):
|
||||||
@@ -99,7 +105,9 @@ async def test_business_endpoints_require_bearer(client: AsyncClient):
|
|||||||
response = await client.get("/api/v1/users/me", headers=headers)
|
response = await client.get("/api/v1/users/me", headers=headers)
|
||||||
assert response.status_code == 401, headers
|
assert response.status_code == 401, headers
|
||||||
assert response.json()["error"]["code"] == "unauthorized"
|
assert response.json()["error"]["code"] == "unauthorized"
|
||||||
assert response.headers["WWW-Authenticate"].startswith('Bearer realm="messenger"')
|
assert response.headers["WWW-Authenticate"].startswith(
|
||||||
|
'Bearer realm="messenger"'
|
||||||
|
)
|
||||||
assert_request_id(response)
|
assert_request_id(response)
|
||||||
|
|
||||||
|
|
||||||
@@ -121,17 +129,27 @@ async def test_logout_revokes_only_current_session(client: AsyncClient):
|
|||||||
first = await login(client, user)
|
first = await login(client, user)
|
||||||
second = await login(client, user)
|
second = await login(client, user)
|
||||||
|
|
||||||
assert (await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))).status_code == 204
|
assert (
|
||||||
|
await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))
|
||||||
|
).status_code == 204
|
||||||
|
|
||||||
assert (await client.get("/api/v1/users/me", headers=bearer(first))).status_code == 401
|
assert (
|
||||||
assert (await client.get("/api/v1/users/me", headers=bearer(second))).status_code == 200
|
await client.get("/api/v1/users/me", headers=bearer(first))
|
||||||
|
).status_code == 401
|
||||||
|
assert (
|
||||||
|
await client.get("/api/v1/users/me", headers=bearer(second))
|
||||||
|
).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
async def test_logout_twice_returns_401(client: AsyncClient):
|
async def test_logout_twice_returns_401(client: AsyncClient):
|
||||||
session = await create_user(client)
|
session = await create_user(client)
|
||||||
|
|
||||||
first = await client.delete("/api/v1/auth/sessions/current", headers=bearer(session))
|
first = await client.delete(
|
||||||
again = await client.delete("/api/v1/auth/sessions/current", headers=bearer(session))
|
"/api/v1/auth/sessions/current", headers=bearer(session)
|
||||||
|
)
|
||||||
|
again = await client.delete(
|
||||||
|
"/api/v1/auth/sessions/current", headers=bearer(session)
|
||||||
|
)
|
||||||
|
|
||||||
assert first.status_code == 204
|
assert first.status_code == 204
|
||||||
assert first.content == b""
|
assert first.content == b""
|
||||||
@@ -142,26 +160,27 @@ async def test_session_expires_after_ttl(make_settings):
|
|||||||
app = create_app(make_settings(session_ttl_seconds=2))
|
app = create_app(make_settings(session_ttl_seconds=2))
|
||||||
async with make_client(app) as client:
|
async with make_client(app) as client:
|
||||||
session = await create_user(client)
|
session = await create_user(client)
|
||||||
assert (await client.get("/api/v1/users/me", headers=bearer(session))).status_code == 200
|
assert (
|
||||||
|
await client.get("/api/v1/users/me", headers=bearer(session))
|
||||||
|
).status_code == 200
|
||||||
|
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
|
|
||||||
response = await client.get("/api/v1/users/me", headers=bearer(session))
|
response = await client.get("/api/v1/users/me", headers=bearer(session))
|
||||||
assert response.status_code == 401
|
assert response.status_code == 401
|
||||||
assert response.headers["WWW-Authenticate"].startswith("Bearer")
|
assert response.headers["WWW-Authenticate"].startswith("Bearer")
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|
||||||
|
|
||||||
async def test_token_is_not_stored_in_plaintext(client: AsyncClient, db_engine):
|
async def test_token_is_stored_only_as_sha256_key(client: AsyncClient, redis_client):
|
||||||
from sqlalchemy import text
|
|
||||||
|
|
||||||
session = await create_user(client)
|
session = await create_user(client)
|
||||||
|
|
||||||
async with db_engine.connect() as connection:
|
keys = [key async for key in redis_client.scan_iter("session:*")]
|
||||||
result = await connection.execute(text("SELECT token_hash FROM sessions"))
|
token_hash = hashlib.sha256(session["token"].encode()).hexdigest()
|
||||||
stored = result.scalars().all()
|
|
||||||
|
|
||||||
assert stored and session["token"] not in stored
|
assert keys == [f"session:{token_hash}"]
|
||||||
|
assert await redis_client.get(keys[0]) == session["id"]
|
||||||
|
assert all(session["token"] not in key for key in keys)
|
||||||
|
|
||||||
|
|
||||||
async def test_password_is_not_stored_in_plaintext(client: AsyncClient, db_engine):
|
async def test_password_is_not_stored_in_plaintext(client: AsyncClient, db_engine):
|
||||||
@@ -177,3 +196,70 @@ async def test_password_is_not_stored_in_plaintext(client: AsyncClient, db_engin
|
|||||||
|
|
||||||
assert PASSWORD not in stored
|
assert PASSWORD not in stored
|
||||||
assert stored.startswith("$argon2id$")
|
assert stored.startswith("$argon2id$")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_login_rejects_out_of_range_password_like_wrong_password(
|
||||||
|
client: AsyncClient,
|
||||||
|
):
|
||||||
|
user = await register(client)
|
||||||
|
reference = await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(user["username"], "wrong-password-123"),
|
||||||
|
)
|
||||||
|
|
||||||
|
for password in ("x" * 11, "x" * 129, ""):
|
||||||
|
response = await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(user["username"], password),
|
||||||
|
)
|
||||||
|
assert response.status_code == 401
|
||||||
|
assert (
|
||||||
|
response.json()["error"]["message"] == reference.json()["error"]["message"]
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
response.headers["WWW-Authenticate"]
|
||||||
|
== reference.headers["WWW-Authenticate"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_malformed_basic_credentials_return_401(client: AsyncClient):
|
||||||
|
import base64
|
||||||
|
|
||||||
|
def raw(value: bytes) -> dict[str, str]:
|
||||||
|
return {"Authorization": "Basic " + base64.b64encode(value).decode()}
|
||||||
|
|
||||||
|
for headers in (
|
||||||
|
raw(b"no-colon-here"),
|
||||||
|
raw(b":password-without-user"),
|
||||||
|
raw(b"\xff\xfe:invalid-utf8"),
|
||||||
|
{"Authorization": "Basic"},
|
||||||
|
{"Authorization": "Digest abc"},
|
||||||
|
):
|
||||||
|
response = await client.post("/api/v1/auth/sessions", headers=headers)
|
||||||
|
assert response.status_code == 401, headers
|
||||||
|
assert response.headers["WWW-Authenticate"].startswith("Basic")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_unknown_user_takes_comparable_time_to_wrong_password(
|
||||||
|
client: AsyncClient,
|
||||||
|
):
|
||||||
|
import statistics
|
||||||
|
import time
|
||||||
|
|
||||||
|
user = await register(client)
|
||||||
|
|
||||||
|
async def measure(username: str) -> float:
|
||||||
|
samples = []
|
||||||
|
for _ in range(5):
|
||||||
|
started = time.perf_counter()
|
||||||
|
await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(username, "wrong-password-123"),
|
||||||
|
)
|
||||||
|
samples.append(time.perf_counter() - started)
|
||||||
|
return statistics.median(samples)
|
||||||
|
|
||||||
|
wrong_password = await measure(user["username"])
|
||||||
|
unknown_user = await measure("no_such_user")
|
||||||
|
|
||||||
|
assert unknown_user > wrong_password * 0.5
|
||||||
|
|||||||
+21
-11
@@ -142,7 +142,9 @@ async def test_nonexistent_chat_returns_404(client: AsyncClient):
|
|||||||
assert_request_id(response)
|
assert_request_id(response)
|
||||||
|
|
||||||
|
|
||||||
async def test_failed_chat_creation_leaves_no_partial_data(client: AsyncClient, db_engine):
|
async def test_failed_chat_creation_leaves_no_partial_data(
|
||||||
|
client: AsyncClient, db_engine
|
||||||
|
):
|
||||||
"""Атомарность: неизвестный участник -> нет ни чата, ни записей членства."""
|
"""Атомарность: неизвестный участник -> нет ни чата, ни записей членства."""
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
|
||||||
@@ -155,7 +157,9 @@ async def test_failed_chat_creation_leaves_no_partial_data(client: AsyncClient,
|
|||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
|
|
||||||
async with db_engine.connect() as connection:
|
async with db_engine.connect() as connection:
|
||||||
chats = (await connection.execute(text("SELECT count(*) FROM chats"))).scalar_one()
|
chats = (
|
||||||
|
await connection.execute(text("SELECT count(*) FROM chats"))
|
||||||
|
).scalar_one()
|
||||||
members = (
|
members = (
|
||||||
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
||||||
).scalar_one()
|
).scalar_one()
|
||||||
@@ -167,14 +171,18 @@ async def test_chat_list_pagination_and_order(client: AsyncClient):
|
|||||||
chats = [await create_chat(client, alice, title=f"chat-{i}") for i in range(5)]
|
chats = [await create_chat(client, alice, title=f"chat-{i}") for i in range(5)]
|
||||||
|
|
||||||
page1 = (await client.get("/api/v1/chats?limit=2", headers=bearer(alice))).json()
|
page1 = (await client.get("/api/v1/chats?limit=2", headers=bearer(alice))).json()
|
||||||
page2 = (await client.get(
|
page2 = (
|
||||||
f"/api/v1/chats?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
await client.get(
|
||||||
headers=bearer(alice),
|
f"/api/v1/chats?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
||||||
)).json()
|
headers=bearer(alice),
|
||||||
page3 = (await client.get(
|
)
|
||||||
f"/api/v1/chats?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
).json()
|
||||||
headers=bearer(alice),
|
page3 = (
|
||||||
)).json()
|
await client.get(
|
||||||
|
f"/api/v1/chats?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
||||||
|
headers=bearer(alice),
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
|
||||||
ids = [c["id"] for page in (page1, page2, page3) for c in page["items"]]
|
ids = [c["id"] for page in (page1, page2, page3) for c in page["items"]]
|
||||||
assert ids == [c["id"] for c in chats]
|
assert ids == [c["id"] for c in chats]
|
||||||
@@ -183,4 +191,6 @@ async def test_chat_list_pagination_and_order(client: AsyncClient):
|
|||||||
|
|
||||||
async def test_chat_endpoints_require_bearer(client: AsyncClient):
|
async def test_chat_endpoints_require_bearer(client: AsyncClient):
|
||||||
assert (await client.get("/api/v1/chats")).status_code == 401
|
assert (await client.get("/api/v1/chats")).status_code == 401
|
||||||
assert (await client.post("/api/v1/chats", json={"title": "x", "member_ids": []})).status_code in (401, 400)
|
assert (
|
||||||
|
await client.post("/api/v1/chats", json={"title": "x", "member_ids": []})
|
||||||
|
).status_code in (401, 400)
|
||||||
|
|||||||
+161
-9
@@ -7,12 +7,16 @@ from uuid import uuid4
|
|||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
from tests.conftest import make_client
|
from tests.conftest import close_app, make_client
|
||||||
from tests.helpers import PASSWORD, bearer, create_user
|
from tests.helpers import PASSWORD, basic_header, bearer, create_user, register
|
||||||
|
|
||||||
|
|
||||||
async def test_parallel_registration_of_same_username_creates_exactly_one_user(make_settings):
|
async def test_parallel_registration_of_same_username_creates_exactly_one_user(
|
||||||
app = create_app(make_settings(max_in_flight=64, db_pool_size=20, db_max_overflow=20))
|
make_settings,
|
||||||
|
):
|
||||||
|
app = create_app(
|
||||||
|
make_settings(max_in_flight=64, db_pool_size=20, db_max_overflow=20)
|
||||||
|
)
|
||||||
|
|
||||||
async with make_client(app) as client:
|
async with make_client(app) as client:
|
||||||
responses = await asyncio.gather(
|
responses = await asyncio.gather(
|
||||||
@@ -28,7 +32,7 @@ async def test_parallel_registration_of_same_username_creates_exactly_one_user(m
|
|||||||
for _ in range(16)
|
for _ in range(16)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|
||||||
statuses = Counter(response.status_code for response in responses)
|
statuses = Counter(response.status_code for response in responses)
|
||||||
assert statuses == Counter({201: 1, 409: 15}), statuses
|
assert statuses == Counter({201: 1, 409: 15}), statuses
|
||||||
@@ -84,11 +88,13 @@ async def test_100_messages_from_10_clients(make_settings):
|
|||||||
items = history.json()["items"]
|
items = history.json()["items"]
|
||||||
assert len(items) == 100
|
assert len(items) == 100
|
||||||
assert len({m["id"] for m in items}) == 100
|
assert len({m["id"] for m in items}) == 100
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|
||||||
|
|
||||||
async def test_chat_creation_in_parallel_is_atomic(make_settings, db_engine):
|
async def test_chat_creation_in_parallel_is_atomic(make_settings, db_engine):
|
||||||
app = create_app(make_settings(max_in_flight=32, db_pool_size=20, db_max_overflow=20))
|
app = create_app(
|
||||||
|
make_settings(max_in_flight=32, db_pool_size=20, db_max_overflow=20)
|
||||||
|
)
|
||||||
|
|
||||||
async with make_client(app) as client:
|
async with make_client(app) as client:
|
||||||
alice = await create_user(client)
|
alice = await create_user(client)
|
||||||
@@ -104,11 +110,157 @@ async def test_chat_creation_in_parallel_is_atomic(make_settings, db_engine):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
assert all(r.status_code == 201 for r in responses)
|
assert all(r.status_code == 201 for r in responses)
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|
||||||
async with db_engine.connect() as connection:
|
async with db_engine.connect() as connection:
|
||||||
chats = (await connection.execute(text("SELECT count(*) FROM chats"))).scalar_one()
|
chats = (
|
||||||
|
await connection.execute(text("SELECT count(*) FROM chats"))
|
||||||
|
).scalar_one()
|
||||||
members = (
|
members = (
|
||||||
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
||||||
).scalar_one()
|
).scalar_one()
|
||||||
assert chats == 10 and members == 20
|
assert chats == 10 and members == 20
|
||||||
|
|
||||||
|
|
||||||
|
async def test_parallel_registration_of_distinct_usernames_all_succeed(make_settings):
|
||||||
|
app = create_app(make_settings(max_in_flight=64))
|
||||||
|
async with make_client(app) as client:
|
||||||
|
responses = await asyncio.gather(
|
||||||
|
*(
|
||||||
|
client.post(
|
||||||
|
"/api/v1/users",
|
||||||
|
json={
|
||||||
|
"username": f"distinct_{i}",
|
||||||
|
"display_name": "D",
|
||||||
|
"password": PASSWORD,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for i in range(12)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
assert [r.status_code for r in responses] == [201] * 12
|
||||||
|
assert len({r.json()["id"] for r in responses}) == 12
|
||||||
|
|
||||||
|
|
||||||
|
async def test_parallel_logins_issue_distinct_valid_tokens(make_settings):
|
||||||
|
app = create_app(make_settings(max_in_flight=64))
|
||||||
|
async with make_client(app) as client:
|
||||||
|
user = await register(client)
|
||||||
|
responses = await asyncio.gather(
|
||||||
|
*(
|
||||||
|
client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(user["username"], user["password"]),
|
||||||
|
)
|
||||||
|
for _ in range(10)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
tokens = [r.json()["token"] for r in responses]
|
||||||
|
checks = await asyncio.gather(
|
||||||
|
*(
|
||||||
|
client.get(
|
||||||
|
"/api/v1/users/me", headers={"Authorization": f"Bearer {token}"}
|
||||||
|
)
|
||||||
|
for token in tokens
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
assert all(r.status_code == 201 for r in responses)
|
||||||
|
assert len(set(tokens)) == 10
|
||||||
|
assert all(r.status_code == 200 for r in checks)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_parallel_logout_of_same_token_succeeds_once(make_settings):
|
||||||
|
app = create_app(make_settings(max_in_flight=64))
|
||||||
|
async with make_client(app) as client:
|
||||||
|
session = await create_user(client)
|
||||||
|
responses = await asyncio.gather(
|
||||||
|
*(
|
||||||
|
client.delete("/api/v1/auth/sessions/current", headers=bearer(session))
|
||||||
|
for _ in range(10)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
assert Counter(r.status_code for r in responses) == Counter({204: 1, 401: 9})
|
||||||
|
|
||||||
|
|
||||||
|
async def test_message_limit_is_exact_under_concurrency(make_settings, db_engine):
|
||||||
|
app = create_app(
|
||||||
|
make_settings(
|
||||||
|
max_messages=5, max_in_flight=64, db_pool_size=20, db_max_overflow=20
|
||||||
|
)
|
||||||
|
)
|
||||||
|
async with make_client(app) as client:
|
||||||
|
user = await create_user(client)
|
||||||
|
chat = (
|
||||||
|
await client.post(
|
||||||
|
"/api/v1/chats",
|
||||||
|
headers=bearer(user),
|
||||||
|
json={"title": "limit", "member_ids": [user["id"]]},
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
responses = await asyncio.gather(
|
||||||
|
*(
|
||||||
|
client.post(
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages",
|
||||||
|
headers=bearer(user),
|
||||||
|
json={"text": f"m{i}"},
|
||||||
|
)
|
||||||
|
for i in range(20)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
assert Counter(r.status_code for r in responses) == Counter({201: 5, 503: 15})
|
||||||
|
async with db_engine.connect() as connection:
|
||||||
|
stored = (
|
||||||
|
await connection.execute(text("SELECT count(*) FROM messages"))
|
||||||
|
).scalar_one()
|
||||||
|
counter = (
|
||||||
|
await connection.execute(
|
||||||
|
text("SELECT value FROM counters WHERE name = 'messages'")
|
||||||
|
)
|
||||||
|
).scalar_one()
|
||||||
|
assert stored == counter == 5
|
||||||
|
|
||||||
|
|
||||||
|
async def test_failed_chat_insert_rolls_back_whole_transaction(
|
||||||
|
make_settings, db_engine, monkeypatch
|
||||||
|
):
|
||||||
|
import app.domain.chats as chats_domain
|
||||||
|
|
||||||
|
async def accept_everyone(_session, user_ids):
|
||||||
|
return set(user_ids)
|
||||||
|
|
||||||
|
app = create_app(make_settings())
|
||||||
|
async with make_client(app) as client:
|
||||||
|
alice = await create_user(client)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
chats_domain.users_storage, "get_existing_user_ids", accept_everyone
|
||||||
|
)
|
||||||
|
response = await client.post(
|
||||||
|
"/api/v1/chats",
|
||||||
|
headers=bearer(alice),
|
||||||
|
json={"title": "broken", "member_ids": [alice["id"], str(uuid4())]},
|
||||||
|
)
|
||||||
|
monkeypatch.undo()
|
||||||
|
after = await client.post(
|
||||||
|
"/api/v1/chats",
|
||||||
|
headers=bearer(alice),
|
||||||
|
json={"title": "ok", "member_ids": [alice["id"]]},
|
||||||
|
)
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert after.status_code == 201
|
||||||
|
async with db_engine.connect() as connection:
|
||||||
|
titles = (await connection.execute(text("SELECT title FROM chats"))).scalars()
|
||||||
|
members = (
|
||||||
|
await connection.execute(text("SELECT count(*) FROM chat_members"))
|
||||||
|
).scalar_one()
|
||||||
|
assert list(titles) == ["ok"]
|
||||||
|
assert members == 1
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import logging
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
|
||||||
@@ -52,7 +52,9 @@ async def test_method_not_allowed_preserves_405(client: AsyncClient):
|
|||||||
assert_request_id(response)
|
assert_request_id(response)
|
||||||
|
|
||||||
|
|
||||||
async def test_unhandled_exception_is_hidden_from_client(client_no_raise: AsyncClient, caplog):
|
async def test_unhandled_exception_is_hidden_from_client(
|
||||||
|
client_no_raise: AsyncClient, caplog
|
||||||
|
):
|
||||||
with caplog.at_level(logging.ERROR, logger="app.errors.handlers"):
|
with caplog.at_level(logging.ERROR, logger="app.errors.handlers"):
|
||||||
response = await client_no_raise.get("/__test__/explode")
|
response = await client_no_raise.get("/__test__/explode")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
"""Недоступность Redis и PostgreSQL: ограниченный 503, без анонимного доступа."""
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from app.main import create_app
|
||||||
|
from tests.conftest import close_app, make_client
|
||||||
|
from tests.helpers import PASSWORD, assert_request_id, basic_header, bearer, create_user
|
||||||
|
|
||||||
|
ME = "/api/v1/users/me"
|
||||||
|
DEAD_DATABASE_URL = "postgresql+asyncpg://nobody:secretpass@127.0.0.1:1/none"
|
||||||
|
|
||||||
|
|
||||||
|
def assert_unavailable(response) -> None:
|
||||||
|
assert response.status_code == 503, response.text
|
||||||
|
assert response.json()["error"]["code"] == "unavailable"
|
||||||
|
assert "secretpass" not in response.text
|
||||||
|
assert "Traceback" not in response.text
|
||||||
|
assert_request_id(response)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_redis_down_gives_503_for_login_and_protected_endpoints(make_settings):
|
||||||
|
alive = create_app(make_settings())
|
||||||
|
async with make_client(alive) as client:
|
||||||
|
session = await create_user(client)
|
||||||
|
await close_app(alive)
|
||||||
|
|
||||||
|
app = create_app(make_settings(redis_port=1, redis_connect_timeout_seconds=0.5))
|
||||||
|
async with make_client(app, raise_app_exceptions=False) as client:
|
||||||
|
started = time.perf_counter()
|
||||||
|
protected = await client.get(ME, headers=bearer(session))
|
||||||
|
elapsed = time.perf_counter() - started
|
||||||
|
|
||||||
|
login = await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(session["username"], session["password"]),
|
||||||
|
)
|
||||||
|
logout = await client.delete(
|
||||||
|
"/api/v1/auth/sessions/current", headers=bearer(session)
|
||||||
|
)
|
||||||
|
ready = await client.get("/health/ready")
|
||||||
|
live = await client.get("/health/live")
|
||||||
|
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
for response in (protected, login, logout, ready):
|
||||||
|
assert_unavailable(response)
|
||||||
|
assert live.status_code == 200
|
||||||
|
assert elapsed < 3
|
||||||
|
|
||||||
|
|
||||||
|
async def test_redis_down_keeps_registration_working(make_settings):
|
||||||
|
app = create_app(make_settings(redis_port=1, redis_connect_timeout_seconds=0.5))
|
||||||
|
async with make_client(app, raise_app_exceptions=False) as client:
|
||||||
|
response = await client.post(
|
||||||
|
"/api/v1/users",
|
||||||
|
json={"username": "no_redis", "display_name": "N", "password": PASSWORD},
|
||||||
|
)
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
assert response.status_code == 201
|
||||||
|
|
||||||
|
|
||||||
|
async def test_database_down_with_valid_session_gives_503(make_settings):
|
||||||
|
alive = create_app(make_settings())
|
||||||
|
async with make_client(alive) as client:
|
||||||
|
session = await create_user(client)
|
||||||
|
await close_app(alive)
|
||||||
|
|
||||||
|
app = create_app(
|
||||||
|
make_settings(database_url=DEAD_DATABASE_URL, db_connect_timeout_seconds=1)
|
||||||
|
)
|
||||||
|
async with make_client(app, raise_app_exceptions=False) as client:
|
||||||
|
protected = await client.get(ME, headers=bearer(session))
|
||||||
|
chats = await client.get("/api/v1/chats", headers=bearer(session))
|
||||||
|
login = await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(session["username"], session["password"]),
|
||||||
|
)
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
for response in (protected, chats, login):
|
||||||
|
assert_unavailable(response)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_dependency_failure_never_authenticates_anonymous_requests(make_settings):
|
||||||
|
app = create_app(make_settings(redis_port=1, redis_connect_timeout_seconds=0.5))
|
||||||
|
async with make_client(app, raise_app_exceptions=False) as client:
|
||||||
|
no_token = await client.get(ME)
|
||||||
|
garbage = await client.get(ME, headers={"Authorization": "Bearer garbage"})
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
assert no_token.status_code == 401
|
||||||
|
assert_unavailable(garbage)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
from tests.conftest import make_client
|
from tests.conftest import close_app, make_client
|
||||||
from tests.helpers import assert_request_id
|
from tests.helpers import assert_request_id
|
||||||
|
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ async def test_readiness_is_503_when_database_is_down(make_settings):
|
|||||||
assert ready.status_code == 503
|
assert ready.status_code == 503
|
||||||
assert ready.json()["error"]["code"] == "unavailable"
|
assert ready.json()["error"]["code"] == "unavailable"
|
||||||
assert_request_id(ready)
|
assert_request_id(ready)
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|
||||||
|
|
||||||
async def test_business_request_is_503_when_database_is_down(make_settings):
|
async def test_business_request_is_503_when_database_is_down(make_settings):
|
||||||
@@ -54,7 +54,7 @@ async def test_business_request_is_503_when_database_is_down(make_settings):
|
|||||||
"password": "Correct-horse-battery-1",
|
"password": "Correct-horse-battery-1",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|
||||||
assert response.status_code == 503
|
assert response.status_code == 503
|
||||||
assert response.json()["error"]["code"] == "unavailable"
|
assert response.json()["error"]["code"] == "unavailable"
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""План запроса истории на >= 10 000 сообщений: индекс без Sort и полного скана."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||||
|
|
||||||
|
from tests.helpers import bearer, create_chat, create_user
|
||||||
|
|
||||||
|
HISTORY_QUERY = """
|
||||||
|
SELECT * FROM messages
|
||||||
|
WHERE chat_id = :chat_id AND (created_at, id) > (:after_created_at, :after_id)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT 51
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def walk(node: dict) -> list[dict]:
|
||||||
|
nodes = [node]
|
||||||
|
for child in node.get("Plans", []):
|
||||||
|
nodes.extend(walk(child))
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
|
||||||
|
async def seed_messages(
|
||||||
|
engine: AsyncEngine, chat_id: str, sender_id: str, count: int
|
||||||
|
) -> None:
|
||||||
|
async with engine.begin() as connection:
|
||||||
|
await connection.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT gen_random_uuid(), :chat_id, :sender_id, 'message ' || g,
|
||||||
|
now() - make_interval(secs => :count - g)
|
||||||
|
FROM generate_series(1, :count) AS g
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{"chat_id": chat_id, "sender_id": sender_id, "count": count},
|
||||||
|
)
|
||||||
|
await connection.execute(text("ANALYZE messages"))
|
||||||
|
|
||||||
|
|
||||||
|
async def test_history_page_uses_composite_index(client, db_engine: AsyncEngine):
|
||||||
|
alice = await create_user(client)
|
||||||
|
target = await create_chat(client, alice, title="target")
|
||||||
|
noise = await create_chat(client, alice, title="noise")
|
||||||
|
await seed_messages(db_engine, target["id"], alice["id"], 10_000)
|
||||||
|
await seed_messages(db_engine, noise["id"], alice["id"], 10_000)
|
||||||
|
|
||||||
|
middle = (
|
||||||
|
await client.get(
|
||||||
|
f"/api/v1/chats/{target['id']}/messages?limit=100", headers=bearer(alice)
|
||||||
|
)
|
||||||
|
).json()["items"][-1]
|
||||||
|
|
||||||
|
async with db_engine.connect() as connection:
|
||||||
|
raw_plan = (
|
||||||
|
await connection.execute(
|
||||||
|
text(f"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {HISTORY_QUERY}"),
|
||||||
|
{
|
||||||
|
"chat_id": UUID(target["id"]),
|
||||||
|
"after_created_at": datetime.fromisoformat(middle["created_at"]),
|
||||||
|
"after_id": UUID(middle["id"]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
).scalar_one()
|
||||||
|
|
||||||
|
plan = (raw_plan if isinstance(raw_plan, list) else json.loads(raw_plan))[0]["Plan"]
|
||||||
|
nodes = walk(plan)
|
||||||
|
node_types = {node["Node Type"] for node in nodes}
|
||||||
|
index_names = {node.get("Index Name") for node in nodes}
|
||||||
|
|
||||||
|
assert "ix_messages_chat_id_created_at_id" in index_names
|
||||||
|
assert "Sort" not in node_types
|
||||||
|
assert "Seq Scan" not in node_types
|
||||||
|
assert all(node.get("Actual Rows", 0) <= 51 for node in nodes)
|
||||||
+17
-8
@@ -1,11 +1,11 @@
|
|||||||
"""Остаток трека «управляемая деградация»: MAX_IN_FLIGHT -> 429, MAX_MESSAGES -> 503."""
|
"""Ограничения нагрузки: MAX_IN_FLIGHT -> 429, MAX_MESSAGES -> 503."""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from app.main import create_app
|
from app.main import create_app
|
||||||
from tests.conftest import make_client
|
from tests.conftest import close_app, make_client
|
||||||
from tests.helpers import assert_request_id, bearer, create_chat, create_user
|
from tests.helpers import assert_request_id, bearer, create_chat, create_user
|
||||||
|
|
||||||
|
|
||||||
@@ -24,16 +24,23 @@ async def test_message_limit_rejects_without_deleting_confirmed_messages(make_se
|
|||||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||||
|
|
||||||
for index in range(2):
|
for index in range(2):
|
||||||
ok = await client.post(url, headers=bearer(user), json={"text": f"confirmed-{index}"})
|
ok = await client.post(
|
||||||
|
url, headers=bearer(user), json={"text": f"confirmed-{index}"}
|
||||||
|
)
|
||||||
assert ok.status_code == 201
|
assert ok.status_code == 201
|
||||||
|
|
||||||
rejected = await client.post(url, headers=bearer(user), json={"text": "rejected"})
|
rejected = await client.post(
|
||||||
|
url, headers=bearer(user), json={"text": "rejected"}
|
||||||
|
)
|
||||||
_assert_error(rejected, 503, "unavailable")
|
_assert_error(rejected, 503, "unavailable")
|
||||||
|
|
||||||
history = await client.get(f"{url}?limit=100", headers=bearer(user))
|
history = await client.get(f"{url}?limit=100", headers=bearer(user))
|
||||||
assert history.status_code == 200
|
assert history.status_code == 200
|
||||||
assert [m["text"] for m in history.json()["items"]] == ["confirmed-0", "confirmed-1"]
|
assert [m["text"] for m in history.json()["items"]] == [
|
||||||
await app.state.engine.dispose()
|
"confirmed-0",
|
||||||
|
"confirmed-1",
|
||||||
|
]
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
|
||||||
async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypatch):
|
async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypatch):
|
||||||
@@ -62,7 +69,9 @@ async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypat
|
|||||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||||
|
|
||||||
held = [
|
held = [
|
||||||
asyncio.create_task(client.post(url, headers=bearer(user), json={"text": f"held-{i}"}))
|
asyncio.create_task(
|
||||||
|
client.post(url, headers=bearer(user), json={"text": f"held-{i}"})
|
||||||
|
)
|
||||||
for i in range(2)
|
for i in range(2)
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -86,4 +95,4 @@ async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypat
|
|||||||
recovered = await client.post(url, headers=bearer(user), json={"text": "after"})
|
recovered = await client.post(url, headers=bearer(user), json={"text": "after"})
|
||||||
assert recovered.status_code == 201
|
assert recovered.status_code == 201
|
||||||
assert_request_id(recovered)
|
assert_request_id(recovered)
|
||||||
await app.state.engine.dispose()
|
await close_app(app)
|
||||||
|
|||||||
+32
-21
@@ -87,21 +87,28 @@ async def test_pagination_has_no_duplicates(client: AsyncClient):
|
|||||||
chat = await create_chat(client, alice)
|
chat = await create_chat(client, alice)
|
||||||
|
|
||||||
created = [
|
created = [
|
||||||
(await _message(client, alice, chat, f"message-{index}")).json() for index in range(5)
|
(await _message(client, alice, chat, f"message-{index}")).json()
|
||||||
|
for index in range(5)
|
||||||
]
|
]
|
||||||
|
|
||||||
page1 = (await client.get(
|
page1 = (
|
||||||
f"/api/v1/chats/{chat['id']}/messages?limit=2",
|
await client.get(
|
||||||
headers=bearer(alice),
|
f"/api/v1/chats/{chat['id']}/messages?limit=2",
|
||||||
)).json()
|
headers=bearer(alice),
|
||||||
page2 = (await client.get(
|
)
|
||||||
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
).json()
|
||||||
headers=bearer(alice),
|
page2 = (
|
||||||
)).json()
|
await client.get(
|
||||||
page3 = (await client.get(
|
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page1['next_cursor'], safe='')}",
|
||||||
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
headers=bearer(alice),
|
||||||
headers=bearer(alice),
|
)
|
||||||
)).json()
|
).json()
|
||||||
|
page3 = (
|
||||||
|
await client.get(
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages?limit=2&cursor={quote(page2['next_cursor'], safe='')}",
|
||||||
|
headers=bearer(alice),
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
|
||||||
ids = [item["id"] for page in (page1, page2, page3) for item in page["items"]]
|
ids = [item["id"] for page in (page1, page2, page3) for item in page["items"]]
|
||||||
assert ids == [item["id"] for item in created]
|
assert ids == [item["id"] for item in created]
|
||||||
@@ -122,10 +129,12 @@ async def test_cursor_cannot_be_used_for_another_chat(client: AsyncClient):
|
|||||||
await _message(client, alice, chat_b, "b1")
|
await _message(client, alice, chat_b, "b1")
|
||||||
await _message(client, alice, chat_b, "b2")
|
await _message(client, alice, chat_b, "b2")
|
||||||
|
|
||||||
page = (await client.get(
|
page = (
|
||||||
f"/api/v1/chats/{chat_a['id']}/messages?limit=1",
|
await client.get(
|
||||||
headers=bearer(alice),
|
f"/api/v1/chats/{chat_a['id']}/messages?limit=1",
|
||||||
)).json()
|
headers=bearer(alice),
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
|
||||||
response = await client.get(
|
response = await client.get(
|
||||||
f"/api/v1/chats/{chat_b['id']}/messages?limit=1&cursor={quote(page['next_cursor'], safe='')}",
|
f"/api/v1/chats/{chat_b['id']}/messages?limit=1&cursor={quote(page['next_cursor'], safe='')}",
|
||||||
@@ -205,11 +214,13 @@ async def test_messages_survive_new_login(client: AsyncClient):
|
|||||||
async def test_history_order_is_created_at_then_id(client: AsyncClient):
|
async def test_history_order_is_created_at_then_id(client: AsyncClient):
|
||||||
alice = await create_user(client)
|
alice = await create_user(client)
|
||||||
chat = await create_chat(client, alice)
|
chat = await create_chat(client, alice)
|
||||||
created = [_message(client, alice, chat, f"m{i}").json() for i in range(10)]
|
created = [(await _message(client, alice, chat, f"m{i}")).json() for i in range(10)]
|
||||||
|
|
||||||
listed = (await client.get(
|
listed = (
|
||||||
f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=bearer(alice)
|
await client.get(
|
||||||
)).json()["items"]
|
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]
|
assert [m["id"] for m in listed] == [m["id"] for m in created]
|
||||||
keys = [(m["created_at"], m["id"]) for m in listed]
|
keys = [(m["created_at"], m["id"]) for m in listed]
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Миграции с нуля: «миграции с нуля и повторный запуск без дублирования данных»."""
|
"""Миграции: применение с нуля, идемпотентный повтор, совпадение со схемой моделей."""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from alembic.autogenerate import compare_metadata
|
from alembic.autogenerate import compare_metadata
|
||||||
@@ -8,7 +8,7 @@ from sqlalchemy import inspect, text
|
|||||||
from app.models import Base
|
from app.models import Base
|
||||||
from tests.conftest import reset_schema, upgrade_head
|
from tests.conftest import reset_schema, upgrade_head
|
||||||
|
|
||||||
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "sessions"}
|
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "counters"}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -24,11 +24,15 @@ async def migrated_engine(database_url, db_engine):
|
|||||||
|
|
||||||
async def test_upgrade_creates_all_tables(migrated_engine):
|
async def test_upgrade_creates_all_tables(migrated_engine):
|
||||||
async with migrated_engine.connect() as connection:
|
async with migrated_engine.connect() as connection:
|
||||||
tables = await connection.run_sync(lambda sync: set(inspect(sync).get_table_names()))
|
tables = await connection.run_sync(
|
||||||
|
lambda sync: set(inspect(sync).get_table_names())
|
||||||
|
)
|
||||||
assert EXPECTED_TABLES <= tables
|
assert EXPECTED_TABLES <= tables
|
||||||
|
|
||||||
|
|
||||||
async def test_upgrade_twice_is_idempotent_and_keeps_data(migrated_engine, database_url):
|
async def test_upgrade_twice_is_idempotent_and_keeps_data(
|
||||||
|
migrated_engine, database_url
|
||||||
|
):
|
||||||
async with migrated_engine.begin() as connection:
|
async with migrated_engine.begin() as connection:
|
||||||
await connection.execute(
|
await connection.execute(
|
||||||
text(
|
text(
|
||||||
@@ -41,17 +45,23 @@ async def test_upgrade_twice_is_idempotent_and_keeps_data(migrated_engine, datab
|
|||||||
|
|
||||||
async with migrated_engine.connect() as connection:
|
async with migrated_engine.connect() as connection:
|
||||||
count = (
|
count = (
|
||||||
await connection.execute(text("SELECT count(*) FROM users WHERE username = 'keep_me'"))
|
await connection.execute(
|
||||||
|
text("SELECT count(*) FROM users WHERE username = 'keep_me'")
|
||||||
|
)
|
||||||
).scalar_one()
|
).scalar_one()
|
||||||
assert count == 1
|
assert count == 1
|
||||||
|
|
||||||
|
|
||||||
async def test_models_and_migrations_are_in_sync(migrated_engine):
|
async def test_models_and_migrations_are_in_sync(migrated_engine):
|
||||||
def compare(sync_connection):
|
def compare(sync_connection):
|
||||||
context = MigrationContext.configure(sync_connection, opts={"compare_type": True})
|
context = MigrationContext.configure(
|
||||||
|
sync_connection, opts={"compare_type": True}
|
||||||
|
)
|
||||||
return compare_metadata(context, Base.metadata)
|
return compare_metadata(context, Base.metadata)
|
||||||
|
|
||||||
async with migrated_engine.connect() as connection:
|
async with migrated_engine.connect() as connection:
|
||||||
diff = await connection.run_sync(compare)
|
diff = await connection.run_sync(compare)
|
||||||
|
|
||||||
assert diff == [], f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
assert diff == [], (
|
||||||
|
f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""Курсоры: непрозрачность, привязка к ресурсу и устойчивость к подделке."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from tests.helpers import bearer, create_chat, create_user, send_message
|
||||||
|
|
||||||
|
|
||||||
|
def forged_cursor(**payload: str) -> str:
|
||||||
|
return base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"cursor",
|
||||||
|
[
|
||||||
|
"not-base64-%%%",
|
||||||
|
base64.urlsafe_b64encode(b"not json").decode(),
|
||||||
|
base64.urlsafe_b64encode(b"[1, 2, 3]").decode(),
|
||||||
|
forged_cursor(kind="messages"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_garbage_cursor_returns_400(client: AsyncClient, cursor: str):
|
||||||
|
alice = await create_user(client)
|
||||||
|
chat = await create_chat(client, alice)
|
||||||
|
|
||||||
|
for url in (
|
||||||
|
f"/api/v1/chats?cursor={quote(cursor, safe='')}",
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages?cursor={quote(cursor, safe='')}",
|
||||||
|
):
|
||||||
|
response = await client.get(url, headers=bearer(alice))
|
||||||
|
assert response.status_code == 400, url
|
||||||
|
assert response.json()["error"]["code"] == "invalid_request"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_cursor_without_timezone_is_rejected(client: AsyncClient):
|
||||||
|
alice = await create_user(client)
|
||||||
|
cursor = forged_cursor(
|
||||||
|
kind="chats",
|
||||||
|
resource_id=alice["id"],
|
||||||
|
created_at="2026-01-01T00:00:00",
|
||||||
|
item_id="00000000-0000-4000-8000-000000000000",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.get(
|
||||||
|
f"/api/v1/chats?cursor={quote(cursor, safe='')}", headers=bearer(alice)
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
async def test_chat_list_cursor_is_bound_to_its_owner(client: AsyncClient):
|
||||||
|
alice = await create_user(client)
|
||||||
|
bob = await create_user(client)
|
||||||
|
for index in range(2):
|
||||||
|
await create_chat(client, alice, bob, title=f"shared-{index}")
|
||||||
|
|
||||||
|
page = (await client.get("/api/v1/chats?limit=1", headers=bearer(alice))).json()
|
||||||
|
response = await client.get(
|
||||||
|
f"/api/v1/chats?limit=1&cursor={quote(page['next_cursor'], safe='')}",
|
||||||
|
headers=bearer(bob),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
async def test_messages_cursor_is_not_accepted_by_chat_list(client: AsyncClient):
|
||||||
|
alice = await create_user(client)
|
||||||
|
chat = await create_chat(client, alice)
|
||||||
|
for index in range(2):
|
||||||
|
await send_message(client, alice, chat, f"m{index}")
|
||||||
|
|
||||||
|
page = (
|
||||||
|
await client.get(
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=bearer(alice)
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
response = await client.get(
|
||||||
|
f"/api/v1/chats?cursor={quote(page['next_cursor'], safe='')}",
|
||||||
|
headers=bearer(alice),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
async def test_limit_can_change_between_pages(client: AsyncClient):
|
||||||
|
alice = await create_user(client)
|
||||||
|
chat = await create_chat(client, alice)
|
||||||
|
sent = [
|
||||||
|
(await send_message(client, alice, chat, f"m{index}")).json()
|
||||||
|
for index in range(6)
|
||||||
|
]
|
||||||
|
|
||||||
|
first = (
|
||||||
|
await client.get(
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=bearer(alice)
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
rest = (
|
||||||
|
await client.get(
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages?limit=100"
|
||||||
|
f"&cursor={quote(first['next_cursor'], safe='')}",
|
||||||
|
headers=bearer(alice),
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
|
||||||
|
assert [m["id"] for m in first["items"] + rest["items"]] == [m["id"] for m in sent]
|
||||||
|
assert rest["next_cursor"] is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_message_sent_after_reading_last_page_is_seen_with_cursor(
|
||||||
|
client: AsyncClient,
|
||||||
|
):
|
||||||
|
alice = await create_user(client)
|
||||||
|
chat = await create_chat(client, alice)
|
||||||
|
await send_message(client, alice, chat, "first")
|
||||||
|
await send_message(client, alice, chat, "second")
|
||||||
|
|
||||||
|
page = (
|
||||||
|
await client.get(
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=bearer(alice)
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
new = (await send_message(client, alice, chat, "third")).json()
|
||||||
|
rest = (
|
||||||
|
await client.get(
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages?limit=100"
|
||||||
|
f"&cursor={quote(page['next_cursor'], safe='')}",
|
||||||
|
headers=bearer(alice),
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
|
||||||
|
assert [m["text"] for m in rest["items"]] == ["second", "third"]
|
||||||
|
assert rest["items"][-1] == new
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
"""Сессии в Redis: TTL, абсолютный срок, отзыв, потеря и перезапуск хранилища."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import AsyncClient
|
||||||
|
from redis.asyncio import Redis
|
||||||
|
|
||||||
|
from app.main import create_app
|
||||||
|
from tests.conftest import close_app, make_client
|
||||||
|
from tests.helpers import basic_header, bearer, create_user, register
|
||||||
|
|
||||||
|
ME = "/api/v1/users/me"
|
||||||
|
LOGOUT = "/api/v1/auth/sessions/current"
|
||||||
|
|
||||||
|
|
||||||
|
def session_key(token: str) -> str:
|
||||||
|
return "session:" + hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_session_key_ttl_matches_expires_at(
|
||||||
|
client: AsyncClient, redis_client: Redis
|
||||||
|
):
|
||||||
|
user = await register(client)
|
||||||
|
response = await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(user["username"], user["password"]),
|
||||||
|
)
|
||||||
|
body = response.json()
|
||||||
|
|
||||||
|
expires_at = datetime.fromisoformat(body["expires_at"])
|
||||||
|
expire_time_ms = await redis_client.pexpiretime(session_key(body["token"]))
|
||||||
|
|
||||||
|
assert abs(expire_time_ms - expires_at.timestamp() * 1000) < 2
|
||||||
|
assert 299_000 < await redis_client.pttl(session_key(body["token"])) <= 300_000
|
||||||
|
|
||||||
|
|
||||||
|
async def test_session_ttl_is_absolute_and_not_extended_by_activity(
|
||||||
|
client: AsyncClient, redis_client: Redis
|
||||||
|
):
|
||||||
|
session = await create_user(client)
|
||||||
|
key = session_key(session["token"])
|
||||||
|
expire_before = await redis_client.pexpiretime(key)
|
||||||
|
|
||||||
|
for _ in range(5):
|
||||||
|
assert (await client.get(ME, headers=bearer(session))).status_code == 200
|
||||||
|
|
||||||
|
assert await redis_client.pexpiretime(key) == expire_before
|
||||||
|
|
||||||
|
|
||||||
|
async def test_logout_removes_session_key(client: AsyncClient, redis_client: Redis):
|
||||||
|
session = await create_user(client)
|
||||||
|
key = session_key(session["token"])
|
||||||
|
assert await redis_client.exists(key) == 1
|
||||||
|
|
||||||
|
assert (await client.delete(LOGOUT, headers=bearer(session))).status_code == 204
|
||||||
|
|
||||||
|
assert await redis_client.exists(key) == 0
|
||||||
|
assert (await client.get(ME, headers=bearer(session))).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_expired_session_is_rejected_everywhere(make_settings):
|
||||||
|
app = create_app(make_settings(session_ttl_seconds=1))
|
||||||
|
async with make_client(app) as client:
|
||||||
|
session = await create_user(client)
|
||||||
|
assert (await client.get(ME, headers=bearer(session))).status_code == 200
|
||||||
|
|
||||||
|
await asyncio.sleep(1.5)
|
||||||
|
|
||||||
|
for method, url in (("GET", ME), ("GET", "/api/v1/chats"), ("DELETE", LOGOUT)):
|
||||||
|
response = await client.request(method, url, headers=bearer(session))
|
||||||
|
assert response.status_code == 401, (method, url)
|
||||||
|
assert response.headers["WWW-Authenticate"].startswith("Bearer")
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_relogin_after_expiry_issues_new_working_token(make_settings):
|
||||||
|
app = create_app(make_settings(session_ttl_seconds=1))
|
||||||
|
async with make_client(app) as client:
|
||||||
|
user = await register(client)
|
||||||
|
first = (
|
||||||
|
await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(user["username"], user["password"]),
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
await asyncio.sleep(1.5)
|
||||||
|
second = (
|
||||||
|
await client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers=basic_header(user["username"], user["password"]),
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
|
||||||
|
assert first["token"] != second["token"]
|
||||||
|
assert (await client.get(ME, headers=bearer(first))).status_code == 401
|
||||||
|
assert (await client.get(ME, headers=bearer(second))).status_code == 200
|
||||||
|
await close_app(app)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_tampered_token_is_rejected(client: AsyncClient):
|
||||||
|
session = await create_user(client)
|
||||||
|
token = session["token"]
|
||||||
|
tampered = token[:-1] + ("A" if token[-1] != "A" else "B")
|
||||||
|
|
||||||
|
response = await client.get(ME, headers={"Authorization": f"Bearer {tampered}"})
|
||||||
|
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_session_of_deleted_user_is_rejected(client: AsyncClient, db_engine):
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
session = await create_user(client)
|
||||||
|
async with db_engine.begin() as connection:
|
||||||
|
await connection.execute(
|
||||||
|
text("DELETE FROM users WHERE id = :id"), {"id": session["id"]}
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.get(ME, headers=bearer(session))
|
||||||
|
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
async def test_redis_flush_invalidates_all_sessions(
|
||||||
|
client: AsyncClient, redis_client: Redis
|
||||||
|
):
|
||||||
|
alice = await create_user(client)
|
||||||
|
bob = await create_user(client)
|
||||||
|
|
||||||
|
await redis_client.flushdb()
|
||||||
|
|
||||||
|
for session in (alice, bob):
|
||||||
|
assert (await client.get(ME, headers=bearer(session))).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skipif(
|
||||||
|
os.environ.get("DOCKER_TESTS") != "1",
|
||||||
|
reason="перезапускает контейнер redis из compose; включается DOCKER_TESTS=1",
|
||||||
|
)
|
||||||
|
async def test_sessions_survive_redis_restart(client: AsyncClient, redis_client: Redis):
|
||||||
|
active = await create_user(client)
|
||||||
|
revoked = await create_user(client)
|
||||||
|
assert (await client.delete(LOGOUT, headers=bearer(revoked))).status_code == 204
|
||||||
|
|
||||||
|
process = await asyncio.create_subprocess_exec(
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"restart",
|
||||||
|
"redis",
|
||||||
|
stdout=asyncio.subprocess.DEVNULL,
|
||||||
|
stderr=asyncio.subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
assert await process.wait() == 0
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await redis_client.ping()
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise
|
||||||
|
await asyncio.sleep(0.5)
|
||||||
|
|
||||||
|
response = await client.get(ME, headers=bearer(active))
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["id"] == active["id"]
|
||||||
|
assert (await client.get(ME, headers=bearer(revoked))).status_code == 401
|
||||||
+1
-1
@@ -38,7 +38,7 @@ async def test_get_current_user(client: AsyncClient):
|
|||||||
{"username": "alice-123", "display_name": "Alice", "password": PASSWORD},
|
{"username": "alice-123", "display_name": "Alice", "password": PASSWORD},
|
||||||
{"username": "AlicE", "display_name": "Alice", "password": PASSWORD},
|
{"username": "AlicE", "display_name": "Alice", "password": PASSWORD},
|
||||||
{"username": "a" * 33, "display_name": "Alice", "password": PASSWORD},
|
{"username": "a" * 33, "display_name": "Alice", "password": PASSWORD},
|
||||||
{"username": "alice", "display_name": "Alice"}, # нет пароля
|
{"username": "alice", "display_name": "Alice"},
|
||||||
{"username": "alice", "display_name": "Alice", "password": "x" * 11},
|
{"username": "alice", "display_name": "Alice", "password": "x" * 11},
|
||||||
{"username": "alice", "display_name": "Alice", "password": "x" * 129},
|
{"username": "alice", "display_name": "Alice", "password": "x" * 129},
|
||||||
],
|
],
|
||||||
|
|||||||
Reference in New Issue
Block a user