forked from mtusi2026/mtusi2026lab4
63 lines
3.0 KiB
Python
63 lines
3.0 KiB
Python
"""Параллельные запросы не должны терять, дублировать или портить данные."""
|
|
import threading
|
|
import unittest
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
import api
|
|
from race import run_race
|
|
|
|
|
|
class ConcurrencyTest(unittest.TestCase):
|
|
def test_100_messages_from_10_clients(self):
|
|
summary = run_race(clients=10, per_client=10)
|
|
self.assertEqual(summary['accepted_201'], 100)
|
|
self.assertEqual(summary['history_total'], 100)
|
|
self.assertEqual(summary['history_unique_ids'], 100)
|
|
self.assertEqual(summary['history_unique_texts'], 100)
|
|
self.assertTrue(summary['history_matches_accepted'])
|
|
self.assertEqual(summary['senders_in_history'], 10)
|
|
self.assertEqual((summary['min_messages_per_sender'], summary['max_messages_per_sender']), (10, 10))
|
|
self.assertTrue(summary['ordered_by_created_at_and_id'])
|
|
|
|
def test_same_username_registered_in_parallel_wins_once(self):
|
|
# Уникальность username держит индекс PostgreSQL: из одновременных INSERT проходит один,
|
|
# остальные получают нарушение уникальности, и API отвечает 409.
|
|
attempts = 20
|
|
username = api.unique_username()
|
|
passwords = ['Гонка-пароль-%02d' % n for n in range(attempts)]
|
|
start = threading.Barrier(attempts)
|
|
|
|
def register(index):
|
|
start.wait()
|
|
body = {'username': username, 'display_name': 'Гонка %d' % index, 'password': passwords[index]}
|
|
return api.request('POST', '/api/v1/users', body=body)
|
|
|
|
with ThreadPoolExecutor(max_workers=attempts) as pool:
|
|
responses = list(pool.map(register, range(attempts)))
|
|
statuses = sorted(response.status for response in responses)
|
|
self.assertEqual(statuses, [201] + [409] * (attempts - 1))
|
|
# Победитель один, и войти можно только с его паролем.
|
|
winner = next(index for index, response in enumerate(responses) if response.status == 201)
|
|
logins = [api.login(username, password).status for password in passwords]
|
|
self.assertEqual(logins, [201 if index == winner else 401 for index in range(attempts)])
|
|
|
|
def test_chats_created_in_parallel_are_all_listed(self):
|
|
user = api.new_user()
|
|
count = 30
|
|
start = threading.Barrier(count)
|
|
|
|
def create(index):
|
|
start.wait()
|
|
return api.new_chat(user, [user], title='Параллельный чат %d' % index)
|
|
|
|
with ThreadPoolExecutor(max_workers=count) as pool:
|
|
created = list(pool.map(create, range(count)))
|
|
listed = [chat for page in api.pages('/api/v1/chats', user, 7) for chat in page]
|
|
self.assertEqual(len(listed), count)
|
|
self.assertEqual({chat['id'] for chat in listed}, {chat['id'] for chat in created})
|
|
self.assertEqual(listed, sorted(listed, key=api.order_key))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|