Разбить API на слои, комментарии на русском
Skeleton contracts / contracts (pull_request) Canceled after 0s

routes -> http/auth -> repositories -> infra; поведение не изменилось, smoke, persistence и тесты уровня 4 перепрогнаны.
This commit is contained in:
celis
2026-10-29 22:25:01 +03:00
parent cac37bddec
commit b79be9b0eb
35 changed files with 729 additions and 486 deletions
+7 -7
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Level-4 checks of my solution: races, rollback, pagination, expiry, logout, wrong password, dependency loss.
"""Проверки уровня 4: гонки, откат, пагинация, истечение сессии, logout, неверный пароль, отказ зависимостей.
Uses the public tests/client.py helpers. Stops/starts compose services (volumes are kept):
Использует помощники из публичного tests/client.py. Останавливает и запускает сервисы compose (volumes сохраняются):
python3 student-tests/test_lab2.py --base-url http://127.0.0.1:8080
"""
import base64
@@ -56,7 +56,7 @@ def test_chat_rollback(c):
alice = c.user('rb')
title = 'rollback-' + uuid.uuid4().hex
before = psql('SELECT count(*) FROM chats')
# caller passes validation; the unknown member fails the FK after the chat row was inserted
# запрос проходит валидацию; неизвестный участник нарушает FK уже после вставки строки чата
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': title, 'member_ids': [alice['id'], str(uuid.uuid4())]})
check(psql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == '0', 'rollback: orphan chat row left')
check(psql('SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL') == '0',
@@ -78,7 +78,7 @@ def test_pagination_and_injection(c):
cursor = page['next_cursor']
if cursor is None:
break
# contract order is (created_at, id); two messages in one millisecond are ordered by id
# порядок по контракту — (created_at, id); два сообщения в одну миллисекунду упорядочены по id
check(got == sorted(sent, key=lambda m: (m['created_at'], uuid.UUID(m['id']).int)), 'pagination: lost/duplicated/reordered')
first = c.call('GET', path, actor=alice, schema='MessagePage')['json']
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(first['next_cursor'], safe=''), 400, actor=alice)
@@ -110,7 +110,7 @@ def test_expiry(c):
time.sleep(3)
r = short.call('GET', '/api/v1/users/me', 401, actor=alice)
check(r['headers']['WWW-Authenticate'] == 'Bearer realm="messenger"', 'wrong challenge')
# the same Valkey is shared, so the main API must reject it too
# Valkey общий, поэтому основной API тоже должен отклонить токен
c.call('GET', '/api/v1/users/me', 401, actor=alice)
finally:
compose('--profile', 'ttl', 'stop', 'api_short_ttl')
@@ -126,7 +126,7 @@ def outage(c, service, survives):
r = c.call('GET', path, 503, actor=alice)
elapsed = time.monotonic() - started
check(r['json']['error']['code'] == 'unavailable' and elapsed < 5, service + ': not a bounded 503')
# an anonymous request is still 401, never served as trusted
# анонимный запрос по-прежнему 401, а не обслуживается как доверенный
c.call('GET', '/api/v1/users/me', 401)
survivor = c.call('POST', '/api/v1/users', [201, 503], body={'username': 'o_' + uuid.uuid4().hex[:12],
'display_name': 'x', 'password': 'Outage-password-1'})
@@ -134,7 +134,7 @@ def outage(c, service, survives):
finally:
compose('start', service)
wait_ready(c)
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # same token after recovery
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # тот же токен после восстановления
return '%s stopped -> ready/me 503 unavailable in %.2fs, anonymous 401, registration %s; recovered with same token' % (
service, elapsed, '201' if survives else '503')