Files
mtusi2026lab4/tests/extra.py
T
2026-11-12 19:38:03 +03:00

112 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from concurrent.futures import ThreadPoolExecutor
import json
import base64
import uuid
from urllib.parse import quote
from client import Client, arguments, check, run
def main():
args = arguments("Собственные тесты мессенджера")
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
chat_path = "/api/v1/chats/" + chat["id"]
client.call(
"POST",
"/api/v1/users",
400,
raw=b'{"username":',
headers={"Content-Type": "application/json"},
)
client.call("POST", "/api/v1/users", 409, body=alice["registration"])
client.call(
"POST",
chat_path + "/messages",
400,
actor=alice,
body={"text": " "},
)
client.call("GET", chat_path, 404, actor=eve)
# Уникальность защищена ограничением БД, в том числе при гонке.
registration = {
'username': 'race_' + uuid.uuid4().hex[:16],
'display_name': 'Гонка регистрации',
'password': 'Пароль:с-двоеточием-123',
}
def register(_):
local = Client(args.base_url, args.ca_file)
return local.call('POST', '/api/v1/users', [201, 409], body=registration)['status']
with ThreadPoolExecutor(max_workers=6) as pool:
statuses = list(pool.map(register, range(6)))
check(statuses.count(201) == 1 and statuses.count(409) == 5, 'гонка регистрации не защищена')
session = client.call('POST', '/api/v1/auth/sessions', 201,
headers={'Authorization': 'Basic ' + base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()}, schema='Session')['json']
actor = {'token': session['token']}
client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
# Даже прогретый Redis не должен разрешать отозванную сессию.
client.call('GET', '/api/v1/users/me', 401, actor=actor)
def send_batch(worker_id):
local = Client(args.base_url, args.ca_file)
result = []
for index in range(10):
response = local.message(
alice,
chat,
"параллельное-%d-%d" % (worker_id, index),
)["json"]
result.append(response["id"])
return result
with ThreadPoolExecutor(max_workers=10) as pool:
created_ids = [
message_id
for batch in pool.map(send_batch, range(10))
for message_id in batch
]
check(len(created_ids) == 100, "не все параллельные запросы вернули ответ")
check(len(set(created_ids)) == 100, "параллельные запросы вернули повторяющиеся ID")
received = []
cursor = None
while True:
path = chat_path + "/messages?limit=17"
if cursor is not None:
path += "&cursor=" + quote(cursor, safe="")
page = client.call("GET", path, actor=bob, schema="MessagePage")["json"]
received.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
concurrent_messages = [
message for message in received if message["text"].startswith("параллельное-")
]
received_ids = [message["id"] for message in concurrent_messages]
check(len(received_ids) == 100, "в истории нет ровно 100 параллельно созданных сообщений")
check(len(set(received_ids)) == 100, "в истории есть повторяющиеся сообщения")
check(set(received_ids) == set(created_ids), "ID созданных и прочитанных сообщений не совпадают")
print(
json.dumps(
{
"результат": "ПРОЙДЕНО",
"гонка_регистрации": "1 создан, 5 конфликтов",
"unicode_пароль_и_logout_с_кэшем": "ПРОЙДЕНО",
"параллельных_клиентов": 10,
"создано_сообщений": len(created_ids),
"уникальных_сообщений": len(set(received_ids)),
},
ensure_ascii=False,
)
)
if __name__ == "__main__":
run(main)