"""Кто что может читать: чужой чат отдаётся точно так же, как отсутствующий. В контракте есть 404 для чатов и сообщений и нигде нет 403, поэтому посторонний не должен по кодам ответов узнавать о существовании чата. """ from __future__ import annotations import unittest import uuid import harness class ChatVisibility(unittest.TestCase): """Участие определяется сессией, а не заголовком или полем тела запроса.""" @classmethod def setUpClass(cls): cls.api = harness.client() cls.alice = harness.account(cls.api, "acc_alice") cls.bob = harness.account(cls.api, "acc_bob") cls.eve = harness.account(cls.api, "acc_eve") cls.chat = harness.chat(cls.api, cls.alice, [cls.bob], title="Приватный чат") harness.send(cls.api, cls.alice, cls.chat, "Только для участников") def test_members_read_the_chat(self): for actor in (self.alice, self.bob): with self.subTest(user=actor["username"]): response = self.api.call("GET", "/api/v1/chats/" + self.chat["id"], 200, actor=actor, schema="Chat") self.assertEqual(response["json"]["id"], self.chat["id"]) def test_outsider_gets_not_found(self): for path in ("/api/v1/chats/" + self.chat["id"], "/api/v1/chats/" + self.chat["id"] + "/messages"): with self.subTest(path=path): response = self.api.call("GET", path, [404], actor=self.eve) self.assertEqual(response["json"]["error"]["code"], "not_found") def test_outsider_cannot_write(self): response = self.api.call( "POST", "/api/v1/chats/" + self.chat["id"] + "/messages", [404], actor=self.eve, body={"text": "Посторонний"}, ) self.assertEqual(response["json"]["error"]["code"], "not_found") def test_outsider_does_not_see_the_chat_in_the_list(self): self.assertNotIn(self.chat["id"], {item["id"] for item in harness.all_chats(self.api, self.eve)}) def test_a_foreign_chat_and_a_missing_chat_are_reported_alike(self): """Тот же статус, тот же код, то же сообщение: разница не должна утекать.""" foreign = self.api.call("GET", "/api/v1/chats/" + self.chat["id"], [404], actor=self.eve) missing = self.api.call("GET", "/api/v1/chats/" + str(uuid.uuid4()), [404], actor=self.eve) left = dict(foreign["json"]["error"]) right = dict(missing["json"]["error"]) left.pop("request_id") right.pop("request_id") self.assertEqual(left, right) self.assertEqual(foreign["status"], missing["status"]) def test_x_user_id_does_not_open_a_foreign_chat(self): response = self.api.call( "GET", "/api/v1/chats/" + self.chat["id"], [404], actor=self.eve, headers={"X-User-Id": self.alice["id"]}, ) self.assertEqual(response["json"]["error"]["code"], "not_found") def test_a_left_member_still_sees_the_history(self): """Участие фиксируется при создании, поэтому история участника не исчезает.""" messages = harness.all_messages(self.api, self.bob, self.chat["id"]) self.assertTrue(messages) self.assertTrue(all(item["chat_id"] == self.chat["id"] for item in messages)) class CurrentUser(unittest.TestCase): """GET /users/me отвечает владельцу сессии и больше никому.""" @classmethod def setUpClass(cls): cls.api = harness.client() cls.alice = harness.account(cls.api, "me_alice") cls.bob = harness.account(cls.api, "me_bob") def test_each_session_sees_its_own_user(self): for actor in (self.alice, self.bob): with self.subTest(user=actor["username"]): body = self.api.call("GET", "/api/v1/users/me", 200, actor=actor, schema="User")["json"] self.assertEqual(body["id"], actor["id"]) self.assertEqual(body["username"], actor["username"]) def test_registration_body_is_never_echoed(self): body = self.api.call("GET", "/api/v1/users/me", 200, actor=self.alice, schema="User")["json"] self.assertNotIn("password", body) self.assertNotIn("password_hash", body) if __name__ == "__main__": unittest.main(verbosity=2)