126 lines
6.0 KiB
Python
126 lines
6.0 KiB
Python
"""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)
|