forked from mtusi2026/mtusi2026lab2
lab2
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
"""Test: concurrent registration of the same username must produce exactly one 201 and one 409."""
|
||||
import base64
|
||||
import json
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def post_user(username: str, password: str):
|
||||
body = json.dumps({
|
||||
"username": username,
|
||||
"display_name": "Race Test",
|
||||
"password": password,
|
||||
}).encode()
|
||||
req = urllib.request.Request(
|
||||
BASE + "/api/v1/users",
|
||||
data=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read().decode()
|
||||
|
||||
|
||||
def main():
|
||||
username = "race_" + uuid.uuid4().hex[:8]
|
||||
password = "RaceTestPassword123"
|
||||
results = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker():
|
||||
status, body = post_user(username, password)
|
||||
with lock:
|
||||
results.append((status, body))
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(2)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
statuses = [s for s, _ in results]
|
||||
print("Statuses:", statuses)
|
||||
assert sorted(statuses) == [201, 409], f"expected [201, 409], got {statuses}"
|
||||
print("PASS: race registration — one 201, one 409")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Test: when Redis is down, protected endpoints return 503, not 500."""
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def call(method, path, headers=None):
|
||||
h = {"Accept": "application/json"}
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE + path, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status, resp.read().decode()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read().decode()
|
||||
|
||||
|
||||
def stop_redis():
|
||||
subprocess.run(["docker", "compose", "stop", "redis"], check=True, capture_output=True)
|
||||
|
||||
|
||||
def start_redis():
|
||||
subprocess.run(["docker", "compose", "start", "redis"], check=True, capture_output=True)
|
||||
# Ждём, пока Redis станет healthy
|
||||
for _ in range(30):
|
||||
p = subprocess.run(
|
||||
["docker", "inspect", "--format={{.State.Health.Status}}", "mtusi2026lab2-redis-1"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if p.stdout.strip() == "healthy":
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError("redis did not become healthy")
|
||||
|
||||
|
||||
def main():
|
||||
# Проверяем, что без токена всё ещё 401 (не 500)
|
||||
try:
|
||||
stop_redis()
|
||||
time.sleep(2)
|
||||
|
||||
# 1. Аноним не должен пройти (401, не 503 — токена нет)
|
||||
status, body = call("GET", "/api/v1/users/me")
|
||||
assert status == 401, f"anonymous request without token should be 401, got {status} {body}"
|
||||
print("Anonymous without token: 401 (correct)")
|
||||
|
||||
# 2. С фиктивным токеном — 503 (Redis недоступен), не 500
|
||||
status, body = call("GET", "/api/v1/users/me", headers={
|
||||
"Authorization": "Bearer faketoken12345",
|
||||
})
|
||||
assert status == 503, f"with fake token and Redis down should be 503, got {status} {body}"
|
||||
print("With token, Redis down: 503 (correct)")
|
||||
print("PASS: Redis unavailability handled correctly")
|
||||
finally:
|
||||
start_redis()
|
||||
print("Redis restarted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Test: session expires after SESSION_TTL_SECONDS."""
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
EXPECTED_TTL = 2 # секунды
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None):
|
||||
h = {"Accept": "application/json"}
|
||||
h.update(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status, json.loads(resp.read().decode() or "{}")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read().decode() or "{}")
|
||||
|
||||
|
||||
def main():
|
||||
# 1. Регистрируем пользователя
|
||||
username = "exp_" + uuid.uuid4().hex[:8]
|
||||
password = "ExpiryTestPass123"
|
||||
status, user = call("POST", "/api/v1/users", {
|
||||
"username": username,
|
||||
"display_name": "Expiry Test",
|
||||
"password": password,
|
||||
})
|
||||
assert status == 201, f"register failed: {status} {user}"
|
||||
|
||||
# 2. Логинимся
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
status, session = call("POST", "/api/v1/auth/sessions", headers={
|
||||
"Authorization": "Basic " + cred,
|
||||
})
|
||||
assert status == 201, f"login failed: {status} {session}"
|
||||
token = session["token"]
|
||||
print(f"Got token; waiting {EXPECTED_TTL + 2}s for expiry...")
|
||||
|
||||
# 3. Проверяем, что токен сразу работает
|
||||
status, _ = call("GET", "/api/v1/users/me", headers={
|
||||
"Authorization": "Bearer " + token,
|
||||
})
|
||||
assert status == 200, f"token should work immediately, got {status}"
|
||||
print("Token works immediately: OK")
|
||||
|
||||
# 4. Ждём больше TTL
|
||||
time.sleep(EXPECTED_TTL + 2)
|
||||
|
||||
# 5. Проверяем, что токен больше не работает
|
||||
status, body = call("GET", "/api/v1/users/me", headers={
|
||||
"Authorization": "Bearer " + token,
|
||||
})
|
||||
assert status == 401, f"expired token should give 401, got {status} {body}"
|
||||
print("Token rejected after TTL: OK")
|
||||
print("PASS: session expiry works")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user