import uuid from sqlalchemy import text from conftest import assert_error from core.db import engine def count_rows(table): with engine.connect() as connection: return connection.scalar(text(f"SELECT count(*) FROM {table}")) def test_unknown_member_returns_400_and_nothing_is_saved(client, alice): response = client.post("/api/v1/chats", headers=alice["auth"], json={"title": "С призраком", "member_ids": [alice["id"], str(uuid.uuid4())]}) assert_error(response, 400, "invalid_request") assert count_rows("chats") == 0 assert count_rows("chat_members") == 0 def test_created_chat_is_stored_with_members(client, chat, alice, bob): assert sorted(chat["member_ids"]) == sorted([alice["id"], bob["id"]]) assert count_rows("chats") == 1 assert count_rows("chat_members") == 2 again = client.get("/api/v1/chats/" + chat["id"], headers=bob["auth"]).json() assert again == chat def test_foreign_chat_returns_404(client, chat, eve): headers = eve["auth"] path = "/api/v1/chats/" + chat["id"] assert_error(client.get(path, headers=headers), 404, "not_found") assert_error(client.get(path + "/messages", headers=headers), 404, "not_found") assert_error(client.post(path + "/messages", headers=headers, json={"text": "чужое"}), 404, "not_found") assert client.get("/api/v1/chats", headers=headers).json()["items"] == [] def test_member_sees_chat(client, chat, bob): response = client.get("/api/v1/chats", headers=bob["auth"]) assert [c["id"] for c in response.json()["items"]] == [chat["id"]] def test_creator_must_be_member(client, alice, bob): response = client.post("/api/v1/chats", headers=alice["auth"], json={"title": "Без меня", "member_ids": [bob["id"]]}) assert_error(response, 400, "invalid_request") def test_duplicate_members_return_400(client, alice): response = client.post("/api/v1/chats", headers=alice["auth"], json={"title": "Дубли", "member_ids": [alice["id"], alice["id"]]}) assert_error(response, 400, "invalid_request")