Lab 2: PostgreSQL storage and Redis sessions
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
import sys
|
||||
import unittest
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, timestamp
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def read_all(self, client, actor, path, limit=17):
|
||||
items = []
|
||||
cursor = None
|
||||
seen = set()
|
||||
for _ in range(1000):
|
||||
url = path + "?limit=" + str(limit)
|
||||
if cursor is not None:
|
||||
url += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", url, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
self.assertNotIn(cursor, seen, "cursor зациклился")
|
||||
seen.add(cursor)
|
||||
self.fail("Слишком много страниц")
|
||||
|
||||
def test_malformed_json(self):
|
||||
result = self.c.call("POST", "/api/v1/users", 400,
|
||||
raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"})
|
||||
self.assertEqual(result["json"]["error"]["code"], "invalid_request")
|
||||
|
||||
def test_foreign_chat(self):
|
||||
self.c.call("GET", self.path, 404, actor=self.eve)
|
||||
self.c.call("GET", self.path + "/messages", 404, actor=self.eve)
|
||||
self.c.call("POST", self.path + "/messages", 404,
|
||||
actor=self.eve, body={"text": "Чужой чат"})
|
||||
page = self.c.call("GET", "/api/v1/chats", actor=self.eve,
|
||||
schema="ChatPage")["json"]
|
||||
self.assertNotIn(self.chat["id"], [item["id"] for item in page["items"]])
|
||||
|
||||
def test_empty_message(self):
|
||||
for value in ("", " ", "\n\t"):
|
||||
with self.subTest(text=repr(value)):
|
||||
self.c.call("POST", self.path + "/messages", 400,
|
||||
actor=self.alice, body={"text": value})
|
||||
|
||||
def test_duplicate_username(self):
|
||||
self.c.call("POST", "/api/v1/users", 409,
|
||||
body=self.alice["registration"])
|
||||
|
||||
def test_multiple_pages_and_cursor_scope(self):
|
||||
expected = [self.c.message(self.alice, self.chat, "Страница " + str(i))["json"]
|
||||
for i in range(7)]
|
||||
actual = self.read_all(self.c, self.bob, self.path + "/messages", limit=2)
|
||||
self.assertEqual(actual, sorted(expected, key=lambda x:
|
||||
(timestamp(x["created_at"]), uuid.UUID(x["id"]).int)))
|
||||
self.assertEqual(len({item["id"] for item in actual}), 7)
|
||||
page = self.c.call("GET", self.path + "/messages?limit=1",
|
||||
actor=self.alice, schema="MessagePage")["json"]
|
||||
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "Другой", "member_ids": [self.alice["id"]]},
|
||||
schema="Chat")["json"]
|
||||
self.c.call("GET", "/api/v1/chats/" + other["id"] + "/messages?cursor="
|
||||
+ quote(page["next_cursor"], safe=""), 400, actor=self.alice)
|
||||
|
||||
def test_validation_and_auth(self):
|
||||
for body in ({"text": 123}, {"text": "ok", "sender_id": self.bob["id"]},
|
||||
{"text": "x" * 4001}):
|
||||
self.c.call("POST", self.path + "/messages", 400,
|
||||
actor=self.alice, body=body)
|
||||
for limit in ("0", "101", "abc", "1.5"):
|
||||
self.c.call("GET", self.path + "/messages?limit=" + limit,
|
||||
400, actor=self.alice)
|
||||
self.c.call("GET", self.path + "/messages?cursor=garbage", 400,
|
||||
actor=self.alice)
|
||||
self.c.call("GET", "/api/v1/users/me", 401)
|
||||
self.c.call("GET", "/api/v1/users/me", 401,
|
||||
headers={"X-User-Id": str(uuid.uuid4())})
|
||||
self.c.call("POST", self.path + "/messages", 401, raw=b'{',
|
||||
headers={"Content-Type": "application/json"})
|
||||
self.c.call("POST", self.path + "/messages", 415, actor=self.alice,
|
||||
raw=b'plain', headers={"Content-Type": "text/plain"})
|
||||
for members in ([self.alice["id"], self.alice["id"]],
|
||||
[self.bob["id"]], [self.alice["id"], str(uuid.uuid4())]):
|
||||
self.c.call("POST", "/api/v1/chats", 400, actor=self.alice,
|
||||
body={"title": "Неверный чат", "member_ids": members})
|
||||
|
||||
def test_concurrency_100_messages_10_clients(self):
|
||||
# У каждого из 10 потоков свой HTTP-клиент и 10 последовательных POST.
|
||||
def send_batch(worker):
|
||||
client = Client()
|
||||
sent = []
|
||||
for i in range(10):
|
||||
text = "worker=" + str(worker) + ";message=" + str(i)
|
||||
sent.append(client.message(self.alice, self.chat, text)["json"])
|
||||
return sent
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
batches = list(pool.map(send_batch, range(10)))
|
||||
sent = [item for batch in batches for item in batch]
|
||||
actual = self.read_all(self.c, self.bob, self.path + "/messages")
|
||||
self.assertEqual(len(sent), 100)
|
||||
self.assertEqual(len(actual), 100)
|
||||
self.assertEqual(len({item["id"] for item in actual}), 100)
|
||||
self.assertEqual({item["id"] for item in actual}, {item["id"] for item in sent})
|
||||
self.assertEqual({item["text"] for item in actual}, {item["text"] for item in sent})
|
||||
self.assertTrue(all(item["sender_id"] == self.alice["id"] for item in actual))
|
||||
print("PASS: 10 clients; 100 POST; 100 unique messages; IDs/text match")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""HTTP + PostgreSQL checks; run inside api so its DB settings are available."""
|
||||
import base64
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from client import Client
|
||||
from src.db import connection_kwargs
|
||||
|
||||
|
||||
class Grade4Tests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c = Client()
|
||||
|
||||
def test_registration_race(self):
|
||||
body = {"username": "race_" + uuid4().hex[:16],
|
||||
"display_name": "Гонка регистрации", "password": "Example-password-123"}
|
||||
barrier = threading.Barrier(4)
|
||||
|
||||
def register(_):
|
||||
c = Client()
|
||||
barrier.wait(timeout=10)
|
||||
return c.call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as workers:
|
||||
statuses = list(workers.map(register, range(4)))
|
||||
self.assertEqual(sorted(statuses), [201, 409, 409, 409])
|
||||
with psycopg.connect(**connection_kwargs()) as conn:
|
||||
row = conn.execute("SELECT count(*) AS n FROM users WHERE username=%s",
|
||||
(body["username"],)).fetchone()
|
||||
self.assertEqual(row["n"], 1)
|
||||
|
||||
def test_chat_rollback_after_unknown_member(self):
|
||||
alice = self.c.user("rollback")
|
||||
title = "rollback_" + uuid4().hex
|
||||
with psycopg.connect(**connection_kwargs()) as conn:
|
||||
before = conn.execute("SELECT count(*) AS n FROM chat_members WHERE user_id=%s",
|
||||
(alice["id"],)).fetchone()["n"]
|
||||
self.c.call("POST", "/api/v1/chats", 400, actor=alice,
|
||||
body={"title": title, "member_ids": [alice["id"], str(uuid4())]})
|
||||
with psycopg.connect(**connection_kwargs()) as conn:
|
||||
self.assertEqual(conn.execute("SELECT count(*) AS n FROM chats WHERE title=%s",
|
||||
(title,)).fetchone()["n"], 0)
|
||||
after = conn.execute("SELECT count(*) AS n FROM chat_members WHERE user_id=%s",
|
||||
(alice["id"],)).fetchone()["n"]
|
||||
self.assertEqual(before, after)
|
||||
|
||||
def test_login_logout_and_legacy_header(self):
|
||||
alice = self.c.user("sessions")
|
||||
wrong = base64.b64encode(
|
||||
(alice["registration"]["username"] + ":wrong-password-123").encode()
|
||||
).decode()
|
||||
self.c.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers={"Authorization": "Basic " + wrong})
|
||||
self.c.call("GET", "/api/v1/users/me", 401,
|
||||
headers={"X-User-Id": alice["id"]})
|
||||
me = self.c.call("GET", "/api/v1/users/me", actor=alice,
|
||||
headers={"X-User-Id": str(uuid4())}, schema="User")["json"]
|
||||
self.assertEqual(me["id"], alice["id"])
|
||||
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
self.c.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
self.c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=alice)
|
||||
|
||||
def test_unicode_password_with_colon_and_hash(self):
|
||||
body = {"username": "utf_" + uuid4().hex[:16], "display_name": "Студент 👋",
|
||||
"password": "Пароль:мандарин🍊123"}
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
basic = base64.b64encode((body["username"] + ":" + body["password"]).encode()).decode()
|
||||
session = self.c.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers={"Authorization": "Basic " + basic}, schema="Session")["json"]
|
||||
self.assertEqual(session["user"], user)
|
||||
self.assertEqual(len(base64.urlsafe_b64decode(session["token"] + "=")), 32)
|
||||
with psycopg.connect(**connection_kwargs()) as conn:
|
||||
stored = conn.execute("SELECT password_hash FROM users WHERE id=%s",
|
||||
(user["id"],)).fetchone()["password_hash"]
|
||||
self.assertTrue(stored.startswith("$argon2id$"))
|
||||
self.assertNotIn(body["password"], stored)
|
||||
|
||||
def test_equal_timestamp_pages(self):
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
ids = [uuid4() for _ in range(5)]
|
||||
with psycopg.connect(**connection_kwargs()) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO messages (id,chat_id,sender_id,text,created_at) "
|
||||
"VALUES (%s,%s,%s,%s,'2026-01-01T00:00:00Z')",
|
||||
[(i, chat["id"], alice["id"], "Одинаковое время") for i in ids],
|
||||
)
|
||||
from urllib.parse import quote
|
||||
found, cursor = [], None
|
||||
for _ in range(6):
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=2"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = self.c.call("GET", path, actor=bob, schema="MessagePage")["json"]
|
||||
found.extend(x["id"] for x in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertIsNone(cursor)
|
||||
self.assertEqual(found, [str(i) for i in sorted(ids)])
|
||||
|
||||
def test_nul_in_persisted_fields_returns_400(self):
|
||||
self.c.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "nul_" + uuid4().hex[:16], "display_name": "x\u0000y",
|
||||
"password": "Example-password-123"})
|
||||
alice = self.c.user("nul")
|
||||
self.c.call("POST", "/api/v1/chats", 400, actor=alice,
|
||||
body={"title": "x\u0000y", "member_ids": [alice["id"]]})
|
||||
chat = self.c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "NUL check", "member_ids": [alice["id"]]}, schema="Chat")["json"]
|
||||
self.c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400,
|
||||
actor=alice, body={"text": "x\u0000y"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Pure cursor checks: python -m unittest discover -s student-tests -p test_pagination.py."""
|
||||
import importlib.util
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
class PaginationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.assertIsNotNone(
|
||||
importlib.util.find_spec("src.pagination"),
|
||||
"SQL pagination helper has not been implemented",
|
||||
)
|
||||
from src import pagination
|
||||
from src.errors import ApiError
|
||||
self.p = pagination
|
||||
self.error = ApiError
|
||||
|
||||
def test_cursor_round_trip_and_scope(self):
|
||||
item = {"id": "00000000-0000-4000-8000-000000000001",
|
||||
"created_at": "2026-10-19T12:00:00.123456Z"}
|
||||
cursor = self.p.encode_cursor("messages:chat-a", item)
|
||||
limit, after = self.p.parse_page("17", cursor, "messages:chat-a")
|
||||
self.assertEqual(limit, 17)
|
||||
self.assertEqual(after, (datetime(2026, 10, 19, 12, 0, 0, 123456,
|
||||
tzinfo=timezone.utc), UUID(item["id"])))
|
||||
with self.assertRaises(self.error):
|
||||
self.p.parse_page("17", cursor, "messages:chat-b")
|
||||
|
||||
def test_invalid_limits_and_cursors(self):
|
||||
for value in ("0", "101", "1.5", "abc", "-1"):
|
||||
with self.subTest(limit=value), self.assertRaises(self.error):
|
||||
self.p.parse_page(value, None, "scope")
|
||||
for value in ("", "garbage", "!!!!", "bnVsbA", "W10"):
|
||||
with self.subTest(cursor=value), self.assertRaises(self.error):
|
||||
self.p.parse_page("50", value, "scope")
|
||||
self.assertEqual(self.p.parse_page("50", None, "scope"), (50, None))
|
||||
|
||||
def test_cursor_requires_complete_utc_datetime(self):
|
||||
for timestamp in ("2026-01-01Z", "2026-01-01T00:00:00", "2026-01-01T00:00:00+03:00"):
|
||||
item = {"id": "00000000-0000-4000-8000-000000000001", "created_at": timestamp}
|
||||
cursor = self.p.encode_cursor("scope", item)
|
||||
with self.subTest(timestamp=timestamp), self.assertRaises(self.error):
|
||||
self.p.parse_page("50", cursor, "scope")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user