From 9bba9c4b25d25cf55dc0d00cc29b3eb41b06e423 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Fri, 2 Oct 2026 16:32:10 +0300 Subject: [PATCH] test(student-tests): lab2 consolidate negative, concurrency, auth and resilience checks in one commit --- evidence/explain_history.txt | 33 ++++++++++++ student-tests/README.md | 36 +++++++++++-- student-tests/explain_history.sh | 44 +++++++++++++++ student-tests/run_all.py | 10 +++- student-tests/test_auth.py | 81 ++++++++++++++++++++++++++++ student-tests/test_concurrency.py | 5 +- student-tests/test_expiry.py | 46 ++++++++++++++++ student-tests/test_resilience.py | 89 +++++++++++++++++++++++++++++++ 8 files changed, 337 insertions(+), 7 deletions(-) create mode 100644 evidence/explain_history.txt create mode 100644 student-tests/explain_history.sh create mode 100644 student-tests/test_auth.py create mode 100644 student-tests/test_expiry.py create mode 100644 student-tests/test_resilience.py diff --git a/evidence/explain_history.txt b/evidence/explain_history.txt new file mode 100644 index 0000000..8f2a0c0 --- /dev/null +++ b/evidence/explain_history.txt @@ -0,0 +1,33 @@ +# EXPLAIN (ANALYZE, BUFFERS) для истории сообщений +# date: 2026-10-02T11:01:11Z +# chat_id: cf9e8ca9-d08c-41d1-b55f-18c9fba43aec + +## Ключевой запрос пагинации + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.29..4.38 rows=50 width=73) (actual time=0.021..0.029 rows=50 loops=1) + Buffers: shared hit=3 + -> Index Scan using messages_chat_created_id_idx on messages (cost=0.29..819.43 rows=10000 width=73) (actual time=0.020..0.025 rows=50 loops=1) + Index Cond: (chat_id = 'cf9e8ca9-d08c-41d1-b55f-18c9fba43aec'::uuid) + Buffers: shared hit=3 + Planning: + Buffers: shared hit=111 + Planning Time: 0.694 ms + Execution Time: 0.063 ms +(9 rows) + + +## Индексы таблицы messages + indexname | indexdef +------------------------------+---------------------------------------------------------------------------------------------------- + messages_pkey | CREATE UNIQUE INDEX messages_pkey ON public.messages USING btree (id) + messages_chat_created_id_idx | CREATE INDEX messages_chat_created_id_idx ON public.messages USING btree (chat_id, created_at, id) +(2 rows) + + +## Оценка размера и количества + estimated_rows | total_size +----------------+------------ + 10222 | 2264 kB +(1 row) + diff --git a/student-tests/README.md b/student-tests/README.md index 0781b12..7524c0d 100644 --- a/student-tests/README.md +++ b/student-tests/README.md @@ -1,7 +1,37 @@ # Собственные тесты -Проверки негативных сценариев и конкурентной работы, отдельно от публичных `tests/`. +Проверки негативных сценариев, конкурентной работы, жизненного цикла +сессий и отказов хранилищ. Отдельно от публичных `tests/`. -Запуск (сервер уже должен быть поднят на `localhost:8080`): +Сервер должен быть поднят на `http://localhost:8080`. - python students-tests/run_all.py --base-url http://localhost:8080 +## Быстрый прогон + + python student-tests/run_all.py --base-url http://localhost:8080 + +Запускает `test_cases.py`, `test_concurrency.py`, `test_auth.py`. +Это базовый набор, не требующий особой конфигурации стенда. + +## Отдельные сценарии + + python student-tests/test_expiry.py --base-url http://localhost:8080 + +Требует стенд с `SESSION_TTL_SECONDS=2`. Проверяет, что сессия +перестаёт работать после истечения TTL. Меняй TTL в `compose.yaml`, +перезапускай api и прогоняй. + + python student-tests/test_resilience.py --service redis + python student-tests/test_resilience.py --service postgres + +Требуют запущенного Docker и работающего стенда. Скрипт останавливает +указанный сервис через `docker compose stop`, проверяет, что защищённые +endpoint отдают 503 unavailable (не 401 и не 500), и запускает сервис +обратно. + +## Данные для EXPLAIN + + python student-tests/seed_messages.py --count 10000 + student-tests/explain_history.sh + +`seed_messages.py` печатает `chat_id`; передай его в `explain_history.sh`, +результат сохранится в `evidence/explain_history.txt`. \ No newline at end of file diff --git a/student-tests/explain_history.sh b/student-tests/explain_history.sh new file mode 100644 index 0000000..5f381fd --- /dev/null +++ b/student-tests/explain_history.sh @@ -0,0 +1,44 @@ +#!/bin/sh +set -eu + +chat_id="${1:-}" +if [ -z "$chat_id" ]; then + echo "usage: $0 " >&2 + echo "chat_id печатает student-tests/seed_messages.py" >&2 + exit 2 +fi + +cd "$(dirname "$0")/.." +mkdir -p evidence + +{ + echo "# EXPLAIN (ANALYZE, BUFFERS) для истории сообщений" + echo "# date: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "# chat_id: $chat_id" + echo + + echo "## Ключевой запрос пагинации" + docker compose exec -T postgres psql -U messenger -d messenger -c " + EXPLAIN (ANALYZE, BUFFERS) + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = '$chat_id' + ORDER BY created_at, id + LIMIT 50; + " + echo + + echo "## Индексы таблицы messages" + docker compose exec -T postgres psql -U messenger -d messenger -c " + SELECT indexname, indexdef FROM pg_indexes + WHERE tablename = 'messages'; + " + echo + + echo "## Оценка размера и количества" + docker compose exec -T postgres psql -U messenger -d messenger -c " + SELECT reltuples::bigint AS estimated_rows, + pg_size_pretty(pg_total_relation_size('messages')) AS total_size + FROM pg_class WHERE relname = 'messages'; + " +} | tee evidence/explain_history.txt \ No newline at end of file diff --git a/student-tests/run_all.py b/student-tests/run_all.py index e089770..69f0467 100644 --- a/student-tests/run_all.py +++ b/student-tests/run_all.py @@ -5,14 +5,20 @@ from pathlib import Path ROOT = Path(__file__).resolve().parent +QUICK = ('test_cases.py', 'test_concurrency.py', 'test_auth.py') + def main(): args = sys.argv[1:] - for script in ('test_cases.py', 'test_concurrency.py'): + failed = [] + for script in QUICK: print(f'=== {script} ===') result = subprocess.run([sys.executable, str(ROOT / script), *args]) if result.returncode != 0: - sys.exit(result.returncode) + failed.append(script) + if failed: + print('FAILED:', ', '.join(failed)) + sys.exit(1) print('=== Все тесты прошли ===') diff --git a/student-tests/test_auth.py b/student-tests/test_auth.py new file mode 100644 index 0000000..5fab75d --- /dev/null +++ b/student-tests/test_auth.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +import base64 +import uuid +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, Failure, arguments, check, run # noqa: E402 + + +def register(c, username, password): + c.call('POST', '/api/v1/users', 201, body={ + 'username': username, + 'display_name': 'Auth test', + 'password': password, + }) + + +def login(c, username, password): + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + r = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session') + return r['json'] + + +def main(): + args = arguments('Logout и неверные учётные данные') + c = Client(args.base_url, args.ca_file) + + # --- logout отзывает текущую сессию --- + username = 'lo_' + uuid.uuid4().hex[:10] + password = 'T3st-' + uuid.uuid4().hex + register(c, username, password) + session = login(c, username, password) + actor = {'id': session['user']['id'], 'token': session['token']} + + # токен работает + c.call('GET', '/api/v1/users/me', actor=actor, schema='User') + + # отзываем + c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor) + + # тот же токен больше не работает + c.call('GET', '/api/v1/users/me', 401, actor=actor) + c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor) + + # --- неверный пароль и неизвестный username дают одинаковый 401 --- + wrong = base64.b64encode(f'{username}:wrong-password-123'.encode()).decode() + r_wrong = c.call('POST', '/api/v1/auth/sessions', 401, + headers={'Authorization': 'Basic ' + wrong}) + check('Basic' in r_wrong['headers'].get('WWW-Authenticate', ''), + 'нет WWW-Authenticate: Basic на неверный пароль') + + unknown = base64.b64encode( + f'nobody_{uuid.uuid4().hex[:10]}:any-password-123'.encode()).decode() + r_unknown = c.call('POST', '/api/v1/auth/sessions', 401, + headers={'Authorization': 'Basic ' + unknown}) + + check(r_wrong['json']['error']['code'] == 'unauthorized', + 'неверный пароль: ожидался код unauthorized') + check(r_unknown['json']['error']['code'] == 'unauthorized', + 'неизвестный username: ожидался код unauthorized') + check(r_wrong['json']['error']['message'] == r_unknown['json']['error']['message'], + 'сообщения отличаются: перебор username возможен') + + # --- X-User-Id не даёт доступ в lab2 --- + c.call('GET', '/api/v1/users/me', 401, + headers={'X-User-Id': session['user']['id']}) + + # --- Basic на бизнес-endpoint не проходит --- + good = base64.b64encode(f'{username}:{password}'.encode()).decode() + c.call('GET', '/api/v1/users/me', 401, + headers={'Authorization': 'Basic ' + good}) + + print('PASS: logout, wrong password, X-User-Id и Basic на бизнес-endpoint') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_concurrency.py b/student-tests/test_concurrency.py index 9dee97a..05fd018 100644 --- a/student-tests/test_concurrency.py +++ b/student-tests/test_concurrency.py @@ -52,14 +52,15 @@ def main(): # --- гонка за username --- username = 'race_' + uuid.uuid4().hex[:8] + password = 'T3st-' + uuid.uuid4().hex + body = {'username': username, 'display_name': 'Race', 'password': password} barrier2 = threading.Barrier(workers) def register(_): local = Client(args.base_url, args.ca_file, timeout=10) barrier2.wait() try: - local.call('POST', '/api/v1/users', 201, - body={'username': username, 'display_name': 'Race'}) + local.call('POST', '/api/v1/users', 201, body=body) return 'ok' except Failure: return 'conflict' diff --git a/student-tests/test_expiry.py b/student-tests/test_expiry.py new file mode 100644 index 0000000..b79aa2a --- /dev/null +++ b/student-tests/test_expiry.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +import base64 +import time +import uuid +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Истечение сессии. Требует SESSION_TTL_SECONDS=2') + c = Client(args.base_url, args.ca_file) + + username = 'exp_' + uuid.uuid4().hex[:10] + password = 'T3st-' + uuid.uuid4().hex + c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': 'Exp', 'password': password}) + + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + s = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session')['json'] + actor = {'id': s['user']['id'], 'token': s['token']} + + # сразу после логина — работает + c.call('GET', '/api/v1/users/me', actor=actor, schema='User') + + # ждём больше TTL. Если TTL не 2, тест упадёт с понятным сообщением + # (см. проверку ниже по факту отказа). + time.sleep(3.5) + + # ожидаем 401 с Bearer challenge + r = c.call('GET', '/api/v1/users/me', 401, actor=actor) + challenge = r['headers'].get('WWW-Authenticate', '') + check(challenge.lower().startswith('bearer'), + f'ожидался WWW-Authenticate: Bearer, получено {challenge!r}') + + # и сразу проверяем, что до истечения он работал — уже сделано выше + print('PASS: сессия истекла после TTL и вернула 401 Bearer') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_resilience.py b/student-tests/test_resilience.py new file mode 100644 index 0000000..5f1b0f5 --- /dev/null +++ b/student-tests/test_resilience.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +import argparse +import subprocess +import time +import uuid +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, check, run # noqa: E402 + +REPO_ROOT = ROOT + + +def compose(*args, timeout=90): + return subprocess.run( + ['docker', 'compose', '--env-file', '.env', *args], + cwd=REPO_ROOT, capture_output=True, text=True, timeout=timeout, + ) + + +def make_user(c): + username = 'rs_' + uuid.uuid4().hex[:10] + password = 'T3st-' + uuid.uuid4().hex + c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': 'Res', 'password': password}) + import base64 + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + s = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session')['json'] + return {'id': s['user']['id'], 'token': s['token']} + + +def wait_ready(c, seconds=90): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + c.call('GET', '/health/ready', schema='Health') + return + except Exception: + time.sleep(1) + raise RuntimeError('health/ready не восстановился за %d секунд' % seconds) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('--service', choices=['redis', 'postgres'], required=True) + p.add_argument('--base-url', default=None) + args = p.parse_args() + + c = Client(args.base_url) + alice = make_user(c) + c.call('GET', '/api/v1/users/me', actor=alice, schema='User') + + print(f'[{args.service}] останавливаем сервис') + r = compose('stop', args.service) + check(r.returncode == 0, f'docker compose stop: {r.stderr.strip()}') + + try: + time.sleep(2) + + # Защищённый endpoint должен вернуть 503 unavailable. + resp = c.call('GET', '/api/v1/users/me', 503, actor=alice) + code = resp['json']['error']['code'] + check(code == 'unavailable', + f'ожидался код unavailable, получено {code!r}') + + # Сообщение не должно раскрывать детали про Redis/Postgres/сеть. + msg = resp['json']['error']['message'].lower() + for bad in ('redis', 'postgres', 'sql', 'connection', 'refused', 'dial'): + check(bad not in msg, f'сообщение раскрывает "{bad}": {msg}') + + # Здоровье тоже должно репортить 503. + c.call('GET', '/health/ready', 503) + finally: + print(f'[{args.service}] запускаем сервис обратно') + r = compose('start', args.service) + check(r.returncode == 0, f'docker compose start: {r.stderr.strip()}') + wait_ready(c) + + # Токен alice всё ещё валиден после возврата сервиса. + c.call('GET', '/api/v1/users/me', actor=alice, schema='User') + print(f'PASS: {args.service} недоступен → 503 unavailable без утечек; восстановление OK') + + +if __name__ == '__main__': + run(main) \ No newline at end of file