This commit is contained in:
2026-10-23 14:47:53 +03:00
parent 65003b6119
commit 84fc48d315
29 changed files with 1940 additions and 24 deletions
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Проверка отказа Redis/PostgreSQL (уровень 4). Требует Docker и RUN_INFRA_TEST=1."""
import json
import os
import subprocess
import sys
import time
import unittest
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE = os.environ.get('BASE_URL', 'http://localhost:8080').rstrip('/')
def compose_argv():
override = os.environ.get('COMPOSE', '').strip()
if override:
return override.split()
return ['docker', 'compose']
def compose(*args):
result = subprocess.run(
[*compose_argv(), *args],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
raise RuntimeError(
COMPOSE + ' ' + ' '.join(args) + ' failed: ' + (result.stderr or result.stdout)
)
def http(method, path, token=None, expected=None):
headers = {'Accept': 'application/json'}
if token:
headers['Authorization'] = 'Bearer ' + token
req = urllib.request.Request(BASE + path, headers=headers, method=method)
try:
response = urllib.request.urlopen(req, timeout=5)
except urllib.error.HTTPError as error:
response = error
with response:
body = response.read()
payload = json.loads(body) if body else None
if expected is not None:
if isinstance(expected, int):
expected = [expected]
if response.code not in expected:
raise AssertionError(
f'{method} {path}: expected {expected}, got {response.code} {payload}'
)
return response.code, payload
def wait_ready(deadline=60):
end = time.monotonic() + deadline
while time.monotonic() < end:
try:
code, _ = http('GET', '/health/ready')
if code == 200:
return
except (urllib.error.URLError, TimeoutError, ConnectionError, json.JSONDecodeError):
pass
time.sleep(0.5)
raise TimeoutError('API did not become ready')
@unittest.skipUnless(
os.environ.get('RUN_INFRA_TEST') == '1',
'Set RUN_INFRA_TEST=1 to run Docker dependency failure tests',
)
class DependencyFailureTests(unittest.TestCase):
token = None
@classmethod
def setUpClass(cls):
wait_ready()
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client # noqa: WPS433
actor = Client(BASE).user('dep')
cls.token = actor['token']
def tearDown(self):
compose('start', 'redis', 'postgres')
wait_ready()
def test_redis_down_ready_and_auth(self):
compose('stop', 'redis')
time.sleep(1)
code, payload = http('GET', '/health/ready')
self.assertEqual(code, 503)
self.assertEqual(payload['error']['code'], 'unavailable')
code, payload = http('GET', '/api/v1/users/me', token=self.token)
self.assertEqual(code, 503)
self.assertEqual(payload['error']['code'], 'unavailable')
def test_postgres_down_ready(self):
compose('stop', 'postgres')
time.sleep(1)
code, payload = http('GET', '/health/ready')
self.assertEqual(code, 503)
self.assertEqual(payload['error']['code'], 'unavailable')
if __name__ == '__main__':
unittest.main()
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Дополнительные проверки уровня 4: auth, expiry, гонка username, rollback чата."""
import base64
import json
import os
import sys
import time
import unittest
import urllib.error
import urllib.request
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, check # noqa: E402
BASE = os.environ.get('BASE_URL', 'http://localhost:8080').rstrip('/')
def raw_request(method, path, expected, body=None, headers=None):
data = None
h = {'Accept': 'application/json'}
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
h['Content-Type'] = 'application/json'
h.update(headers or {})
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
response = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
payload = response.read()
check(response.code == expected, f'{method} {path}: expected {expected}, got {response.code}')
return response.code, response.headers, json.loads(payload) if payload else None
class Lab2Grade4Tests(unittest.TestCase):
def test_logout_revokes_session(self):
c = Client(BASE)
actor = c.user('logout')
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)
def test_wrong_password_rejected(self):
c = Client(BASE)
actor = c.user('pwd')
bad = base64.b64encode(
(actor['registration']['username'] + ':wrong-password-x').encode()
).decode()
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + bad})
def test_readiness_requires_dependencies(self):
c = Client(BASE)
c.call('GET', '/health/ready', schema='Health')
@unittest.skipUnless(
os.environ.get('RUN_EXPIRY_TEST') == '1',
'Set RUN_EXPIRY_TEST=1 and SESSION_TTL_SECONDS=2 on the API, then rerun',
)
def test_session_expiry(self):
c = Client(BASE)
username = 'u_exp_' + uuid.uuid4().hex[:12]
password = 'T3st-' + uuid.uuid4().hex
body = {'username': username, 'display_name': 'Expiry', 'password': password}
user = c.call('POST', '/api/v1/users', 201, body=body, schema='User')['json']
credential = base64.b64encode((username + ':' + password).encode()).decode()
session = c.call(
'POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + credential},
schema='Session',
)['json']
actor = {'id': user['id'], 'user': user, 'registration': body, 'token': session['token']}
time.sleep(3)
c.call('GET', '/api/v1/users/me', 401, actor=actor)
def test_duplicate_username_race(self):
c = Client(BASE)
username = 'u_race_' + uuid.uuid4().hex[:10]
password = 'T3st-' + uuid.uuid4().hex
body = {
'username': username,
'display_name': 'Race',
'password': password,
}
def register():
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
req = urllib.request.Request(
BASE + '/api/v1/users',
data=data,
headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
method='POST',
)
try:
response = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as error:
return error.code
with response:
return response.code
with ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(lambda _: register(), range(8)))
check(all(code in (201, 409) for code in statuses), f'unexpected race statuses: {set(statuses)}')
check(sum(1 for code in statuses if code == 201) == 1, 'expected exactly one 201')
def test_chat_creation_rollback_unknown_member(self):
c = Client(BASE)
alice = c.user('rb_alice')
bob = c.user('rb_bob')
fake = str(uuid.uuid4())
c.call(
'POST', '/api/v1/chats', 400, actor=alice,
body={'title': 'Bad', 'member_ids': [alice['id'], fake]},
)
listed = c.call('GET', '/api/v1/chats?limit=100', actor=alice, schema='ChatPage')['json']
check(all(item['title'] != 'Bad' for item in listed['items']), 'chat row leaked after rollback')
listed_bob = c.call('GET', '/api/v1/chats?limit=100', actor=bob, schema='ChatPage')['json']
check(all(item['title'] != 'Bad' for item in listed_bob['items']), 'chat row leaked to bob')
if __name__ == '__main__':
unittest.main()
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Sanity checks for track 2 evidence artifacts."""
import json
import os
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / 'evidence' / 'track2'
@unittest.skipUnless(
os.environ.get('RUN_TRACK2_VERIFY') == '1',
'Set RUN_TRACK2_VERIFY=1 after running track2 scripts',
)
class Track2EvidenceTests(unittest.TestCase):
def test_benchmark_artifact(self):
path = EVIDENCE / 'benchmark.json'
self.assertTrue(path.is_file(), 'missing benchmark.json — run scripts/track2_benchmark.py')
data = json.loads(path.read_text(encoding='utf-8'))
keyset = data['read_plans']['keyset_limit_50']['execution_ms']
offset = data['read_plans']['offset_50000_limit_50']['execution_ms']
self.assertLess(keyset, offset, 'keyset should be faster than large OFFSET on hot chat')
self.assertIsNotNone(data['read_plans']['keyset_limit_50'].get('index_name'))
def test_restore_artifact(self):
path = EVIDENCE / 'restore_report.json'
self.assertTrue(path.is_file(), 'missing restore_report.json')
data = json.loads(path.read_text(encoding='utf-8'))
self.assertTrue(data['counts_match'])
self.assertTrue(data['sample_match'])
self.assertGreaterEqual(data['source']['messages'], 100_000)
if __name__ == '__main__':
unittest.main()