"""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()