import base64 import uuid import httpx BASE = "http://localhost:8080" def _register_and_login(client: httpx.Client) -> dict: username = "u_" + uuid.uuid4().hex[:10] password = "Test-password-" + uuid.uuid4().hex[:8] r = client.post( f"{BASE}/api/v1/users", json={ "username": username, "display_name": "Тест", "password": password, }, ) assert r.status_code == 201, r.text user = r.json() credential = base64.b64encode( (username + ":" + password).encode("utf-8") ).decode("ascii") r = client.post( f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}, ) assert r.status_code == 201, r.text session = r.json() return { "id": user["id"], "username": username, "password": password, "token": session["token"], } def _auth(actor: dict) -> dict: return {"Authorization": "Bearer " + actor["token"]} def test_invalid_json_returns_400(): with httpx.Client() as c: r = c.post( f"{BASE}/api/v1/users", content=b"{not json at all", headers={"Content-Type": "application/json"}, ) assert r.status_code == 400 body = r.json() assert body["error"]["code"] == "invalid_request" assert "X-Request-Id" in r.headers def test_duplicate_username_returns_409(): with httpx.Client() as c: actor = _register_and_login(c) r = c.post( f"{BASE}/api/v1/users", json={ "username": actor["username"], "display_name": "Другой", "password": "Another-password-123", }, ) assert r.status_code == 409 assert r.json()["error"]["code"] == "conflict" def test_empty_message_returns_400(): with httpx.Client() as c: alice = _register_and_login(c) bob = _register_and_login(c) chat = c.post( f"{BASE}/api/v1/chats", json={"title": "t", "member_ids": [alice["id"], bob["id"]]}, headers=_auth(alice), ).json() r = c.post( f"{BASE}/api/v1/chats/{chat['id']}/messages", json={"text": ""}, headers=_auth(alice), ) assert r.status_code == 400 def test_outsider_gets_404_not_403(): with httpx.Client() as c: alice = _register_and_login(c) bob = _register_and_login(c) eve = _register_and_login(c) chat = c.post( f"{BASE}/api/v1/chats", json={"title": "t", "member_ids": [alice["id"], bob["id"]]}, headers=_auth(alice), ).json() r = c.get( f"{BASE}/api/v1/chats/{chat['id']}", headers=_auth(eve), ) assert r.status_code == 404 r2 = c.post( f"{BASE}/api/v1/chats/{chat['id']}/messages", json={"text": "вторжение"}, headers=_auth(eve), ) assert r2.status_code == 404 def test_pagination_walks_all_pages(): with httpx.Client() as c: alice = _register_and_login(c) bob = _register_and_login(c) chat = c.post( f"{BASE}/api/v1/chats", json={"title": "t", "member_ids": [alice["id"], bob["id"]]}, headers=_auth(alice), ).json() sent_ids = [] for i in range(5): m = c.post( f"{BASE}/api/v1/chats/{chat['id']}/messages", json={"text": f"msg-{i}"}, headers=_auth(alice), ).json() sent_ids.append(m["id"]) collected = [] cursor = None while True: params = {"limit": 2} if cursor: params["cursor"] = cursor r = c.get( f"{BASE}/api/v1/chats/{chat['id']}/messages", params=params, headers=_auth(alice), ) assert r.status_code == 200, r.text page = r.json() collected.extend(m["id"] for m in page["items"]) cursor = page["next_cursor"] if not cursor: break assert collected == sent_ids def test_wrong_password_returns_401(): with httpx.Client() as c: actor = _register_and_login(c) bad = base64.b64encode( (actor["username"] + ":wrong-password-1234").encode("utf-8") ).decode("ascii") r = c.post( f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + bad}, ) assert r.status_code == 401 assert "WWW-Authenticate" in r.headers assert r.headers["WWW-Authenticate"].lower().startswith("basic") def test_logout_invalidates_token(): with httpx.Client() as c: actor = _register_and_login(c) r = c.delete( f"{BASE}/api/v1/auth/sessions/current", headers=_auth(actor), ) assert r.status_code == 204 r = c.get(f"{BASE}/api/v1/users/me", headers=_auth(actor)) assert r.status_code == 401 def test_x_user_id_ignored_with_bearer(): with httpx.Client() as c: alice = _register_and_login(c) bob = _register_and_login(c) r = c.get( f"{BASE}/api/v1/users/me", headers={ "Authorization": "Bearer " + alice["token"], "X-User-Id": bob["id"], }, ) assert r.status_code == 200 assert r.json()["id"] == alice["id"] def test_basic_on_business_endpoint_returns_401(): with httpx.Client() as c: actor = _register_and_login(c) credential = base64.b64encode( (actor["username"] + ":" + actor["password"]).encode("utf-8") ).decode("ascii") r = c.get( f"{BASE}/api/v1/users/me", headers={"Authorization": "Basic " + credential}, ) assert r.status_code == 401 def test_race_duplicate_username_only_one_wins(): """Гонка: два параллельных POST /users с одинаковым username. Ожидание: один 201, второй 409. В БД ровно один пользователь. """ from concurrent.futures import ThreadPoolExecutor username = "race_" + uuid.uuid4().hex[:10] password = "Test-password-1234" def register(): with httpx.Client(timeout=10) as c: return c.post( f"{BASE}/api/v1/users", json={ "username": username, "display_name": "Race", "password": password, }, ).status_code with ThreadPoolExecutor(max_workers=2) as pool: statuses = list(pool.map(lambda _: register(), range(2))) assert sorted(statuses) == [201, 409], f"got statuses {statuses}" credential = base64.b64encode( (username + ":" + password).encode("utf-8") ).decode("ascii") with httpx.Client() as c: r = c.post( f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}, ) assert r.status_code == 201, "победитель должен уметь логиниться" assert r.json()["user"]["username"] == username def test_rollback_chat_with_unknown_member(): """Составная операция создания чата с несуществующим участником. Ожидание: 400, чат не создан, в БД ничего не осталось. """ with httpx.Client() as c: alice = _register_and_login(c) fake_id = str(uuid.uuid4()) r = c.post( f"{BASE}/api/v1/chats", json={ "title": "Не должно создаться", "member_ids": [alice["id"], fake_id], }, headers=_auth(alice), ) assert r.status_code == 400, r.text chats = c.get( f"{BASE}/api/v1/chats?limit=100", headers=_auth(alice), ).json() titles = [ch["title"] for ch in chats["items"]] assert "Не должно создаться" not in titles, "чат создан несмотря на ошибку"