test(student-tests): lab2 consolidate negative, concurrency, auth and resilience checks in one commit
This commit is contained in:
@@ -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)
|
||||
|
||||
+33
-3
@@ -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 <chat_id>
|
||||
|
||||
`seed_messages.py` печатает `chat_id`; передай его в `explain_history.sh`,
|
||||
результат сохранится в `evidence/explain_history.txt`.
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
chat_id="${1:-}"
|
||||
if [ -z "$chat_id" ]; then
|
||||
echo "usage: $0 <chat_id>" >&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
|
||||
@@ -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('=== Все тесты прошли ===')
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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'
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user