Files
mtusi2026lab3/student-tests/test_replicas.py
T

42 lines
2.3 KiB
Python

import unittest
import uuid
from helpers import call, new_chat, new_user
class ReplicasTest(unittest.TestCase):
def test_one_session_is_served_by_several_replicas(self):
"""Один токен без повторного входа обслуживается разными репликами (X-Instance-Id), все ответы 200"""
alice = new_user('alice')
results = [call('GET', '/api/v1/users/me', token=alice['token']) for _ in range(10)]
self.assertEqual({status for status, _, _ in results}, {200})
self.assertGreaterEqual(len({headers['X-Instance-Id'] for _, headers, _ in results}), 2)
def test_write_on_one_replica_is_read_on_another(self):
"""Сообщение, подтверждённое одной репликой, сразу видно при чтении через другую"""
alice = new_user('alice')
chat = new_chat(alice)
path = '/api/v1/chats/%s/messages' % chat['id']
for i in range(6):
_, written_by, message = call('POST', path, {'text': 'm%d' % i}, alice['token'])
status, read_by, page = call('GET', path + '?limit=100', token=alice['token'])
self.assertEqual(status, 200)
self.assertIn(message['id'], [m['id'] for m in page['items']],
'запись через %s не видна через %s' % (written_by['X-Instance-Id'], read_by['X-Instance-Id']))
def test_every_api_response_has_instance_id(self):
"""X-Instance-Id есть и в успешных ответах, и в ошибках API, и в health"""
alice = new_user('alice')
for method, path, token, expected in (
('GET', '/health/live', None, 200), ('GET', '/health/ready', None, 200),
('GET', '/api/v1/users/me', None, 401), ('GET', '/api/v1/users/me', alice['token'], 200),
('GET', '/api/v1/chats/' + str(uuid.uuid4()), alice['token'], 404), ('GET', '/nope', None, 404)):
with self.subTest(path=path, expected=expected):
status, headers, _ = call(method, path, token=token)
self.assertEqual(status, expected)
self.assertTrue(headers['X-Instance-Id'])
if __name__ == '__main__':
unittest.main()