finished
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / application (pull_request) Canceled after 0s

This commit is contained in:
2026-11-06 20:40:12 +03:00
parent 65003b6119
commit 7329d94740
31 changed files with 1662 additions and 4 deletions
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "student-tests"))
os.environ["RUN_EXPIRY"] = "1"
from run import test_expiry # noqa: E402
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, run # noqa: E402
def main():
c = Client(os.environ.get("BASE_URL", "http://localhost:8080"))
test_expiry(c)
print("PASS: session expiry")
if __name__ == "__main__":
run(main)
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Dependency failure and Redis-only restart checks (Docker Compose)."""
import json
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
def compose(*args):
env_file = ROOT / ".env"
cmd = ["docker", "compose"]
if env_file.is_file():
cmd.extend(["--env-file", str(env_file)])
cmd.extend(args)
proc = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True)
if proc.returncode != 0:
raise Failure("docker compose %s failed: %s" % (" ".join(args), (proc.stderr or "")[-500:]))
return proc
def wait_ready(c: Client, seconds=90):
deadline = time.monotonic() + seconds
last = None
while time.monotonic() < deadline:
try:
c.call("GET", "/health/ready", schema="Health")
return
except Failure as exc:
last = exc
time.sleep(0.5)
raise Failure("ready not restored: %s" % last)
def wait_status(c: Client, path, expected, seconds=30, actor=None):
deadline = time.monotonic() + seconds
last = None
while time.monotonic() < deadline:
try:
c.call("GET", path, expected, actor=actor, schema="Health" if expected == 200 and path.startswith("/health") else None)
return
except Failure as exc:
last = exc
time.sleep(0.4)
raise Failure("did not observe %s for %s: %s" % (expected, path, last))
def main():
base = os.environ.get("BASE_URL", "http://localhost:8080")
c = Client(base, timeout=3)
alice = c.user("infra")
compose("ps")
compose("stop", "redis")
wait_status(c, "/health/live", 200)
wait_status(c, "/health/ready", 503)
wait_status(c, "/api/v1/users/me", 503, actor=alice)
compose("start", "redis")
wait_ready(c)
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
compose("stop", "postgres")
wait_status(c, "/health/live", 200)
wait_status(c, "/health/ready", 503)
compose("start", "postgres")
wait_ready(c)
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
alice2, bob, _eve, chat = c.bootstrap()
msg = c.message(alice2, chat, "before-redis-restart")["json"]
compose("restart", "redis")
wait_ready(c)
me = c.call("GET", "/api/v1/users/me", actor=alice2, schema="User")["json"]
check(me["id"] == alice2["id"], "session lost after Redis restart despite AOF")
page = c.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=bob,
schema="MessagePage",
)["json"]
check(any(m["id"] == msg["id"] for m in page["items"]), "history not rebuilt after cache restart")
print(json.dumps({"redis_restart": "session+history ok", "db_or_redis_down": "503"}, ensure_ascii=False))
print("PASS: infra unavailability and redis restart")
if __name__ == "__main__":
run(main)
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""Student checks for grades 4 and 5 (track 1: cache consistency)."""
import base64
import json
import os
import sys
import threading
import time
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, Failure, check, run # noqa: E402
def _basic(username, password):
return "Basic " + base64.b64encode((username + ":" + password).encode()).decode()
def lab_metrics(c: Client):
return json.loads(c.call("GET", "/api/v1/_lab/metrics")["bytes"].decode())
def lab_flags(c: Client, body):
return json.loads(c.call("POST", "/api/v1/_lab/flags", 200, body=body)["bytes"].decode())
def test_wrong_password_and_x_user_id(c: Client):
actor = c.user("neg")
bad = _basic(actor["registration"]["username"], "wrong-password-xx")
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": bad})
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": actor["id"]})
c.call("GET", "/api/v1/users/me", 401)
def test_logout(c: Client):
actor = c.user("out")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
c.call("GET", "/api/v1/users/me", 401, actor=actor)
def test_register_race(c: Client):
username = "r_" + uuid.uuid4().hex[:12]
body = {
"username": username,
"display_name": "Race",
"password": "Example-only-not-a-real-secret-123",
}
results = []
def once():
local = Client(c.base)
try:
results.append(local.call("POST", "/api/v1/users", [201, 409], body=body)["status"])
except Failure as exc:
results.append(str(exc))
threads = [threading.Thread(target=once) for _ in range(16)]
for t in threads:
t.start()
for t in threads:
t.join()
created = results.count(201)
conflicted = results.count(409)
check(created == 1, "username race: expected exactly one 201, got %s" % results)
check(conflicted == 15, "username race: expected fifteen 409, got %s" % results)
def test_chat_rollback(c: Client):
alice = c.user("rb")
before = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"]
missing = str(uuid.uuid4())
c.call(
"POST",
"/api/v1/chats",
400,
actor=alice,
body={"title": "rollback-should-not-exist", "member_ids": [alice["id"], missing]},
)
after = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"]
check(len(after) == len(before), "composite chat create leaked a row after rollback")
check(all(x["title"] != "rollback-should-not-exist" for x in after), "rolled-back title became visible")
def test_read_after_write(c: Client):
alice, bob, _eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
lab_flags(c, {"invalidate": True, "singleflight": True, "reset_sql": True})
first = c.message(alice, chat, "raw-visible-" + uuid.uuid4().hex)["json"]
page = c.call("GET", path, actor=bob, schema="MessagePage")["json"]
check(any(m["id"] == first["id"] for m in page["items"]), "read-after-write lost the new message")
def test_stale_without_invalidation_then_fixed(c: Client):
alice, bob, _eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=50"
c.call("GET", path, actor=alice, schema="MessagePage")
lab_flags(c, {"invalidate": False, "singleflight": True})
stale_text = "stale-probe-" + uuid.uuid4().hex
c.message(alice, chat, stale_text)
page = c.call("GET", path, actor=bob, schema="MessagePage")["json"]
stale = all(m["text"] != stale_text for m in page["items"])
check(stale, "expected a stale cache read when invalidation is disabled")
lab_flags(c, {"invalidate": True})
fresh_text = "fresh-probe-" + uuid.uuid4().hex
c.message(alice, chat, fresh_text)
page2 = c.call("GET", path, actor=bob, schema="MessagePage")["json"]
check(any(m["text"] == fresh_text for m in page2["items"]), "invalidation did not restore read-after-write")
def test_stampede(c: Client):
alice, _bob, _eve, chat = c.bootstrap()
c.message(alice, chat, "stampede-seed")
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=50"
def burst(n=24):
barrier = threading.Barrier(n)
def one(_i):
local = Client(c.base)
barrier.wait()
return local.call("GET", path, actor=alice, schema="MessagePage")
with ThreadPoolExecutor(max_workers=n) as pool:
list(pool.map(one, range(n)))
lab_flags(c, {"singleflight": False, "invalidate": True, "reset_sql": True})
c.message(alice, chat, "miss-" + uuid.uuid4().hex)
lab_flags(c, {"reset_sql": True, "singleflight": False})
burst()
unprotected = lab_metrics(c)["history_sql"]
lab_flags(c, {"singleflight": True, "reset_sql": True})
c.message(alice, chat, "miss2-" + uuid.uuid4().hex)
lab_flags(c, {"reset_sql": True, "singleflight": True})
burst()
protected = lab_metrics(c)["history_sql"]
print(json.dumps({"stampede_sql_without_singleflight": unprotected, "stampede_sql_with_singleflight": protected}, ensure_ascii=False))
check(unprotected >= 8, "unprotected stampede did not generate enough SQL")
check(protected < unprotected, "singleflight did not reduce SQL during stampede")
check(protected <= 4, "singleflight still issued too many history SQL queries")
def test_expiry(c: Client):
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
check(ttl <= 3, "expiry test requires SESSION_TTL_SECONDS<=3 (recreate api with short TTL)")
actor = c.user("ttl")
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
time.sleep(ttl + 1.5)
c.call("GET", "/api/v1/users/me", 401, actor=actor)
def main():
base = os.environ.get("BASE_URL", "http://localhost:8080")
c = Client(base)
c.call("GET", "/health/live", schema="Health")
c.call("GET", "/health/ready", schema="Health")
tests = [
test_wrong_password_and_x_user_id,
test_logout,
test_register_race,
test_chat_rollback,
test_read_after_write,
test_stale_without_invalidation_then_fixed,
test_stampede,
]
if os.environ.get("RUN_EXPIRY") == "1":
tests.append(test_expiry)
try:
for fn in tests:
fn(c)
print("PASS", fn.__name__)
finally:
try:
lab_flags(c, {"invalidate": True, "singleflight": True})
except Exception:
pass
print("PASS: student grade 4/5 HTTP checks")
if __name__ == "__main__":
run(main)