Lab2 grade 4: PostgreSQL, Redis sessions, Compose, student tests and evidence.

This commit is contained in:
2026-10-30 12:37:18 +03:00
parent 65003b6119
commit 950ff93573
34 changed files with 2252 additions and 41 deletions
+11
View File
@@ -0,0 +1,11 @@
# Собственные проверки (lab2)
Требуется уже запущенный стенд (`compose up`).
```sh
# из корня репозитория, внутри контейнера python или локально:
cd student-tests
BASE_URL=http://127.0.0.1:8080 python run_all.py
```
Для проверки expiry поднимите API с `SESSION_TTL_SECONDS=2` и повторите `test_sessions`.
+64
View File
@@ -0,0 +1,64 @@
"""Minimal HTTP helpers for student tests (stdlib only)."""
from __future__ import annotations
import base64
import json
import os
import urllib.error
import urllib.request
import uuid
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
def call(method, path, expected=None, body=None, token=None, headers=None, raw=None):
h = {"Accept": "application/json"}
if token:
h["Authorization"] = "Bearer " + token
if body is not None:
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
h.update(headers or {})
req = urllib.request.Request(BASE_URL + path, data=raw, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=30)
except urllib.error.HTTPError as err:
resp = err
data = resp.read()
status = resp.code
if expected is not None:
assert status == expected, (
f"{method} {path}: expected {expected}, got {status}: {data[:200]!r}"
)
payload = None
ctype = resp.headers.get_content_type()
if ctype == "application/json" and data:
payload = json.loads(data.decode("utf-8"))
assert resp.headers.get("X-Request-Id"), "missing X-Request-Id"
return {"status": status, "headers": resp.headers, "json": payload, "bytes": data}
def register(label: str):
username = f"st_{label}_{uuid.uuid4().hex[:10]}"
password = "T3st-" + uuid.uuid4().hex
body = {
"username": username,
"display_name": f"Student {label}",
"password": password,
}
user = call("POST", "/api/v1/users", 201, body=body)["json"]
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
session = call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "Basic " + credential},
)["json"]
return {
"id": user["id"],
"user": user,
"token": session["token"],
"registration": body,
}
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Run all student tests against a live API (BASE_URL)."""
from __future__ import annotations
import importlib
import sys
import traceback
MODULES = [
"test_api",
"test_concurrency",
"test_sessions",
"test_deps",
]
def main() -> int:
failed = 0
passed = 0
for name in MODULES:
mod = importlib.import_module(name)
tests = [getattr(mod, n) for n in dir(mod) if n.startswith("test_")]
for fn in tests:
label = f"{name}.{fn.__name__}"
try:
fn()
print("OK", label)
passed += 1
except Exception as exc:
failed += 1
print("FAIL", label, ":", exc)
traceback.print_exc()
print(f"Summary: {passed} passed, {failed} failed")
return 1 if failed else 0
if __name__ == "__main__":
sys.path.insert(0, ".")
raise SystemExit(main())
+159
View File
@@ -0,0 +1,159 @@
"""Grade 3/4 API checks: auth, conflict, X-User-Id ignored, logout."""
from __future__ import annotations
import base64
import time
import uuid
from helpers import call, register
def test_username_conflict():
a = register("conflict")
body = dict(a["registration"])
call("POST", "/api/v1/users", 409, body=body)
def test_wrong_password():
a = register("wrongpw")
bad = base64.b64encode(
(a["registration"]["username"] + ":wrong-password-xx").encode()
).decode()
resp = call(
"POST",
"/api/v1/auth/sessions",
401,
headers={"Authorization": "Basic " + bad},
)
assert resp["headers"].get("WWW-Authenticate", "").lower().startswith("basic")
def test_x_user_id_ignored():
a = register("xu")
b = register("xv")
me = call(
"GET",
"/api/v1/users/me",
200,
token=a["token"],
headers={"X-User-Id": b["id"]},
)["json"]
assert me["id"] == a["id"]
def test_basic_on_business_rejected():
a = register("basicbiz")
cred = base64.b64encode(
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
).decode()
call(
"GET",
"/api/v1/users/me",
401,
headers={"Authorization": "Basic " + cred},
)
def test_logout_revokes():
a = register("logout")
call("DELETE", "/api/v1/auth/sessions/current", 204, token=a["token"])
call("GET", "/api/v1/users/me", 401, token=a["token"])
def test_chat_requires_caller_member():
a = register("owner")
b = register("peer")
call(
"POST",
"/api/v1/chats",
400,
token=a["token"],
body={"title": "no me", "member_ids": [b["id"]]},
)
def test_unknown_member_rolls_back():
a = register("atom")
fake = str(uuid.uuid4())
call(
"POST",
"/api/v1/chats",
400,
token=a["token"],
body={"title": "bad", "member_ids": [a["id"], fake]},
)
def test_whitespace_only_password_rejected():
# Maintainer remark: required strings must not be whitespace-only.
body = {
"username": "ws_" + uuid.uuid4().hex[:10],
"display_name": "Spaces",
"password": " " * 12,
}
call("POST", "/api/v1/users", 400, body=body)
def test_nul_in_text_rejected():
a = register("nul")
peer = register("nulb")
chat = call(
"POST",
"/api/v1/chats",
201,
token=a["token"],
body={"title": "nul-chat", "member_ids": [a["id"], peer["id"]]},
)["json"]
call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
400,
token=a["token"],
body={"text": "hello\u0000world"},
)
def test_login_rejects_json_body():
a = register("bodylogin")
cred = base64.b64encode(
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
).decode()
call(
"POST",
"/api/v1/auth/sessions",
400,
body={"unexpected": True},
headers={"Authorization": "Basic " + cred},
)
def test_invalid_basic_encoding_is_401():
# Maintainer remark: malformed Basic must be 401, not 500.
call(
"POST",
"/api/v1/auth/sessions",
401,
headers={"Authorization": "Basic " + base64.b64encode("é".encode()).decode()},
)
def test_unsupported_media_type():
a = register("ctype")
peer = register("ctypeb")
chat = call(
"POST",
"/api/v1/chats",
201,
token=a["token"],
body={"title": "ctype", "member_ids": [a["id"], peer["id"]]},
)["json"]
raw = b'{"text":"x"}'
call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
415,
token=a["token"],
raw=raw,
headers={"Content-Type": "text/plain"},
)
+66
View File
@@ -0,0 +1,66 @@
"""Concurrent registration race and parallel messages."""
from __future__ import annotations
import concurrent.futures
import uuid
from helpers import BASE_URL, call, register
def test_parallel_messages_unique():
a = register("par")
b = register("parb")
chat = call(
"POST",
"/api/v1/chats",
201,
token=a["token"],
body={"title": "parallel", "member_ids": [a["id"], b["id"]]},
)["json"]
def send(i: int):
return call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
201,
token=a["token"],
body={"text": f"msg-{i}"},
)["json"]["id"]
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
ids = list(pool.map(send, range(100)))
assert len(ids) == len(set(ids)) == 100
def test_username_race_one_winner():
username = "race_" + uuid.uuid4().hex[:12]
password = "T3st-" + uuid.uuid4().hex
body = {
"username": username,
"display_name": "Race",
"password": password,
}
def attempt(_):
import json
import urllib.error
import urllib.request
raw = json.dumps(body).encode("utf-8")
req = urllib.request.Request(
BASE_URL + "/api/v1/users",
data=raw,
headers={"Content-Type": "application/json", "Accept": "application/json"},
method="POST",
)
try:
resp = urllib.request.urlopen(req, timeout=30)
except urllib.error.HTTPError as err:
resp = err
return resp.code
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
codes = list(pool.map(attempt, range(8)))
assert codes.count(201) == 1, codes
assert codes.count(409) == 7, codes
+68
View File
@@ -0,0 +1,68 @@
"""Dependency failure checks (Redis/Postgres). Optional: RUN_DEPS_TEST=1."""
from __future__ import annotations
import os
import subprocess
import time
from helpers import BASE_URL, call, register
def _compose(*args: str) -> None:
cmd = ["docker", "compose", "--env-file", ".env", *args]
subprocess.check_call(cmd, cwd=os.path.join(os.path.dirname(__file__), ".."))
def _wait_ready(timeout_s: int = 60) -> None:
deadline = time.time() + timeout_s
while time.time() < deadline:
try:
if call("GET", "/health/ready")["status"] == 200:
return
except Exception:
pass
time.sleep(1)
raise AssertionError("stack did not become ready in time")
def test_redis_stop_returns_503_or_unready():
if os.environ.get("RUN_DEPS_TEST") != "1":
print("SKIP test_redis_stop_returns_503_or_unready (set RUN_DEPS_TEST=1)")
return
actor = register("deps")
_compose("stop", "redis")
time.sleep(2)
try:
ready = call("GET", "/health/ready")
assert ready["status"] == 503, ready["status"]
me = call("GET", "/api/v1/users/me", token=actor["token"])
assert me["status"] in (401, 503)
finally:
_compose("start", "redis")
_wait_ready()
def test_postgres_stop_returns_503():
# Maintainer remark (level 4): cover PostgreSQL unavailability like Redis.
if os.environ.get("RUN_DEPS_TEST") != "1":
print("SKIP test_postgres_stop_returns_503 (set RUN_DEPS_TEST=1)")
return
actor = register("deps_pg")
_compose("stop", "postgres")
time.sleep(2)
try:
ready = call("GET", "/health/ready")
assert ready["status"] == 503, ready["status"]
# Authenticated business path must fail fast as 503 (not hang / not 500).
me = call("GET", "/api/v1/users/me", token=actor["token"])
assert me["status"] == 503, me["status"]
hist = call(
"GET",
f"/api/v1/chats/{actor['id']}/messages",
token=actor["token"],
)
assert hist["status"] in (400, 404, 503), hist["status"]
finally:
_compose("start", "postgres")
_wait_ready(90)
+34
View File
@@ -0,0 +1,34 @@
"""Session expiry (short TTL) — run against stack with SESSION_TTL_SECONDS=2."""
from __future__ import annotations
import base64
import os
import time
from helpers import call, register
def test_session_expiry_if_short_ttl():
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
if ttl > 5:
print("SKIP expiry: SESSION_TTL_SECONDS=%s (need <=5 for this test)" % ttl)
return
a = register("expire")
time.sleep(ttl + 1.5)
call("GET", "/api/v1/users/me", 401, token=a["token"])
def test_login_after_register():
a = register("relogin")
cred = base64.b64encode(
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
).decode()
session = call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "Basic " + cred},
)["json"]
assert session["token_type"] == "Bearer"
assert session["user"]["id"] == a["id"]