Files
mtusi2026lab2/student-tests/test_concurrency.py
ChernikovandClaude Opus 5.5 921ae002d6 ЛР 2 — БВТ2304 — Черников
PostgreSQL с версионируемыми миграциями, вход по Basic и Bearer-сессии в Valkey
(AOF), Argon2id, compose-стенд с секретами в файлах. Собственные тесты в
student-tests/, проверки инфраструктуры и EXPLAIN в scripts/, отчёт в REPORT.md,
результаты в evidence/, команды для показа в DEMO.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:58:54 +03:00

60 lines
2.7 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):
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()