forked from mtusi2026/mtusi2026lab2
lab2
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""Дополнения к публичному smoke. Не печатает и не сохраняет tokens."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--expiry', action='store_true', help='API must run with TTL=2')
|
||||
args = arguments('Student API checks', configure)
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
if args.expiry:
|
||||
time.sleep(2.2)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: short TTL expiry')
|
||||
return
|
||||
registration = {'username': 'race_' + uuid4().hex[:12], 'display_name': 'Гонка',
|
||||
'password': 'Synthetic-password-42'}
|
||||
# Для гонки регистрируем оба допустимых исхода через urllib.
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
def register(_):
|
||||
req = urllib.request.Request(c.base + '/api/v1/users',
|
||||
data=json.dumps(registration).encode(),
|
||||
headers={'Content-Type': 'application/json'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
|
||||
codes = list(executor.map(register, range(8)))
|
||||
check(codes.count(201) == 1 and codes.count(409) == 7, 'username race failed')
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'unknown member', 'member_ids': [alice['id'], str(uuid4())]})
|
||||
for body in [{'text': 'x', 'sender_id': eve['id']}, {'text': 4}, {'text': ' '}]:
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body=body)
|
||||
c.call('GET', path + '/messages?limit=true', 400, actor=alice)
|
||||
c.call('GET', path + '/messages?cursor=not-a-cursor', 400, actor=alice)
|
||||
for n in range(3):
|
||||
c.message(alice, chat, 'read-after-write ' + str(n))
|
||||
page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
from urllib.parse import quote
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' +
|
||||
quote(page['next_cursor'], safe=''), 400, actor=alice)
|
||||
history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(len(history) == 3 and history[-1]['text'] == 'read-after-write 2', 'read-after-write failed')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: registration race, invalid input, cursor scope, read-after-write, logout')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Проверка реального rollback после вставки чата и первого участника."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from uuid import uuid4
|
||||
import psycopg
|
||||
from src.config import DATABASE_URL
|
||||
from src.migrate import migrate
|
||||
|
||||
migrate()
|
||||
migrate() # Повтор миграции не создаёт дубликаты.
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
user = db.execute('SELECT id FROM users LIMIT 1').fetchone()
|
||||
assert user, 'Сначала выполните smoke, чтобы создать синтетического пользователя'
|
||||
chat = uuid4()
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat, 'rollback test'))
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, user[0]))
|
||||
# FK прерывает составную операцию ПОСЛЕ двух успешных INSERT.
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Expected foreign-key failure')
|
||||
assert db.execute('SELECT count(*) FROM chats WHERE id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM chat_members WHERE chat_id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM schema_migrations').fetchone()[0] == 1
|
||||
print('PASS: rollback of chat + members; migration reapplied twice')
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Проверяет отказ Redis/БД. Hook выбирает явно оператор, токен только в памяти."""
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--stop-cache', required=True)
|
||||
p.add_argument('--start-cache', required=True)
|
||||
p.add_argument('--stop-db', required=True)
|
||||
p.add_argument('--start-db', required=True)
|
||||
args = arguments('Dependency failures', configure)
|
||||
c = Client(args.base_url, timeout=8)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
def hook(path):
|
||||
subprocess.run([str(Path(path).resolve())], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=40)
|
||||
def wait():
|
||||
for _ in range(90):
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except AssertionError:
|
||||
time.sleep(.5)
|
||||
raise AssertionError('DB did not recover')
|
||||
result = {}
|
||||
try:
|
||||
hook(args.stop_cache)
|
||||
start = time.monotonic()
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
c.call('GET', '/api/v1/users/me', 401)
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
confirmed = c.message(alice, chat, 'Redis offline')['json']
|
||||
messages = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
|
||||
actor=bob, schema='MessagePage')['json']['items']
|
||||
check(confirmed in messages, 'read-after-write failed without Redis')
|
||||
result['redis_offline_scenario_seconds'] = time.monotonic() - start
|
||||
finally:
|
||||
hook(args.start_cache)
|
||||
# Тот же токен работает после восстановления Redis, logout сразу действует.
|
||||
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
try:
|
||||
hook(args.stop_db)
|
||||
start = time.monotonic()
|
||||
c.call('GET', '/health/ready', 503)
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
c.call('GET', '/api/v1/users/me', 503, actor=bob)
|
||||
c.call('GET', '/api/v1/users/me', 401)
|
||||
result['db_offline_scenario_seconds'] = time.monotonic() - start
|
||||
finally:
|
||||
hook(args.start_db)
|
||||
wait()
|
||||
c.call('GET', '/api/v1/users/me', actor=bob, schema='User')
|
||||
import json
|
||||
result['status'] = 'PASS'
|
||||
Path('evidence/dependency_failures.json').write_text(json.dumps(result, indent=2))
|
||||
print('PASS: Redis fallback + restart + logout; DB bounded 503 + recovery; anonymous rejected')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box grading evidence beyond the public smoke test."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def collect_messages(client, actor, chat, page_size=17):
|
||||
items = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit={page_size}"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Student negative, pagination and concurrency tests")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, outsider, chat = client.bootstrap()
|
||||
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
415,
|
||||
raw=b'{"username":"wrong_media","display_name":"Wrong"}',
|
||||
headers={"Content-Type": "text/plain"},
|
||||
)
|
||||
client.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": " \t"},
|
||||
)
|
||||
client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=outsider)
|
||||
|
||||
prefix = "race-" + uuid.uuid4().hex + "-"
|
||||
|
||||
def send(worker_id):
|
||||
local = Client(args.base_url, args.ca_file)
|
||||
return [
|
||||
local.message(alice, chat, f"{prefix}{worker_id}-{index}")["json"]
|
||||
for index in range(10)
|
||||
]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
created = [message for batch in pool.map(send, range(10)) for message in batch]
|
||||
|
||||
check(len(created) == 100, "not all concurrent requests succeeded")
|
||||
check(len({message["id"] for message in created}) == 100, "duplicate message ids returned")
|
||||
|
||||
history = collect_messages(client, bob, chat)
|
||||
concurrent_history = [message for message in history if message["text"].startswith(prefix)]
|
||||
check(len(concurrent_history) == 100, "history does not contain exactly 100 concurrent messages")
|
||||
check(len({message["id"] for message in concurrent_history}) == 100, "history contains duplicates")
|
||||
check(
|
||||
history == sorted(history, key=lambda message: (message["created_at"], uuid.UUID(message["id"]).int)),
|
||||
"multi-page history is out of order",
|
||||
)
|
||||
|
||||
print("PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination")
|
||||
print("PASS: 10 clients created exactly 100 unique messages")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Из lab1: SIGTERM. Для lab2 проверяем сохранность вместо потери состояния."""
|
||||
import json
|
||||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = "http://127.0.0.1:18080"
|
||||
|
||||
|
||||
def request(method, path, body=None, token=None, expected=200, extra_headers=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
headers.update(extra_headers or {})
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(req, timeout=2)
|
||||
except urllib.error.HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
payload = json.loads(response.read())
|
||||
if response.status != expected:
|
||||
raise AssertionError(f"expected {expected}, received {response.status}: {payload}")
|
||||
return payload
|
||||
|
||||
|
||||
def start_server():
|
||||
env = os.environ.copy()
|
||||
env["LOG_LEVEL"] = "WARNING"
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "18080", "--timeout-graceful-shutdown", "10"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise AssertionError("server exited during startup")
|
||||
try:
|
||||
request("GET", "/health/ready")
|
||||
return process
|
||||
except (OSError, urllib.error.URLError):
|
||||
time.sleep(0.1)
|
||||
process.kill()
|
||||
raise AssertionError("server did not become ready")
|
||||
|
||||
|
||||
def stop_server(process):
|
||||
started = time.monotonic()
|
||||
process.send_signal(signal.SIGTERM)
|
||||
process.wait(timeout=10)
|
||||
elapsed = time.monotonic() - started
|
||||
try:
|
||||
request("GET", "/health/live")
|
||||
except (OSError, urllib.error.URLError):
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("server still accepts requests after shutdown")
|
||||
return elapsed
|
||||
|
||||
|
||||
def main():
|
||||
username = "restart_" + uuid.uuid4().hex[:12]
|
||||
password = "Synthetic-password-42"
|
||||
first = start_server()
|
||||
try:
|
||||
user = request("POST", "/api/v1/users", {
|
||||
"username": username, "display_name": "До перезапуска", "password": password,
|
||||
}, expected=201)
|
||||
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
session = request("POST", "/api/v1/auth/sessions", expected=201,
|
||||
extra_headers={"Authorization": "Basic " + basic})
|
||||
request("GET", "/api/v1/users/me", token=session["token"])
|
||||
finally:
|
||||
elapsed = stop_server(first)
|
||||
second = start_server()
|
||||
try:
|
||||
restored = request("GET", "/api/v1/users/me", token=session["token"])
|
||||
assert restored == user, "User changed after API restart"
|
||||
finally:
|
||||
stop_server(second)
|
||||
print(f"PASS: SIGTERM completed in {elapsed:.3f}s (limit 10s); listener closed")
|
||||
print("PASS: user and existing Bearer session survived API process restart")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user