Files
mtusi2026lab5/student-tests/test_balancing.py

40 lines
1.9 KiB
Python

"""Балансировка: запросы одной сессии обслуживают разные реплики, состояние у них общее."""
import time
import unittest
import api
class BalancingTest(unittest.TestCase):
def test_one_session_is_served_by_several_replicas(self):
user = api.new_user('Балансировка')
responses = [api.request('GET', '/api/v1/users/me', user=user) for _ in range(20)]
self.assertEqual({response.status for response in responses}, {200})
# Сессия общая (Valkey), поэтому любая реплика узнаёт токен без повторного входа.
self.assertGreaterEqual(len({api.instance(response) for response in responses}), 2)
def test_message_written_on_one_replica_is_read_on_another(self):
alice, bob = api.new_user('Алиса'), api.new_user('Боб')
chat = api.new_chat(alice, [alice, bob])
sent = api.send(alice, chat, 'запись на одной реплике')
self.assertEqual(sent.status, 201)
writer = api.instance(sent)
path = '/api/v1/chats/%s/messages' % chat['id']
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
read = api.request('GET', path, user=bob)
if api.instance(read) != writer:
# Подтверждённое сообщение сразу видно через другую реплику.
self.assertEqual(read.json['items'], [sent.json])
return
self.fail('no response from another replica within 5 s')
def test_errors_also_carry_instance_id(self):
for method, path in (('GET', '/api/v1/users/me'), ('GET', '/api/v1/unknown'), ('GET', '/health/live')):
with self.subTest(path=path):
self.assertTrue(api.instance(api.request(method, path)))
if __name__ == '__main__':
unittest.main()