feat: implement lab3 API load balancing and failover

This commit is contained in:
sashadugina06
2026-11-06 01:43:33 +03:00
parent 0ab3a341aa
commit 7088791d5c
116 changed files with 7971 additions and 38 deletions
+43
View File
@@ -0,0 +1,43 @@
# Собственные проверки
`check_auth.py` перенесён из собственной lab2 (BASE_URL теперь задаётся окружением).
`scenarios.py` использует публичный HTTP-клиент без изменения `tests/`.
```sh
export BASE_URL=http://localhost:8080
python3 student-tests/check_auth.py
python3 student-tests/scenarios.py idempotency --output evidence/idempotency.json
python3 student-tests/scenarios.py failover --target-index 0 --output evidence/failover-replica-1.json
python3 student-tests/scenarios.py failover --target-index 1 --output evidence/failover-replica-2.json
python3 student-tests/scenarios.py rolling --output evidence/rolling-update.json
```
Требуются две работающие реплики. Failover сам восстанавливает выбранный контейнер после проверки.
Идемпотентность: 24 параллельных повтора с барьером; обе реплики, один результат,
история без дублей; конфликт body; область user/chat; неверные/отсутствующие ключи;
чужой чат; отзыв сессии; повтор после искусственного старения только тестовой записи до 25 часов.
При старении меняется только `created_at` записей с уникальным ключом данного сценария.
Отказы и rolling: 4 closed-loop потока POST через LB; 2 секунды начального участка,
остановка одного контейнера или последовательная замена обоих, запись подтверждённых
объектов только в память, проверка полной истории прежней сессией после воздействия.
Каждый рабочий поток переиспользует один HTTP-клиент. Ошибки считаются без retry;
отдельная проверка идемпотентности проверяет безопасный повтор. CPU/RAM снимаются
`docker stats --no-stream` параллельно. Время восстановления считается от запуска hook
до завершения первого успешного запроса, **начатого после** завершения hook.
Это консервативная оценка с затратами Docker CLI, не точное время смены состояния HAProxy.
RPS и latency относятся к POST; чтение проверяется при остановленной реплике после нагрузки.
Ошибка сценария даёт ненулевой exit code, а JSON PASS записывается только после assertions.
`baseline.py` запускает неизменённый `tests/load.py` 30 секунд с concurrency=4
и параллельно сохраняет Docker stats. `readiness.py` останавливает PostgreSQL:
проверяет live=200/ready=503 каждой API, восстанавливает БД и прежнюю сессию;
затем останавливает Redis и проверяет ready=200 и чтение профиля через fallback.
Оба хранилища восстанавливаются в finally.
`dns.py` временно отсоединяет одну настоящую API от сети, запускает третью
настоящую API для занятия старого IP, подключает исходную обратно и удаляет
временный контейнер. После реальной смены IP проверяет появление исходного
X-Instance-Id через LB и прежние данные/сессию. Использует только сеть/контейнеры
проекта mtusi2026lab3, публичные host-порты не добавляет. Это отдельный сетевой
эксперимент, не сценарий отказа каждой из двух реплик.
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Run the unmodified public generator, collect concurrent container resources."""
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
start=time.monotonic()
resources=[]
with (ROOT/'evidence/load-baseline.txt').open('w') as log:
proc=subprocess.Popen([sys.executable,'tests/load.py','--duration','30','--concurrency','4','--output','evidence/load-baseline.json'],cwd=ROOT,stdout=log,stderr=subprocess.STDOUT)
while proc.poll() is None:
ids=subprocess.check_output([str(ROOT/'scripts/compose.sh'),'ps','-q'],text=True).splitlines()
data=subprocess.check_output(['docker','stats','--no-stream','--format','{{json .}}',*ids],text=True)
resources.append({'offset_seconds':round(time.monotonic()-start,3),'containers':[json.loads(line) for line in data.splitlines()]})
time.sleep(1)
assert proc.returncode==0, 'Load generator failed; inspect evidence/load-baseline.txt'
(ROOT/'evidence/load-baseline-resources.json').write_text(json.dumps(resources,indent=2)+'\n')
print((ROOT/'evidence/load-baseline.txt').read_text())
+150
View File
@@ -0,0 +1,150 @@
import os
import base64
import json
import secrets
import urllib.error
import urllib.request
BASE_URL = os.getenv("BASE_URL", "http://127.0.0.1:8080")
username = "test_" + secrets.token_hex(5)
password = "StrongPassword123!"
def request(method, path, body=None, authorization=None):
headers = {}
if body is not None:
headers["Content-Type"] = "application/json"
body = json.dumps(body).encode("utf-8")
if authorization:
headers["Authorization"] = authorization
req = urllib.request.Request(
BASE_URL + path,
data=body,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(req, timeout=10) as response:
data = response.read()
return response.status, dict(response.headers), (
json.loads(data) if data else None
)
except urllib.error.HTTPError as error:
data = error.read()
return error.code, dict(error.headers), (
json.loads(data) if data else None
)
def check(name, actual, expected):
result = "PASS" if actual == expected else "FAIL"
print(f"{result}: {name}: {actual} (expected {expected})")
if actual != expected:
raise SystemExit(1)
print("1. Registration")
status, headers, user = request(
"POST",
"/api/v1/users",
{
"username": username,
"display_name": "Test User",
"password": password,
},
)
print("Registration status:", status)
print("Registration headers:", headers)
print("Registration body:", user)
check("registration", status, 201)
assert "password" not in user
assert "password_hash" not in user
assert "X-Request-Id" in headers
print("User ID:", user["id"])
print("\n2. Basic login")
credentials = base64.b64encode(
f"{username}:{password}".encode()
).decode()
status, headers, session = request(
"POST",
"/api/v1/auth/sessions",
authorization="Basic " + credentials,
)
check("login", status, 201)
token = session["token"]
assert session["token_type"] == "Bearer"
assert len(token) >= 40
print("\n3. Access with Bearer token")
status, headers, me = request(
"GET",
"/api/v1/users/me",
authorization="Bearer " + token,
)
check("authorized request", status, 200)
assert me["id"] == user["id"]
print("\n4. Access without token")
status, headers, body = request(
"GET",
"/api/v1/users/me",
)
check("missing token", status, 401)
assert any(
key.lower() == "www-authenticate"
and value == 'Bearer realm="messenger"'
for key, value in headers.items()
), f"Неверный WWW-Authenticate: {headers}"
print("\n5. X-User-Id cannot authorize")
req = urllib.request.Request(
BASE_URL + "/api/v1/users/me",
headers={"X-User-Id": user["id"]},
)
try:
urllib.request.urlopen(req, timeout=10)
raise AssertionError("X-User-Id unexpectedly authorized")
except urllib.error.HTTPError as error:
check("X-User-Id rejected", error.code, 401)
print("\n6. Logout")
status, headers, body = request(
"DELETE",
"/api/v1/auth/sessions/current",
authorization="Bearer " + token,
)
check("logout", status, 204)
print("\n7. Reuse revoked token")
status, headers, body = request(
"GET",
"/api/v1/users/me",
authorization="Bearer " + token,
)
check("revoked token rejected", status, 401)
print("\nALL AUTH CHECKS PASSED")
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Change the address of one real API container in this project's network."""
import ipaddress
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client, Failure
from resilience import history
def cmd(*args):
return subprocess.check_output(args,text=True).strip()
compose=[str(ROOT/'scripts/compose.sh')]
c=Client(timeout=2)
a,b,e,chat=c.bootstrap()
message=c.message(a,chat,'DNS synthetic confirmed')['json']
target=cmd(*compose,'ps','-q','api').splitlines()[0]
info=json.loads(cmd('docker','inspect',target))[0]
network=next(iter(info['NetworkSettings']['Networks']))
assert network=='mtusi2026lab3_default'
old_ip=info['NetworkSettings']['Networks'][network]['IPAddress']
alias=cmd('docker','exec',target,'python','-c','import urllib.request; print(urllib.request.urlopen("http://127.0.0.1:8080/health/live").headers["X-Instance-Id"])')
start=time.monotonic()
# Keep the old address occupied by a third REAL API process, then reconnect
# the original. No fixed subnet or synthetic/dummy backend is needed.
cmd('docker','network','disconnect',network,target)
temporary = None
try:
temporary=cmd(*compose,'run','-d','--no-deps','--use-aliases','api').splitlines()[-1]
cmd('docker','network','connect','--alias','api',network,target)
moved=json.loads(cmd('docker','inspect',target))[0]
new_ip=moved['NetworkSettings']['Networks'][network]['IPAddress']
assert new_ip != old_ip
finally:
if temporary:
cmd('docker','stop','--timeout','6',temporary)
cmd('docker','rm',temporary)
current=json.loads(cmd('docker','inspect',target))[0]
if network not in current['NetworkSettings']['Networks']:
cmd('docker','network','connect','--alias','api',network,target)
errors=0
seen=set()
while time.monotonic()-start<15:
try:
r=c.message(a,chat,'DNS-'+str(time.monotonic_ns()))
seen.add(r['headers']['X-Instance-Id'])
if alias in seen and len(seen)>=2:
break
except Failure:
errors+=1
time.sleep(.05)
else:
raise AssertionError('HAProxy failed to discover moved API')
assert message in history(c,b,chat)
report={'result':'PASS','container':target,'instance':alias,'old_ip':old_ip,'new_ip':new_ip,
'discovery_seconds':round(time.monotonic()-start,3),'failed_attempts':errors,
'observed_instances':sorted(seen),'existing_session_and_confirmed_message':'PASS'}
(ROOT/'evidence/dns-change.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Dependency failure and recovery; only this lab's services are controlled."""
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client, Failure
c=Client(timeout=8)
a=c.user('ready')
compose=[str(ROOT/'scripts/compose.sh')]
def cmd(*args):
return subprocess.check_output(args,text=True,stderr=subprocess.DEVNULL).strip()
api=cmd(*compose,'ps','-q','api').splitlines()
def probe(container,path):
code='import urllib.request,urllib.error;\ntry: r=urllib.request.urlopen("http://127.0.0.1:8080'+path+'",timeout=7)\nexcept urllib.error.HTTPError as e: r=e\nprint(r.code)'
return int(cmd('docker','exec',container,'python','-c',code))
report={}
try:
cmd(*compose,'stop','postgres')
report['postgres_stopped']=[{'container':x,'live':probe(x,'/health/live'),'ready':probe(x,'/health/ready')} for x in api]
assert all(x['live']==200 and x['ready']==503 for x in report['postgres_stopped'])
finally:
cmd(*compose,'start','postgres')
for _ in range(60):
try:
c.call('GET','/api/v1/users/me',actor=a,schema='User')
break
except Failure:
time.sleep(.5)
else:
raise AssertionError('PostgreSQL/session failed to recover')
try:
cmd(*compose,'stop','redis')
report['redis_stopped']=[{'container':x,'ready':probe(x,'/health/ready')} for x in api]
assert all(x['ready']==200 for x in report['redis_stopped'])
c.call('GET','/api/v1/users/me',actor=a,schema='User')
report['redis_optional_profile_fallback']=200
finally:
cmd(*compose,'start','redis')
report['result']='PASS'
(ROOT/'evidence/readiness.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
"""Black-box synthetic tests and measured fault experiments; no credentials saved."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import importlib.util
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
from urllib.parse import quote
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure
from resilience import history
COMPOSE = [str(ROOT / 'scripts/compose.sh')]
BASE = os.getenv('BASE_URL', 'http://localhost:8080')
def cmd(*args):
return subprocess.check_output(args, cwd=ROOT, text=True, stderr=subprocess.DEVNULL).strip()
def ids():
return cmd(*COMPOSE, 'ps', '-q', 'api').splitlines()
def alias(container):
return cmd('docker', 'exec', container, 'python', '-c',
'import urllib.request; r=urllib.request.urlopen("http://127.0.0.1:8080/health/ready",timeout=2); print(r.headers["X-Instance-Id"])')
def wait_two(c, actor):
deadline = time.monotonic()+45
seen = set()
while time.monotonic()<deadline:
try:
for container in ids():
alias(container)
seen.add(c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['headers']['X-Instance-Id'])
if len(ids())==2 and len(seen)>=2:
return sorted(seen)
except Exception:
pass
time.sleep(.2)
raise AssertionError('Two ready API processes not observed through LB')
def idempotency():
c = Client(BASE)
alice, bob, eve, chat = c.bootstrap()
observed = wait_two(c, alice)
key = uuid.uuid4().hex
barrier = threading.Barrier(24)
def repeat(_):
local = Client(BASE)
barrier.wait()
return local.message(alice, chat, 'parallel synthetic', key)
with ThreadPoolExecutor(max_workers=24) as pool:
results = list(pool.map(repeat, range(24)))
message = results[0]['json']
assert all(r['json']==message and r['status']==201 for r in results)
parallel_instances = sorted({r['headers']['X-Instance-Id'] for r in results})
assert len(parallel_instances)==2
assert c.message(alice, chat, 'parallel synthetic', key)['json']==message
path = '/api/v1/chats/'+chat['id']+'/messages'
c.call('POST', path, 409, actor=alice, body={'text':'changed'}, headers={'Idempotency-Key':key})
for invalid in ('', 'space key', 'a'*129, 'invalid!' ):
c.call('POST', path, 400, actor=alice, body={'text':'invalid'}, headers={'Idempotency-Key':invalid})
c.call('POST', path, 400, actor=alice, body={'text':'missing'})
c.call('POST', path, 404, actor=eve, body={'text':'parallel synthetic'}, headers={'Idempotency-Key':key})
bob_message = c.message(bob, chat, 'parallel synthetic', key)['json']
assert bob_message['id'] != message['id']
other_chat = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Other scope','member_ids':[alice['id']]},schema='Chat')['json']
assert c.message(alice, other_chat, 'parallel synthetic', key)['json']['id']!=message['id']
# Simulate age >24h without changing application/host clock.
cmd(*COMPOSE, 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c',
"UPDATE message_requests SET created_at=NOW()-INTERVAL '25 hours' WHERE key='"+key+"'")
assert c.message(alice, chat, 'parallel synthetic', key)['json']==message
reader_instances=set()
for _ in range(12):
page=c.call('GET',path,actor=bob,schema='MessagePage')
assert message in page['json']['items']
assert sum(m['id']==message['id'] for m in page['json']['items'])==1
reader_instances.add(page['headers']['X-Instance-Id'])
assert len(reader_instances)==2
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('POST',path,401,actor=alice,body={'text':'parallel synthetic'},headers={'Idempotency-Key':key})
return {'result':'PASS','parallel_requests':24,'parallel_instances':parallel_instances,
'session_instances':observed,'reader_instances':sorted(reader_instances),
'same_message':True,'history_copies':1,'different_body':409,
'scope_user_and_chat':'PASS','aged_25h_replay':'PASS','revoked_replay':401,'outsider_replay':404}
def experiment(mode, target_index, duration):
c = Client(BASE, timeout=2)
alice, bob, eve, chat = c.bootstrap()
instances = wait_two(c, alice)
before=c.message(alice,chat,'confirmed before experiment')['json']
containers=sorted(ids())
target=containers[target_index]
target_alias=alias(target)
samples=[]
lock=threading.Lock()
ready=threading.Barrier(5)
start=time.monotonic()
stop_event=threading.Event()
resources=[]
def sample_resources():
while not stop_event.is_set():
try:
running=cmd(*COMPOSE,'ps','-q').splitlines()
lines=cmd('docker','stats','--no-stream','--format','{{json .}}',*running)
resources.append({'offset_seconds':round(time.monotonic()-start,3),
'containers':[json.loads(x) for x in lines.splitlines()]})
except Exception:
pass
stop_event.wait(1)
def worker(i):
local=Client(BASE,timeout=2)
ready.wait()
while not stop_event.is_set() and time.monotonic()-start < 120:
key=uuid.uuid4().hex
text='experiment-'+key
t=time.monotonic()
try:
result=local.message(alice,chat,text,key)
message=result['json']
ok=True
except Failure:
message=None
ok=False
done=time.monotonic()
with lock:
samples.append((t,done,ok,message))
sampler=threading.Thread(target=sample_resources)
sampler.start()
with ThreadPoolExecutor(max_workers=4) as pool:
futures=[pool.submit(worker,i) for i in range(4)]
ready.wait()
start=time.monotonic()
time.sleep(2) # measured pre-fault warm section
action_started=time.monotonic()
if mode=='failover':
env=dict(os.environ,TARGET_INSTANCE_ID=target_alias)
hook=subprocess.run([str(ROOT/'scripts/stop-one.sh')],env=env,capture_output=True,text=True,check=True)
action_events={'target_container':target,'target_instance':target_alias,'hook_output':hook.stdout.strip()}
inspect=json.loads(cmd('docker','inspect',target))[0]
assert inspect['State']['Running'] is False
assert len(ids())==1
action_events['target_running_after_hook']=False
action_finished=time.monotonic()
while time.monotonic()-start<duration:
time.sleep(.1)
else:
spec=importlib.util.spec_from_file_location('rolling',ROOT/'scripts/rolling-update.py')
mod=importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
action_events={'replacements':mod.rolling_update()}
action_finished=time.monotonic()
time.sleep(3)
stop_event.set()
for future in futures:
future.result()
sampler.join()
elapsed=time.monotonic()-start
successes=[s for s in samples if s[2]]
errors=len(samples)-len(successes)
confirmed=[s[3] for s in successes]+[before]
# Read all pages with the original session, verify every acknowledged object.
actual=history(c,bob,chat)
actual_by_id={m['id']:m for m in actual}
assert all(actual_by_id.get(m['id'])==m for m in confirmed)
assert len(actual)==len(actual_by_id)
assert len({m['text'] for m in actual})==len(actual)
after=[s for s in successes if s[0]>=action_finished]
assert after
recovery=after[0][1]-action_started
if mode=='failover':
assert recovery<=10
lat=sorted((s[1]-s[0])*1000 for s in successes)
pct=lambda p:round(lat[max(0,math.ceil(len(lat)*p)-1)],3)
report={'mode':mode,'result':'PASS','instances_before':instances,'duration_seconds':round(elapsed,3),
'concurrency':4,'successful_requests':len(successes),'errors':errors,
'error_ratio':round(errors/len(samples),6),'successful_rps':round(len(successes)/elapsed,3),
'successful_latency_ms':{'p50':pct(.5),'p95':pct(.95),'p99':pct(.99)},
'first_success_after_action_seconds':round(recovery,3),
'action_duration_seconds':round(action_finished-action_started,3),
'successful_requests_started_during_action':sum(action_started <= s[0] <= action_finished for s in successes),
'max_gap_between_successful_writes_seconds':round(max(b[1]-a[1] for a,b in zip(sorted(successes,key=lambda s:s[1]), sorted(successes,key=lambda s:s[1])[1:])),3),
'confirmed_checked':len(confirmed),'lost_confirmed':0,'read_write_original_session':'PASS',
'action':action_events,'resources':resources,
'method':'4 closed-loop writers through LB; errors counted, no retry; full history after action. Recovery includes hook duration and next fresh write.'}
if mode=='failover':
cmd(str(ROOT/'scripts/restore.sh'))
report['instances_after_restore']=wait_two(c,alice)
return report
if __name__=='__main__':
parser=argparse.ArgumentParser()
parser.add_argument('mode',choices=['idempotency','failover','rolling'])
parser.add_argument('--target-index',type=int,default=0,choices=[0,1])
parser.add_argument('--duration',type=float,default=15)
parser.add_argument('--output',required=True)
args=parser.parse_args()
report=idempotency() if args.mode=='idempotency' else experiment(args.mode,args.target_index,args.duration)
report['recorded_at_utc']=__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()
Path(args.output).write_text(json.dumps(report,indent=2,ensure_ascii=False)+'\n')
print(json.dumps({k:v for k,v in report.items() if k!='resources'},indent=2,ensure_ascii=False))
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Regression: blocking boundaries must execute off the ASGI event-loop thread.
Run inside the API image; no DB queries, external clients or extra dependencies.
"""
import asyncio
from collections import defaultdict
from contextlib import ExitStack
from datetime import datetime, timezone
import json
import threading
import unittest
from unittest.mock import patch
from uuid import UUID
from psycopg import OperationalError
from src import main
USER_ID = '11111111-1111-4111-8111-111111111111'
CHAT_ID = '22222222-2222-4222-8222-222222222222'
USER = {'id': USER_ID, 'username': 'synthetic', 'display_name': 'Synthetic', 'created_at': '2026-11-06T00:00:00Z'}
CHAT = {'id': CHAT_ID, 'title': 'Synthetic', 'member_ids': [USER_ID], 'created_at': USER['created_at']}
MESSAGE = {'id': '33333333-3333-4333-8333-333333333333', 'chat_id': CHAT_ID, 'sender_id': USER_ID, 'text': 'test', 'created_at': USER['created_at']}
async def request(method, path, body=None, headers=None):
encoded = json.dumps(body).encode() if body is not None else b''
request_headers = {'host': 'test', 'authorization': 'Bearer ' + 'a'*43}
if body is not None:
request_headers['content-type'] = 'application/json'
request_headers.update(headers or {})
scope = {'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.4'},
'http_version': '1.1', 'method': method, 'scheme': 'http',
'path': path, 'raw_path': path.encode(), 'query_string': b'',
'root_path': '', 'server': ('test', 80), 'client': ('127.0.0.1', 1234),
'headers': [(k.encode(), v.encode()) for k, v in request_headers.items()]}
sent = []
received = False
async def receive():
nonlocal received
if not received:
received = True
return {'type': 'http.request', 'body': encoded, 'more_body': False}
await asyncio.Event().wait()
async def send(message):
sent.append(message)
await asyncio.wait_for(main.app(scope, receive, send), timeout=5)
start = next(m for m in sent if m['type'] == 'http.response.start')
data = b''.join(m.get('body', b'') for m in sent if m['type'] == 'http.response.body')
return start['status'], dict(start['headers']), json.loads(data) if data else None
class EventLoopTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.loop_thread = threading.get_ident()
self.calls = defaultdict(list)
self.stack = ExitStack()
self.addCleanup(self.stack.close)
def blocking(self, name, result=None, error=None):
def spy(*args, **kwargs):
self.calls[name].append(threading.get_ident())
if error:
raise error
return result
self.stack.enter_context(patch.object(main, name, side_effect=spy))
def assert_off_loop(self, *names):
for name in names:
self.assertTrue(self.calls[name], name + ' was not exercised')
self.assertNotIn(self.loop_thread, self.calls[name], name + ' blocked the event loop')
async def test_registration_hash_and_insert(self):
self.blocking('hash_password', 'synthetic-hash')
self.blocking('insert_user', USER)
status, headers, _ = await request('POST', '/api/v1/users',
{'username': 'synthetic', 'display_name': 'Synthetic', 'password': 'synthetic-password'})
self.assertEqual(status, 201)
self.assertIn(b'x-instance-id', headers)
self.assert_off_loop('hash_password', 'insert_user')
async def test_login_lookup_verify_and_session(self):
import base64
row = {**USER, 'id': UUID(USER_ID), 'password_hash': 'synthetic-hash', 'created_at': datetime.now(timezone.utc)}
self.blocking('find_user_by_username', row)
self.blocking('verify_password', True)
self.blocking('create_session')
basic = base64.b64encode(b'synthetic:synthetic-password').decode()
status, _, _ = await request('POST', '/api/v1/auth/sessions', headers={'authorization': 'Basic '+basic})
self.assertEqual(status, 201)
self.assert_off_loop('find_user_by_username', 'verify_password', 'create_session')
async def test_chat_session_and_transaction(self):
self.blocking('find_session_user_cached', USER)
self.blocking('insert_chat', CHAT)
status, _, _ = await request('POST', '/api/v1/chats', {'title': 'Synthetic', 'member_ids': [USER_ID]})
self.assertEqual(status, 201)
self.assert_off_loop('find_session_user_cached', 'insert_chat')
async def test_message_session_access_and_atomic_insert(self):
self.blocking('find_session_user_cached', USER)
self.blocking('find_chat', CHAT)
self.blocking('insert_message', MESSAGE)
status, _, _ = await request('POST', '/api/v1/chats/'+CHAT_ID+'/messages', {'text': 'test'}, {'idempotency-key': 'test-key'})
self.assertEqual(status, 201)
self.assert_off_loop('find_session_user_cached', 'find_chat', 'insert_message')
async def test_lifecycle_pool_open_and_close(self):
self.blocking('open_database')
self.blocking('close_database')
await main.app.router.startup()
await main.app.router.shutdown()
self.assert_off_loop('open_database', 'close_database')
async def test_openapi_does_not_read_file_in_request(self):
with patch('pathlib.Path.read_text', side_effect=AssertionError('Disk I/O during HTTP request')):
status, _, data = await request('GET', '/openapi.json')
self.assertEqual(status, 200)
self.assertEqual(data['info']['version'], '1.3.0')
async def test_thread_exception_preserves_error_contract(self):
self.blocking('hash_password', 'synthetic-hash')
self.blocking('insert_user', error=OperationalError('synthetic outage'))
status, headers, data = await request('POST', '/api/v1/users',
{'username': 'synthetic', 'display_name': 'Synthetic', 'password': 'synthetic-password'})
self.assertEqual(status, 503)
self.assertEqual(data['error']['code'], 'unavailable')
self.assertEqual(data['error']['request_id'], headers[b'x-request-id'].decode())
self.assert_off_loop('hash_password', 'insert_user')
if __name__ == '__main__':
unittest.main(verbosity=2)