forked from mtusi2026/mtusi2026lab2
Fixing
This commit is contained in:
@@ -1,54 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline structural checks; full schema validation is a separate target."""
|
||||
import ast
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
def walk(value):
|
||||
if isinstance(value,dict):
|
||||
if '$ref' in value:
|
||||
pointer = value['$ref']
|
||||
assert pointer.startswith('#/'), 'unexpected external reference'
|
||||
target = spec
|
||||
for part in pointer[2:].split('/'):
|
||||
target = target[part.replace('~1','/').replace('~0','~')]
|
||||
for v in value.values():
|
||||
walk(v)
|
||||
elif isinstance(value,list):
|
||||
for v in value:
|
||||
walk(v)
|
||||
walk(spec)
|
||||
for route,methods in spec['paths'].items():
|
||||
placeholders = set(re.findall(r'\{([^}]+)\}',route))
|
||||
for method,op in methods.items():
|
||||
assert op['operationId'] not in operation_ids, 'duplicate operationId'
|
||||
operation_ids.add(op['operationId'])
|
||||
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
|
||||
assert placeholders==params, 'path parameter mismatch: '+route
|
||||
for response in op['responses'].values():
|
||||
assert 'X-Request-Id' in response['headers']
|
||||
if lab>=3:
|
||||
assert 'X-Instance-Id' in response['headers']
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
# Сидирует >=10 000 сообщений и снимает EXPLAIN (ANALYZE, BUFFERS) запроса истории.
|
||||
# Запуск до и после миграции b7e1f3a9c2d4 даёт сравнение "до/после" для REPORT.md.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
OUT="${1:-evidence/explain_history.txt}"
|
||||
PSQL="docker compose exec -T db psql -U postgres -d messenger_db"
|
||||
CHAT="00000000-0000-0000-0000-0000000000c1"
|
||||
|
||||
$PSQL < scripts/seed_explain.sql >/dev/null
|
||||
|
||||
# Курсор из середины истории: сообщение №6000 целевого чата
|
||||
MID=$($PSQL -At -c "SELECT created_at || '|' || id FROM messages WHERE chat_id='$CHAT' ORDER BY created_at, id OFFSET 5999 LIMIT 1")
|
||||
TS="${MID%%|*}"; ID="${MID##*|}"
|
||||
|
||||
{
|
||||
echo "== $(date -u +%FT%TZ) =="
|
||||
echo "== версия миграции =="; $PSQL -At -c "SELECT version_num FROM alembic_version"
|
||||
echo "== индексы messages =="; $PSQL -c "\d messages"
|
||||
echo "== сообщений по чатам =="; $PSQL -c "SELECT chat_id, count(*) FROM messages GROUP BY 1"
|
||||
echo "== первая страница =="
|
||||
$PSQL -c "EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id='$CHAT' ORDER BY created_at, id LIMIT 51"
|
||||
echo "== страница из середины (keyset, как в API) =="
|
||||
$PSQL -c "EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id='$CHAT' AND (created_at, id) > ('$TS'::timestamptz, '$ID'::uuid) ORDER BY created_at, id LIMIT 51"
|
||||
} | tee "$OUT"
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# TODO: copy to restart.sh and implement using YOUR compose/stack services.
|
||||
# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable).
|
||||
# Preserve persistent volumes and schema/data; never down -v / flush / re-seed.
|
||||
# Allow operator unseal if required in lab7; do not print credentials.
|
||||
# Exit 0 only after the intended action; test waits for API readiness separately.
|
||||
printf '%s
|
||||
' 'TODO: implement restart.sh for your infrastructure' >&2
|
||||
exit 2
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Воспроизводимый набор: 2 чата по 12 000 сообщений (24 000 всего). Повторный запуск ничего не дублирует.
|
||||
INSERT INTO users(id, username, display_name, password_hash, created_at)
|
||||
VALUES ('00000000-0000-0000-0000-000000000001', 'explain_user', 'Explain', 'x', now())
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO chats(id, title, created_at) VALUES
|
||||
('00000000-0000-0000-0000-0000000000c1', 'explain target', now()),
|
||||
('00000000-0000-0000-0000-0000000000c2', 'explain noise', now())
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO chat_members(chat_id, user_id, joined_at)
|
||||
SELECT c.id, '00000000-0000-0000-0000-000000000001', now()
|
||||
FROM chats c
|
||||
WHERE c.id IN ('00000000-0000-0000-0000-0000000000c1', '00000000-0000-0000-0000-0000000000c2')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO messages(id, chat_id, sender_id, text, created_at)
|
||||
SELECT md5(c.id::text || g)::uuid, c.id, '00000000-0000-0000-0000-000000000001',
|
||||
'msg ' || g, timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second'
|
||||
FROM (VALUES ('00000000-0000-0000-0000-0000000000c1'::uuid),
|
||||
('00000000-0000-0000-0000-0000000000c2'::uuid)) c(id),
|
||||
generate_series(1, 12000) g
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
ANALYZE messages;
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bash
|
||||
# Собственные автотесты: auth/TTL/logout/гонки/откат/пагинация/отказы Valkey и БД. Одна команда: make test-own
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
export BASE_URL="${BASE_URL:-http://localhost:8080}"
|
||||
PY="${PYTHON:-python3}"
|
||||
|
||||
$PY -c "import pytest, httpx" 2>/dev/null || { echo "pip install pytest httpx"; exit 1; }
|
||||
|
||||
wait_ready() {
|
||||
for _ in $(seq 1 90); do curl -fs "$BASE_URL/health/ready" >/dev/null && return 0; sleep 1; done
|
||||
echo "API not ready"; return 1
|
||||
}
|
||||
wait_healthy() {
|
||||
for _ in $(seq 1 60); do
|
||||
s=$(docker inspect -f '{{.State.Health.Status}}' "$1" 2>/dev/null || echo none)
|
||||
[ "$s" = healthy ] && return 0
|
||||
sleep 1
|
||||
done
|
||||
echo "$1 is not healthy" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
docker compose up -d --build
|
||||
wait_ready
|
||||
$PY -m pytest tests_own -m "not ttl" -v
|
||||
|
||||
wait_healthy lab2_postgres
|
||||
wait_healthy lab2_valkey
|
||||
|
||||
# Короткий TTL только для проверки истечения сессии
|
||||
SESSION_TTL_SECONDS=2 docker compose up -d --force-recreate app
|
||||
wait_ready
|
||||
$PY -m pytest tests_own -m ttl -v
|
||||
|
||||
# Вернуть TTL по умолчанию
|
||||
docker compose up -d --force-recreate app
|
||||
wait_ready
|
||||
echo "OK"
|
||||
@@ -1,23 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
schema = json.loads(path.read_text())
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
|
||||
Reference in New Issue
Block a user