reworked
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def base_url():
|
||||
return os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def live(base_url):
|
||||
c = Client(base_url, timeout=15)
|
||||
try:
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
except Failure as exc:
|
||||
pytest.skip("API is not ready: %s" % exc)
|
||||
return c
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Negative, pagination and auth tests for lab 2."""
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client
|
||||
|
||||
|
||||
PASSWORD = "Example-only-not-a-real-secret-123"
|
||||
|
||||
|
||||
def register(c: Client, username=None):
|
||||
username = username or ("u_" + uuid.uuid4().hex[:10])
|
||||
user = c.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
201,
|
||||
body={"username": username, "display_name": "Test User", "password": PASSWORD},
|
||||
schema="User",
|
||||
)["json"]
|
||||
return user
|
||||
|
||||
|
||||
def login(c: Client, username, password=PASSWORD):
|
||||
import base64
|
||||
|
||||
cred = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
session = c.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + cred},
|
||||
schema="Session",
|
||||
)["json"]
|
||||
return {"id": session["user"]["id"], "user": session["user"], "token": session["token"], "registration": {"username": username, "password": password}}
|
||||
|
||||
|
||||
def actor_of(c: Client, username=None):
|
||||
user = register(c, username)
|
||||
return login(c, user["username"])
|
||||
|
||||
|
||||
def test_malformed_json(live: Client):
|
||||
response = live.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
raw=b"{not-json",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert response["json"]["error"]["code"] == "invalid_request"
|
||||
assert response["headers"].get("X-Request-Id")
|
||||
|
||||
|
||||
def test_duplicate_username(live: Client):
|
||||
user = register(live, username="dup_" + uuid.uuid4().hex[:8])
|
||||
again = live.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
409,
|
||||
body={"username": user["username"], "display_name": "Other", "password": PASSWORD},
|
||||
)
|
||||
assert again["json"]["error"]["code"] == "conflict"
|
||||
|
||||
|
||||
def test_empty_message_rejected(live: Client):
|
||||
alice = actor_of(live)
|
||||
bob = actor_of(live)
|
||||
chat = live.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "t", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
response = live.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": " "},
|
||||
)
|
||||
assert response["status"] == 400
|
||||
|
||||
|
||||
def test_outsider_chat_is_404(live: Client):
|
||||
alice = actor_of(live)
|
||||
bob = actor_of(live)
|
||||
eve = actor_of(live)
|
||||
chat = live.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "secret", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
response = live.call("GET", "/api/v1/chats/" + chat["id"], 404, actor=eve)
|
||||
assert response["json"]["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
def test_message_pagination_multiple_pages(live: Client):
|
||||
alice = actor_of(live)
|
||||
bob = actor_of(live)
|
||||
chat = live.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "pages", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
created = []
|
||||
for idx in range(5):
|
||||
created.append(live.message(alice, chat, "m%s" % idx)["json"])
|
||||
collected = []
|
||||
cursor = None
|
||||
for _ in range(10):
|
||||
path = "/api/v1/chats/%s/messages?limit=2" % chat["id"]
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = live.call("GET", path, actor=bob, schema="MessagePage")["json"]
|
||||
collected.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
assert len(collected) == 5
|
||||
ordered = sorted(created, key=lambda x: (x["created_at"], x["id"]))
|
||||
assert collected == ordered
|
||||
|
||||
|
||||
def test_cursor_from_other_chat_rejected(live: Client):
|
||||
alice = actor_of(live)
|
||||
bob = actor_of(live)
|
||||
chat_a = live.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "a", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
chat_b = live.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "b", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
msg = live.message(alice, chat_a, "only in a")["json"]
|
||||
page = live.call(
|
||||
"GET",
|
||||
"/api/v1/chats/%s/messages?limit=1" % chat_a["id"],
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
assert page["items"][0]["id"] == msg["id"]
|
||||
cursor = page["next_cursor"]
|
||||
# If history is a single item, next_cursor is null; encode a foreign cursor via first page of A after a dummy extra message.
|
||||
if cursor is None:
|
||||
live.message(alice, chat_a, "second")
|
||||
page = live.call(
|
||||
"GET",
|
||||
"/api/v1/chats/%s/messages?limit=1" % chat_a["id"],
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
cursor = page["next_cursor"]
|
||||
response = live.call(
|
||||
"GET",
|
||||
"/api/v1/chats/%s/messages?limit=10&cursor=%s" % (chat_b["id"], quote(cursor, safe="")),
|
||||
400,
|
||||
actor=alice,
|
||||
)
|
||||
assert response["status"] == 400
|
||||
|
||||
|
||||
def test_x_user_id_does_not_authenticate(live: Client):
|
||||
alice = actor_of(live)
|
||||
live.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
|
||||
|
||||
|
||||
def test_wrong_password(live: Client):
|
||||
user = register(live)
|
||||
import base64
|
||||
|
||||
bad = base64.b64encode((user["username"] + ":wrong-password-xx").encode()).decode()
|
||||
live.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + bad})
|
||||
|
||||
|
||||
def test_logout(live: Client):
|
||||
alice = actor_of(live)
|
||||
live.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
live.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""10 clients × 10 messages = 100 unique messages."""
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from client import Client
|
||||
|
||||
from student_tests.test_api import actor_of
|
||||
|
||||
|
||||
def test_concurrent_messages(live: Client):
|
||||
users = [actor_of(live) for _ in range(10)]
|
||||
member_ids = [u["id"] for u in users]
|
||||
chat = live.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=users[0],
|
||||
body={"title": "load", "member_ids": member_ids},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
|
||||
errors = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker(user):
|
||||
local = Client(live.base, timeout=15)
|
||||
for _ in range(10):
|
||||
try:
|
||||
local.message(user, chat, uuid.uuid4().hex)
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
errors.append(str(exc))
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(u,)) for u in users]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=60)
|
||||
|
||||
assert not errors, "unexpected failures: %s" % errors[:5]
|
||||
page = live.call(
|
||||
"GET",
|
||||
"/api/v1/chats/%s/messages?limit=100" % chat["id"],
|
||||
actor=users[0],
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
ids = [item["id"] for item in page["items"]]
|
||||
assert len(ids) == len(set(ids)) == 100
|
||||
@@ -0,0 +1,17 @@
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from client import Client
|
||||
|
||||
|
||||
@pytest.mark.expiry
|
||||
def test_session_expires(live: Client):
|
||||
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
if os.environ.get("RUN_EXPIRY") != "1":
|
||||
pytest.skip("set RUN_EXPIRY=1 and SESSION_TTL_SECONDS<=3")
|
||||
assert ttl <= 3
|
||||
actor = live.user("ttl")
|
||||
live.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
time.sleep(ttl + 1.5)
|
||||
live.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Grade-4: username race and atomic chat rollback."""
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from client import Client
|
||||
|
||||
from student_tests.test_api import PASSWORD, actor_of
|
||||
|
||||
|
||||
def test_register_race(live: Client):
|
||||
username = "r_" + uuid.uuid4().hex[:12]
|
||||
body = {"username": username, "display_name": "Race", "password": PASSWORD}
|
||||
results = []
|
||||
|
||||
def once():
|
||||
local = Client(live.base, timeout=20)
|
||||
try:
|
||||
results.append(local.call("POST", "/api/v1/users", [201, 409], body=body)["status"])
|
||||
except Exception 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()
|
||||
assert results.count(201) == 1, results
|
||||
assert results.count(409) == 15, results
|
||||
|
||||
|
||||
def test_chat_rollback(live: Client):
|
||||
alice = actor_of(live)
|
||||
before = live.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"]
|
||||
missing = str(uuid.uuid4())
|
||||
live.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"title": "rollback-should-not-exist", "member_ids": [alice["id"], missing]},
|
||||
)
|
||||
after = live.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]["items"]
|
||||
assert len(after) == len(before)
|
||||
assert all(x["title"] != "rollback-should-not-exist" for x in after)
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Dependency failure and Redis restart (AOF + cache rebuild)."""
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from client import Client, Failure
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
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 AssertionError("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 AssertionError("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:
|
||||
schema = "Health" if expected == 200 and path.startswith("/health") else None
|
||||
c.call("GET", path, expected, actor=actor, schema=schema)
|
||||
return
|
||||
except Failure as exc:
|
||||
last = exc
|
||||
time.sleep(0.4)
|
||||
raise AssertionError("did not observe %s for %s: %s" % (expected, path, last))
|
||||
|
||||
|
||||
@pytest.mark.infra
|
||||
def test_redis_and_postgres_unavailable(live: Client):
|
||||
if os.environ.get("RUN_INFRA") != "1":
|
||||
pytest.skip("set RUN_INFRA=1 to stop compose services")
|
||||
alice = live.user("infra")
|
||||
compose("stop", "redis")
|
||||
wait_status(live, "/health/live", 200)
|
||||
wait_status(live, "/health/ready", 503)
|
||||
wait_status(live, "/api/v1/users/me", 503, actor=alice)
|
||||
compose("start", "redis")
|
||||
wait_ready(live)
|
||||
live.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
|
||||
compose("stop", "postgres")
|
||||
wait_status(live, "/health/live", 200)
|
||||
wait_status(live, "/health/ready", 503)
|
||||
compose("start", "postgres")
|
||||
wait_ready(live)
|
||||
live.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
|
||||
|
||||
@pytest.mark.infra
|
||||
def test_redis_restart_keeps_session_and_history(live: Client):
|
||||
if os.environ.get("RUN_INFRA") != "1":
|
||||
pytest.skip("set RUN_INFRA=1 to restart redis")
|
||||
alice, bob, _eve, chat = live.bootstrap()
|
||||
msg = live.message(alice, chat, "before-redis-restart")["json"]
|
||||
compose("restart", "redis")
|
||||
wait_ready(live)
|
||||
me = live.call("GET", "/api/v1/users/me", actor=alice, schema="User")["json"]
|
||||
assert me["id"] == alice["id"]
|
||||
page = live.call(
|
||||
"GET",
|
||||
"/api/v1/chats/%s/messages?limit=100" % chat["id"],
|
||||
actor=bob,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
assert any(m["id"] == msg["id"] for m in page["items"])
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Track 1: cache consistency — stampede, stale read, read-after-write."""
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from client import Client
|
||||
|
||||
|
||||
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_read_after_write(live: Client):
|
||||
alice, bob, _eve, chat = live.bootstrap()
|
||||
_lab_flags(live, {"invalidate": True, "singleflight": True, "reset_sql": True})
|
||||
first = live.message(alice, chat, "raw-visible-" + uuid.uuid4().hex)["json"]
|
||||
page = live.call(
|
||||
"GET",
|
||||
"/api/v1/chats/%s/messages?limit=100" % chat["id"],
|
||||
actor=bob,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
assert any(m["id"] == first["id"] for m in page["items"])
|
||||
|
||||
|
||||
def test_stale_without_invalidation_then_fixed(live: Client):
|
||||
alice, bob, _eve, chat = live.bootstrap()
|
||||
path = "/api/v1/chats/%s/messages?limit=50" % chat["id"]
|
||||
live.call("GET", path, actor=alice, schema="MessagePage")
|
||||
_lab_flags(live, {"invalidate": False, "singleflight": True})
|
||||
try:
|
||||
stale_text = "stale-probe-" + uuid.uuid4().hex
|
||||
live.message(alice, chat, stale_text)
|
||||
page = live.call("GET", path, actor=bob, schema="MessagePage")["json"]
|
||||
assert all(m["text"] != stale_text for m in page["items"])
|
||||
finally:
|
||||
_lab_flags(live, {"invalidate": True})
|
||||
fresh_text = "fresh-probe-" + uuid.uuid4().hex
|
||||
live.message(alice, chat, fresh_text)
|
||||
page2 = live.call("GET", path, actor=bob, schema="MessagePage")["json"]
|
||||
assert any(m["text"] == fresh_text for m in page2["items"])
|
||||
|
||||
|
||||
def test_stampede_singleflight_reduces_sql(live: Client):
|
||||
alice, _bob, _eve, chat = live.bootstrap()
|
||||
live.message(alice, chat, "stampede-seed")
|
||||
path = "/api/v1/chats/%s/messages?limit=50" % chat["id"]
|
||||
|
||||
def burst(n=24):
|
||||
barrier = threading.Barrier(n)
|
||||
|
||||
def one(_i):
|
||||
local = Client(live.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)))
|
||||
|
||||
try:
|
||||
_lab_flags(live, {"singleflight": False, "invalidate": True, "reset_sql": True, "delay_ms": 250})
|
||||
live.message(alice, chat, "miss-" + uuid.uuid4().hex)
|
||||
_lab_flags(live, {"reset_sql": True, "singleflight": False, "delay_ms": 250})
|
||||
burst()
|
||||
unprotected = _lab_metrics(live)["history_sql"]
|
||||
|
||||
_lab_flags(live, {"singleflight": True, "reset_sql": True, "delay_ms": 250})
|
||||
live.message(alice, chat, "miss2-" + uuid.uuid4().hex)
|
||||
_lab_flags(live, {"reset_sql": True, "singleflight": True, "delay_ms": 250})
|
||||
burst()
|
||||
protected = _lab_metrics(live)["history_sql"]
|
||||
finally:
|
||||
_lab_flags(live, {"invalidate": True, "singleflight": True, "delay_ms": 0})
|
||||
|
||||
print(json.dumps({"stampede_sql_without_singleflight": unprotected, "stampede_sql_with_singleflight": protected}))
|
||||
assert unprotected >= 8, unprotected
|
||||
assert protected < unprotected, (protected, unprotected)
|
||||
assert protected <= 4, protected
|
||||
Reference in New Issue
Block a user