ЛР 3 — БПИ2303 — Щербаков — на 3

This commit is contained in:
2026-11-13 13:27:43 +03:00
parent 0ab3a341aa
commit fd086f679e
30 changed files with 1450 additions and 24 deletions
+107
View File
@@ -0,0 +1,107 @@
"""Own HTTP checks, separate from the unchanged public tests."""
import base64
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import sys
import unittest
from urllib.parse import quote
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client
class API(unittest.TestCase):
def setUp(self):
self.c = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
self.a, self.b, self.e, self.chat = self.c.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"]
def test_registration_validation(self):
body = dict(self.a["registration"], username="u_" + uuid4().hex[:16])
for password in ("short", "x" * 129, 123, None):
self.c.call("POST", "/api/v1/users", 400, body=dict(body, password=password))
self.c.call("POST", "/api/v1/users", 400, body=dict(body, extra=True))
def test_unicode_password_with_colon_and_max_length(self):
username = "u_" + uuid4().hex[:16]
password = "Я:🔐" + "б" * 125
body = {"username": username, "display_name": "Имя 👋", "password": password}
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
credential = base64.b64encode((username + ":" + password).encode()).decode()
result = self.c.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + credential}, schema="Session")["json"]
self.assertEqual(user, result["user"])
self.assertGreaterEqual(len(base64.urlsafe_b64decode(result["token"] + "=")), 32)
def test_bad_credentials_and_schemes(self):
for credential in ("Basic ***", "Bearer token", "", "Basic " + base64.b64encode(b"missing:wrong-password").decode()):
self.c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": credential})
self.c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": self.a["id"]})
def test_logout_only_revokes_current_session(self):
body = self.a["registration"]
credential = base64.b64encode((body["username"] + ":" + body["password"]).encode()).decode()
other = self.c.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + credential}, schema="Session")["json"]
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.a)
self.c.call("GET", "/api/v1/users/me", 401, actor=self.a)
self.c.call("GET", "/api/v1/users/me", actor={"token": other["token"]}, schema="User")
def test_chat_atomic_invalid_members(self):
before = self.c.call("GET", "/api/v1/chats?limit=100", actor=self.a, schema="ChatPage")["json"]
for members in ([self.a["id"], str(uuid4())], [self.a["id"], self.a["id"]], [self.b["id"]]):
self.c.call("POST", "/api/v1/chats", 400, actor=self.a, body={"title": "rollback", "member_ids": members})
after = self.c.call("GET", "/api/v1/chats?limit=100", actor=self.a, schema="ChatPage")["json"]
self.assertEqual(before, after)
def test_username_race(self):
body = dict(self.a["registration"], username="race_" + uuid4().hex[:16])
def register(_):
return Client(self.c.base).call("POST", "/api/v1/users", [201, 409], body=body)["status"]
with ThreadPoolExecutor(max_workers=6) as pool:
statuses = list(pool.map(register, range(6)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 5)
def test_concurrent_messages_and_keyset(self):
def send(i):
return Client(self.c.base).message(self.a, self.chat, "Поток " + str(i))["json"]
with ThreadPoolExecutor(max_workers=8) as pool:
sent = list(pool.map(send, range(40)))
items, cursor = [], None
while True:
page = self.c.call("GET", self.path + "/messages?limit=7" + ("&cursor=" + quote(cursor) if cursor else ""), actor=self.b, schema="MessagePage")["json"]
items.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
self.assertEqual(len(items), 40)
self.assertEqual({x["id"] for x in items}, {x["id"] for x in sent})
self.assertEqual(items, sorted(sent, key=lambda x: (x["created_at"], x["id"])))
def test_cursor_scope_and_tampering(self):
for i in range(3):
self.c.message(self.a, self.chat, str(i))
page = self.c.call("GET", self.path + "/messages?limit=1", actor=self.a, schema="MessagePage")["json"]
cursor = page["next_cursor"]
self.c.call("GET", "/api/v1/chats?cursor=" + quote(cursor), 400, actor=self.a)
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.a, body={"title": "Другой", "member_ids": [self.a["id"]]}, schema="Chat")["json"]
self.c.call("GET", "/api/v1/chats/" + other["id"] + "/messages?cursor=" + quote(cursor), 400, actor=self.a)
self.c.call("GET", self.path + "/messages?cursor=" + quote("X" + cursor[1:]), 400, actor=self.a)
def test_json_and_sender_validation(self):
for raw in (b'{"text":"a","text":"b"}', b'{"text":NaN}', b'{', b'{"text":"\\u0000"}'):
self.c.call("POST", self.path + "/messages", 400, actor=self.a, raw=raw, headers={"Content-Type": "application/json", "Idempotency-Key": uuid4().hex})
self.c.call("POST", self.path + "/messages", 400, actor=self.a, body={"text": "hello", "sender_id": self.b["id"]})
self.c.call("POST", self.path + "/messages", 400, actor=self.a, body={"text": " "})
page = self.c.call("GET", self.path + "/messages", actor=self.a, schema="MessagePage")["json"]
self.assertEqual(page["items"], [])
def test_access_before_payload_validation(self):
self.c.call("POST", self.path + "/messages", 404, actor=self.e, body={})
self.c.call("POST", self.path + "/messages", 401, body={})
self.c.call("GET", self.path, 404, actor=self.e)
if __name__ == "__main__":
unittest.main()
+68
View File
@@ -0,0 +1,68 @@
"""Real HTTP races through the LB, with one shared session and key."""
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import sys
import threading
import unittest
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client
class Idempotency(unittest.TestCase):
def setUp(self):
self.c = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
self.a, self.b, self.e, self.chat = self.c.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"] + "/messages"
def test_same_key_concurrent_across_replicas(self):
key, barrier = uuid4().hex, threading.Barrier(12)
def send(_):
c = Client(self.c.base)
barrier.wait(timeout=10)
return c.message(self.a, self.chat, "Один результат 👋", key=key)
with ThreadPoolExecutor(max_workers=12) as pool:
results = list(pool.map(send, range(12)))
self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in results}), 2)
self.assertTrue(all(r["json"] == results[0]["json"] for r in results))
history = self.c.call("GET", self.path, actor=self.b, schema="MessagePage")["json"]
self.assertEqual(history["items"], [results[0]["json"]])
print("PASS: concurrent_retries=12 observed_replicas=2 committed_messages=1", flush=True)
def test_conflicting_bodies_race(self):
key, barrier = uuid4().hex, threading.Barrier(2)
def send(text):
c = Client(self.c.base)
barrier.wait(timeout=10)
return c.call("POST", self.path, [201, 409], actor=self.a,
body={"text": text}, headers={"Idempotency-Key": key})
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(send, ["first", "second"]))
self.assertEqual(sorted(r["status"] for r in results), [201, 409])
history = self.c.call("GET", self.path, actor=self.a, schema="MessagePage")["json"]
self.assertEqual(len(history["items"]), 1)
def test_key_scope_and_access(self):
key = uuid4().hex
one = self.c.message(self.a, self.chat, "first", key=key)["json"]
two = self.c.message(self.b, self.chat, "second", key=key)["json"]
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.a,
body={"title": "other", "member_ids": [self.a["id"]]}, schema="Chat")["json"]
three = self.c.message(self.a, other, "third", key=key)["json"]
self.assertEqual(len({m["id"] for m in (one, two, three)}), 3)
self.c.call("POST", self.path, 404, actor=self.e, body={"text": "first"}, headers={"Idempotency-Key": key})
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.a)
self.c.call("POST", self.path, 401, actor=self.a, body={"text": "first"}, headers={"Idempotency-Key": key})
def test_invalid_keys_and_no_cached_error(self):
for key in ("", "a" * 129, "has space", "bad/key", "bad,key"):
self.c.call("POST", self.path, 400, actor=self.a, body={"text": "hello"}, headers={"Idempotency-Key": key})
key = uuid4().hex
self.c.call("POST", self.path, 400, actor=self.a, body={"text": " "}, headers={"Idempotency-Key": key})
self.c.message(self.a, self.chat, "valid after rejected body", key=key)
if __name__ == "__main__":
unittest.main()