143 lines
7.3 KiB
Python
143 lines
7.3 KiB
Python
import unittest
|
||
import uuid
|
||
|
||
from helpers import call, new_chat, new_user, read_all_messages
|
||
|
||
|
||
class ErrorFormatMixin:
|
||
def assertError(self, result, status, code):
|
||
actual, headers, body = result
|
||
self.assertEqual(actual, status)
|
||
self.assertEqual(body['error']['code'], code)
|
||
self.assertEqual(body['error']['request_id'], headers['X-Request-Id'])
|
||
self.assertNotIn('Traceback', body['error']['message'])
|
||
|
||
|
||
class InvalidJsonTest(ErrorFormatMixin, unittest.TestCase):
|
||
def test_malformed_json(self):
|
||
"""Битый JSON -> 400 invalid_request"""
|
||
self.assertError(call('POST', '/api/v1/users', raw=b'{"username": "abc",'), 400, 'invalid_request')
|
||
|
||
def test_json_not_object(self):
|
||
"""JSON-массив вместо объекта -> 400"""
|
||
self.assertError(call('POST', '/api/v1/users', raw=b'[1, 2, 3]'), 400, 'invalid_request')
|
||
|
||
def test_wrong_type(self):
|
||
"""Число вместо строки -> 400 (без тихого приведения типов)"""
|
||
self.assertError(call('POST', '/api/v1/users', {'username': 12345, 'display_name': 'x', 'password': 'Long-enough-pass-1'}), 400, 'invalid_request')
|
||
|
||
def test_extra_field(self):
|
||
"""Лишнее поле в теле -> 400"""
|
||
body = {'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': 'x', 'password': 'Long-enough-pass-1', 'is_admin': True}
|
||
self.assertError(call('POST', '/api/v1/users', body), 400, 'invalid_request')
|
||
|
||
|
||
class DuplicateUsernameTest(ErrorFormatMixin, unittest.TestCase):
|
||
def test_duplicate_username(self):
|
||
"""Повторная регистрация того же username -> 409 conflict"""
|
||
user = new_user('dup')
|
||
again = call('POST', '/api/v1/users', {'username': user['username'], 'display_name': 'Другой',
|
||
'password': 'Other-password-123'})
|
||
self.assertError(again, 409, 'conflict')
|
||
|
||
|
||
class ForeignChatTest(ErrorFormatMixin, unittest.TestCase):
|
||
def setUp(self):
|
||
self.alice, self.bob, self.eve = new_user('alice'), new_user('bob'), new_user('eve')
|
||
self.chat = new_chat(self.alice, self.bob)
|
||
self.path = '/api/v1/chats/' + self.chat['id']
|
||
|
||
def test_outsider_cannot_read_chat(self):
|
||
"""Посторонний читает чат -> 404, как будто чата нет"""
|
||
self.assertError(call('GET', self.path, token=self.eve['token']), 404, 'not_found')
|
||
missing = call('GET', '/api/v1/chats/' + str(uuid.uuid4()), token=self.eve['token'])
|
||
self.assertEqual(missing[2]['error']['message'], call('GET', self.path, token=self.eve['token'])[2]['error']['message'])
|
||
|
||
def test_outsider_cannot_write_or_read_history(self):
|
||
"""Посторонний пишет/читает историю -> 404"""
|
||
self.assertError(call('POST', self.path + '/messages', {'text': 'чужое'}, self.eve['token']), 404, 'not_found')
|
||
self.assertError(call('GET', self.path + '/messages', token=self.eve['token']), 404, 'not_found')
|
||
|
||
def test_outsider_does_not_see_chat_in_list(self):
|
||
"""Чужой чат не попадает в список чатов"""
|
||
status, _, page = call('GET', '/api/v1/chats?limit=100', token=self.eve['token'])
|
||
self.assertEqual(status, 200)
|
||
self.assertNotIn(self.chat['id'], [c['id'] for c in page['items']])
|
||
|
||
def test_member_has_access(self):
|
||
"""Участник видит чат (контроль: 404 выше не из-за ошибки в тесте)"""
|
||
self.assertEqual(call('GET', self.path, token=self.bob['token'])[0], 200)
|
||
|
||
|
||
class EmptyMessageTest(ErrorFormatMixin, unittest.TestCase):
|
||
def setUp(self):
|
||
self.alice = new_user('alice')
|
||
self.path = '/api/v1/chats/%s/messages' % new_chat(self.alice)['id']
|
||
|
||
def test_empty_text(self):
|
||
"""Пустой текст -> 400"""
|
||
self.assertError(call('POST', self.path, {'text': ''}, self.alice['token']), 400, 'invalid_request')
|
||
|
||
def test_whitespace_text(self):
|
||
"""Текст только из пробельных символов -> 400"""
|
||
self.assertError(call('POST', self.path, {'text': ' \t\n '}, self.alice['token']), 400, 'invalid_request')
|
||
|
||
def test_missing_text(self):
|
||
"""Тело без поля text -> 400"""
|
||
self.assertError(call('POST', self.path, {}, self.alice['token']), 400, 'invalid_request')
|
||
|
||
def test_text_length_limit(self):
|
||
"""4000 символов можно (эмодзи = 1 символ), 4001 — 400"""
|
||
self.assertEqual(call('POST', self.path, {'text': '😀' * 4000}, self.alice['token'])[0], 201)
|
||
self.assertError(call('POST', self.path, {'text': 'x' * 4001}, self.alice['token']), 400, 'invalid_request')
|
||
|
||
|
||
class PaginationTest(ErrorFormatMixin, unittest.TestCase):
|
||
def setUp(self):
|
||
self.alice = new_user('alice')
|
||
self.chat = new_chat(self.alice)
|
||
self.sent = [call('POST', '/api/v1/chats/%s/messages' % self.chat['id'],
|
||
{'text': 'сообщение %d' % i}, self.alice['token'])[2] for i in range(7)]
|
||
|
||
def test_walk_several_pages(self):
|
||
"""7 сообщений по 3: три страницы, без потерь, повторов и перестановок"""
|
||
items, pages = read_all_messages(self.chat['id'], self.alice['token'], limit=3)
|
||
self.assertEqual(pages, 3)
|
||
self.assertEqual([m['id'] for m in items], [m['id'] for m in self.sent])
|
||
keys = [(m['created_at'], m['id']) for m in items]
|
||
self.assertEqual(keys, sorted(keys))
|
||
|
||
def test_cursor_from_other_chat(self):
|
||
"""cursor от другого чата -> 400"""
|
||
_, _, page = call('GET', '/api/v1/chats/%s/messages?limit=1' % self.chat['id'], token=self.alice['token'])
|
||
other = new_chat(self.alice, title='Другой')
|
||
self.assertError(call('GET', '/api/v1/chats/%s/messages?cursor=%s' % (other['id'], page['next_cursor']),
|
||
token=self.alice['token']), 400, 'invalid_request')
|
||
|
||
def test_invalid_cursor_and_limit(self):
|
||
"""Мусорный cursor и limit вне 1..100 -> 400"""
|
||
path = '/api/v1/chats/%s/messages' % self.chat['id']
|
||
for query in ('?cursor=not-a-cursor', '?limit=0', '?limit=101', '?limit=abc'):
|
||
with self.subTest(query=query):
|
||
self.assertError(call('GET', path + query, token=self.alice['token']), 400, 'invalid_request')
|
||
|
||
|
||
class IdentityTest(ErrorFormatMixin, unittest.TestCase):
|
||
def test_sender_cannot_be_forged(self):
|
||
"""sender_id в теле запрещён: отправитель только из сессии"""
|
||
alice, bob = new_user('alice'), new_user('bob')
|
||
chat = new_chat(alice, bob)
|
||
forged = call('POST', '/api/v1/chats/%s/messages' % chat['id'], {'text': 'hi', 'sender_id': bob['id']}, alice['token'])
|
||
self.assertError(forged, 400, 'invalid_request')
|
||
|
||
def test_nul_character_is_rejected(self):
|
||
"""Символ NUL нельзя сохранить в PostgreSQL text -> 400, а не 500"""
|
||
alice = new_user('alice')
|
||
chat = new_chat(alice)
|
||
self.assertError(call('POST', '/api/v1/chats/%s/messages' % chat['id'], {'text': 'a\u0000b'}, alice['token']),
|
||
400, 'invalid_request')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
unittest.main()
|