From a5b668c31c18fc92e6c6620fa353d70d2083127b 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: Wed, 7 Oct 2026 16:12:11 +0300 Subject: [PATCH] test(load): lab3 add ai generated k6 write scenario --- student-tests/README.md | 79 +++++++++++++++++++ student-tests/load-k6.js | 125 ++++++++++++++++++++++++++++++ student-tests/run_all.py | 26 +++++++ student-tests/seed_large.py | 82 ++++++++++++++++++++ student-tests/seed_messages.py | 56 +++++++++++++ student-tests/test_auth.py | 81 +++++++++++++++++++ student-tests/test_cases.py | 112 ++++++++++++++++++++++++++ student-tests/test_concurrency.py | 81 +++++++++++++++++++ student-tests/test_expiry.py | 46 +++++++++++ student-tests/test_resilience.py | 89 +++++++++++++++++++++ 10 files changed, 777 insertions(+) create mode 100644 student-tests/README.md create mode 100644 student-tests/load-k6.js create mode 100644 student-tests/run_all.py create mode 100644 student-tests/seed_large.py create mode 100644 student-tests/seed_messages.py create mode 100644 student-tests/test_auth.py create mode 100644 student-tests/test_cases.py create mode 100644 student-tests/test_concurrency.py create mode 100644 student-tests/test_expiry.py create mode 100644 student-tests/test_resilience.py diff --git a/student-tests/README.md b/student-tests/README.md new file mode 100644 index 0000000..8deda0f --- /dev/null +++ b/student-tests/README.md @@ -0,0 +1,79 @@ +# Собственные тесты + +Проверки негативных сценариев, конкурентной работы, жизненного цикла +сессий и отказов хранилищ. Отдельно от публичных `tests/`. + +Сервер должен быть поднят на `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`. +## Трек 2: план запроса и восстановление + +Исследование на ≥100 000 сообщениях с неравномерными размерами чатов. + + python student-tests/seed_large.py + # сохранить chat_id из вывода в evidence/chat_ids.txt + + student-tests/explain_history.sh + student-tests/compare_indexes.sh + student-tests/write_bench.sh + student-tests/backup_restore.sh + +Результаты попадают в `evidence/`: + +- `explain_history.txt` — EXPLAIN (ANALYZE, BUFFERS) ключевого запроса +- `index_comparison.txt` — baseline vs covering vs Seq Scan +- `write_cost.txt` — время 5000 INSERT под разными индексами +- `backup_restore.txt` — pg_dump → pg_restore → сверка счётчиков и md5 + +Восстановленный контейнер `pg_restore_target` оставлен для ручной проверки +и удаляется вручную после эксперимента. + +## Нагрузка (k6) + +Open-loop генератор: фиксированный arrival rate, устраняет coordinated +omission, отдельные метрики для POST /messages. Дополняет `tests/load.py` +(closed-loop), а не заменяет его. + + k6 run -e RATE=50 -e DURATION=30s student-tests/load-k6.js + k6 run -e RATE=50 -e DURATION=3m \ + --summary-export evidence/k6-rolling.json \ + student-tests/load-k6.js + +Setup регистрирует отдельного пользователя и создаёт чат. Чтобы нагружать +существующий чат (например, из `seed_large.py`), задай `CHAT_ID` и `TOKEN`: + + CHAT_ID=... TOKEN=... k6 run -e RATE=50 -e DURATION=1m student-tests/load-k6.js + +Summary (`--summary-export`) — JSON с p50/p95/p99 `write_latency_ms`, +`write_errors.rate`, `http_reqs.rate`. Порог `write_errors<1%` встроен в +options.thresholds: k6 вернёт non-zero exit, если под нагрузкой появились +ошибки сверх порога. \ No newline at end of file diff --git a/student-tests/load-k6.js b/student-tests/load-k6.js new file mode 100644 index 0000000..df8c3d1 --- /dev/null +++ b/student-tests/load-k6.js @@ -0,0 +1,125 @@ +// k6 — open-loop нагрузка на POST /messages. +// +// В отличие от tests/load.py (closed-loop) генерирует фиксированный +// arrival rate независимо от того, как быстро отвечает сервер. Это +// устраняет coordinated omission: если сервер тормозит, k6 не снижает +// интенсивность, а честно измеряет latency и долю ошибок. +// +// Два режима: +// 1. Default — setup регистрирует пользователя, логинится и создаёт чат. +// 2. External — если заданы CHAT_ID и TOKEN, используется существующий +// чат (например, из student-tests/seed_large.py). Регистрация не нужна. +// +// Запуск: +// k6 run -e RATE=50 -e DURATION=30s student-tests/load-k6.js +// k6 run -e RATE=50 -e DURATION=3m student-tests/load-k6.js \ +// --summary-export evidence/k6-rolling.json +// CHAT_ID=... TOKEN=... k6 run -e RATE=50 -e DURATION=1m student-tests/load-k6.js +// +// Метрики: +// write_latency_ms — latency POST /messages (p50/p95/p99 в summary) +// write_errors — доля не-201 +// write_total — счётчик запросов + +import http from 'k6/http'; +import encoding from 'k6/encoding'; +import { check, fail } from 'k6'; +import { Trend, Rate, Counter } from 'k6/metrics'; + +const RATE = parseInt(__ENV.RATE || '50', 10); +const DURATION = __ENV.DURATION || '1m'; +const BASE = __ENV.BASE_URL || 'http://localhost:8080'; +const EXTERNAL_CHAT = __ENV.CHAT_ID || ''; +const EXTERNAL_TOKEN = __ENV.TOKEN || ''; + +const writeLatency = new Trend('write_latency_ms', true); +const writeErrors = new Rate('write_errors'); +const writeTotal = new Counter('write_total'); + +export const options = { + scenarios: { + writes: { + executor: 'constant-arrival-rate', + rate: RATE, + timeUnit: '1s', + duration: DURATION, + preAllocatedVUs: Math.max(50, RATE * 2), + maxVUs: Math.max(200, RATE * 4), + }, + }, + thresholds: { + // Порог уровня 4: не более 1% ошибок. В треке 1 проверим, + // удерживается ли при разных профилях нагрузки. + 'write_errors': ['rate<0.01'], + }, +}; + +export function setup() { + if (EXTERNAL_CHAT && EXTERNAL_TOKEN) { + return { token: EXTERNAL_TOKEN, chatId: EXTERNAL_CHAT }; + } + if ((EXTERNAL_CHAT && !EXTERNAL_TOKEN) || (!EXTERNAL_CHAT && EXTERNAL_TOKEN)) { + fail('CHAT_ID и TOKEN должны задаваться вместе'); + } + + const suffix = Math.random().toString(36).slice(2, 10); + const username = `k6_${suffix}`; + const password = 'Example-pass-12345678'; + + const reg = http.post(`${BASE}/api/v1/users`, JSON.stringify({ + username, display_name: `K6 ${suffix}`, password, + }), { headers: { 'Content-Type': 'application/json' } }); + if (reg.status !== 201) fail(`register failed: ${reg.status} ${reg.body}`); + + const user = reg.json(); + const encoded = encoding.b64encode(`${username}:${password}`); + + const sess = http.post(`${BASE}/api/v1/auth/sessions`, null, { + headers: { 'Authorization': `Basic ${encoded}` }, + }); + if (sess.status !== 201) fail(`login failed: ${sess.status} ${sess.body}`); + + const token = sess.json().token; + + const chat = http.post(`${BASE}/api/v1/chats`, JSON.stringify({ + title: `k6 chat ${suffix}`, + member_ids: [user.id], + }), { + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${token}`, + }, + }); + if (chat.status !== 201) fail(`chat failed: ${chat.status} ${chat.body}`); + + return { token, chatId: chat.json().id }; +} + +export default function (data) { + const key = `k6-${__VU}-${__ITER}-${Date.now()}`; + const body = JSON.stringify({ text: `msg vu=${__VU} iter=${__ITER}` }); + + const res = http.post( + `${BASE}/api/v1/chats/${data.chatId}/messages`, + body, + { + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${data.token}`, + 'Idempotency-Key': key, + }, + tags: { name: 'POST /messages' }, + }, + ); + + writeTotal.add(1); + writeLatency.add(res.timings.duration); + writeErrors.add(res.status !== 201); + + check(res, { + 'status is 201': (r) => r.status === 201, + 'has message id': (r) => { + try { return !!r.json().id; } catch { return false; } + }, + }); +} \ No newline at end of file diff --git a/student-tests/run_all.py b/student-tests/run_all.py new file mode 100644 index 0000000..69f0467 --- /dev/null +++ b/student-tests/run_all.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +import subprocess +import sys +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:] + failed = [] + for script in QUICK: + print(f'=== {script} ===') + result = subprocess.run([sys.executable, str(ROOT / script), *args]) + if result.returncode != 0: + failed.append(script) + if failed: + print('FAILED:', ', '.join(failed)) + sys.exit(1) + print('=== Все тесты прошли ===') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/student-tests/seed_large.py b/student-tests/seed_large.py new file mode 100644 index 0000000..4aeabad --- /dev/null +++ b/student-tests/seed_large.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Сидирует 100k сообщений в 24 чата с неравномерными размерами (трек 2).""" +import base64 +import sys +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +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 make_user(c, label): + username = f'{label}_{uuid.uuid4().hex[:12]}' + password = 'T3st-' + uuid.uuid4().hex + user = c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': label.capitalize(), + 'password': password}, schema='User')['json'] + 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': user['id'], 'username': username, 'token': s['token']} + + +def seed_chat(base_url, ca_file, alice, bob, title, count, workers=8): + c = Client(base_url, ca_file) + chat = c.call('POST', '/api/v1/chats', 201, actor=alice, body={ + 'title': title, 'member_ids': [alice['id'], bob['id']]}, + schema='Chat')['json'] + chat_id = chat['id'] + + per_worker = count // workers + remainder = count - per_worker * workers + + def worker(wid): + local = Client(base_url, ca_file, timeout=20) + n = per_worker + (1 if wid < remainder else 0) + for i in range(n): + local.call('POST', f'/api/v1/chats/{chat_id}/messages', 201, + actor=alice, body={'text': f'{title} #{wid}-{i}'}, + schema='Message') + + started = time.monotonic() + with ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(worker, range(workers))) + elapsed = time.monotonic() - started + print(f' {title}: {count} сообщений за {elapsed:.1f}s ({count/max(elapsed,0.001):.0f}/s)') + return chat_id + + +def main(): + args = arguments('Сидирует неравномерные чаты для трека 2') + c = Client(args.base_url, args.ca_file) + alice = make_user(c, 'track2_a') + bob = make_user(c, 'track2_b') + + plan = ( + [('hot', 55_000)] + + [('medium-%d' % i, 10_000) for i in range(1, 4)] + + [('small-%d' % i, 1_000) for i in range(1, 11)] + + [('tiny-%d' % i, 500) for i in range(1, 11)] + ) + total = sum(n for _, n in plan) + check(total == 100_000, f'сумма {total} != 100000') + + result = {} + started = time.monotonic() + for title, count in plan: + result[title] = seed_chat(args.base_url, args.ca_file, alice, bob, title, count) + elapsed = time.monotonic() - started + + print(f'\nВсего {total} сообщений за {elapsed:.1f}s ({total/elapsed:.0f}/s)') + print('chat_id для EXPLAIN (сохраните эти значения):') + for title in ('hot', 'medium-1', 'small-1', 'tiny-1'): + print(f' {title}: {result[title]}') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/seed_messages.py b/student-tests/seed_messages.py new file mode 100644 index 0000000..47bd608 --- /dev/null +++ b/student-tests/seed_messages.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Заполняет один чат N сообщениями. Надо EXPLAIN.""" +import base64 +import sys +import time +import uuid +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 make_user(c, label): + username = f'{label}_{uuid.uuid4().hex[:12]}' + password = 'T3st-' + uuid.uuid4().hex + user = c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': label.capitalize(), + 'password': password}, schema='User')['json'] + 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': user['id'], 'token': s['token']} + + +def main(): + def configure(p): + p.add_argument('--count', type=int, default=10000) + + args = arguments('Сид для EXPLAIN: создаёт count сообщений в новом чате', configure) + check(args.count >= 1 and args.count <= 1_000_000, 'count вне диапазона') + + c = Client(args.base_url, args.ca_file) + alice = make_user(c, 'seed_a') + bob = make_user(c, 'seed_b') + + chat = c.call('POST', '/api/v1/chats', 201, actor=alice, body={ + 'title': 'Seed chat', 'member_ids': [alice['id'], bob['id']]}, + schema='Chat')['json'] + + started = time.monotonic() + for i in range(args.count): + c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 201, + actor=alice, body={'text': f'seed message {i}'}, schema='Message') + if (i + 1) % 1000 == 0: + print(f' {i + 1}/{args.count}') + + elapsed = time.monotonic() - started + print(f'seeded {args.count} messages in {elapsed:.1f}s ' + f'({args.count / elapsed:.0f}/s)') + print(f'chat_id={chat["id"]}') + + +if __name__ == '__main__': + run(main) \ No newline at end of file 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_cases.py b/student-tests/test_cases.py new file mode 100644 index 0000000..e939d66 --- /dev/null +++ b/student-tests/test_cases.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +import sys +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, LAB, Failure, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Собственные тесты негативных сценариев') + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + + # --- некорректный JSON --- + malformed = b'{"username":"alice","display_name":"A"' + c.call('POST', '/api/v1/users', 400, raw=malformed, + headers={'Content-Type': 'application/json'}) + + # --- лишнее поле --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], + 'display_name': 'X', 'extra': 'мусор'}) + + # --- неверный тип поля --- + c.call('POST', '/api/v1/users', 400, + body={'username': 123, 'display_name': 'X'}) + + # --- пустой display_name --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ''}) + + # --- display_name только из пробелов --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ' '}) + + # --- заглавные в username --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'UPPERCASE', 'display_name': 'X'}) + + # --- дубликат username --- + c.call('POST', '/api/v1/users', 409, body=alice['registration']) + + # --- пустое сообщение --- + c.call('POST', path + '/messages', 400, actor=alice, body={'text': ''}) + + # --- сообщение только из пробелов --- + c.call('POST', path + '/messages', 400, actor=alice, body={'text': ' '}) + + # --- чужой чат --- + c.call('GET', path, 404, actor=eve) + c.call('GET', path + '/messages', 404, actor=eve) + c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'чужое'}) + + # --- чат без создателя в member_ids --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'Без меня', 'member_ids': [bob['id']]}) + + # --- чат с неизвестным участником --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'С фантомом', + 'member_ids': [alice['id'], '00000000-0000-4000-8000-000000000000']}) + + # --- чат с дубликатами --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'Дубликаты', 'member_ids': [alice['id'], alice['id']]}) + + # --- обход нескольких страниц --- + for i in range(5): + c.message(alice, chat, 'page-test-%d' % i) + + seen = [] + cursor = None + for _ in range(20): + query = path + '/messages?limit=2' + if cursor: + from urllib.parse import quote + query += '&cursor=' + quote(cursor, safe='') + page = c.call('GET', query, actor=alice, schema='MessagePage')['json'] + seen.extend(x['id'] for x in page['items']) + cursor = page['next_cursor'] + if cursor is None: + break + check(len(seen) == len(set(seen)), 'пагинация вернула дубликаты') + check(len(seen) >= 5, 'пагинация потеряла сообщения') + + # --- cursor от другого чата --- + other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, + body={'title': 'Другой чат', + 'member_ids': [alice['id'], bob['id']]}, + schema='Chat')['json'] + other_path = '/api/v1/chats/' + other_chat['id'] + c.message(alice, other_chat, 'other-1') + c.message(alice, other_chat, 'other-2') + + other_page = c.call('GET', other_path + '/messages?limit=1', actor=alice, + schema='MessagePage')['json'] + other_cursor = other_page['next_cursor'] + check(other_cursor is not None, 'ожидался cursor от другого чата, но получен null') + + from urllib.parse import quote + c.call('GET', path + '/messages?limit=2&cursor=' + quote(other_cursor, safe=''), + 400, actor=alice) + + print('PASS: негативные сценарии прошли') + + +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 new file mode 100644 index 0000000..05fd018 --- /dev/null +++ b/student-tests/test_concurrency.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +import threading +import uuid +from concurrent.futures import ThreadPoolExecutor + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, LAB, Failure, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Собственные тесты конкурентности') + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + + # --- 100 сообщений от 10 потоков --- + workers = 10 + per_worker = 10 + expected_total = workers * per_worker + barrier = threading.Barrier(workers) + + def writer(worker_id): + local = Client(args.base_url, args.ca_file, timeout=10) + barrier.wait() + for i in range(per_worker): + local.message(alice, chat, 'c-%d-%d' % (worker_id, i)) + + with ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(writer, range(workers))) + + seen = [] + cursor = None + while True: + q = path + '/messages?limit=100' + if cursor: + from urllib.parse import quote + q += '&cursor=' + quote(cursor, safe='') + page = c.call('GET', q, actor=alice, schema='MessagePage')['json'] + seen.extend(x['id'] for x in page['items']) + cursor = page['next_cursor'] + if cursor is None: + break + + check(len(seen) == len(set(seen)), 'после параллельной записи обнаружены дубликаты id сообщений') + check(len(seen) == expected_total, + 'ожидалось ровно %d сообщений, получено %d' % (expected_total, len(seen))) + + # --- гонка за 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=body) + return 'ok' + except Failure: + return 'conflict' + + with ThreadPoolExecutor(max_workers=workers) as pool: + results = list(pool.map(register, range(workers))) + + ok_count = results.count('ok') + conflict_count = results.count('conflict') + check(ok_count == 1, 'ожидалась ровно одна успешная регистрация, получено %d' % ok_count) + check(conflict_count == workers - 1, + 'ожидалось %d конфликтов, получено %d' % (workers - 1, conflict_count)) + + print('PASS: конкурентность (100 сообщений, 1 победитель в гонке за username)') + + +if __name__ == '__main__': + run(main) \ No newline at end of file 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