forked from mtusi2026/mtusi2026lab3
ЛР 3 — БВТ2304 — Черников
HAProxy перед двумя репликами API, X-Instance-Id, общая идемпотентность отправки сообщения в PostgreSQL, двухшаговая остановка реплики по SIGTERM, лимиты CPU/RAM, хуки stop-one и restart. Проверки отказов, эксперимент и поочерёдное обновление в scripts/lab3_checks.py, отчёт в REPORT.md, результаты в evidence/, команды для показа в DEMO.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
"""Небольшой HTTP-клиент для собственных тестов. Только стандартная библиотека, Python 3.9+.
|
||||
|
||||
Стенд должен быть уже запущен. Адрес берётся из переменной окружения BASE_URL.
|
||||
По умолчанию 127.0.0.1, а не localhost: в Windows localhost сначала пробует IPv6
|
||||
и каждый запрос к IPv4-порту занимает около двух секунд.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from urllib.parse import quote
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8080').rstrip('/')
|
||||
TIMEOUT = 10
|
||||
USER_FIELDS = ('id', 'username', 'display_name', 'created_at')
|
||||
# Значение по умолчанию для key: новый случайный Idempotency-Key у каждого POST сообщения.
|
||||
AUTO = object()
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, status, headers, body):
|
||||
self.status = status
|
||||
self.headers = headers
|
||||
self.body = body
|
||||
self.json = json.loads(body) if body else None
|
||||
|
||||
|
||||
def request(method, path, user=None, body=None, raw=None, headers=None, base_url=None, key=AUTO):
|
||||
"""Один запрос. user — словарь с token (Bearer); body — объект для JSON; raw — готовые байты.
|
||||
|
||||
key — Idempotency-Key для POST сообщения: по умолчанию новый случайный, None — без заголовка.
|
||||
"""
|
||||
all_headers = {'Accept': 'application/json'}
|
||||
if user is not None:
|
||||
all_headers['Authorization'] = 'Bearer ' + user['token']
|
||||
if key is AUTO:
|
||||
key = uuid.uuid4().hex if method == 'POST' and path.endswith('/messages') else None
|
||||
if key is not None:
|
||||
all_headers['Idempotency-Key'] = key
|
||||
if body is not None:
|
||||
raw = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||||
if raw is not None:
|
||||
all_headers['Content-Type'] = 'application/json'
|
||||
all_headers.update(headers or {})
|
||||
req = urllib.request.Request((base_url or BASE_URL) + path, data=raw, headers=all_headers, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(req, timeout=TIMEOUT)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
result = Response(response.code, response.headers, response.read())
|
||||
# Общие требования контракта ко всем ответам.
|
||||
assert result.headers.get('X-Request-Id'), 'no X-Request-Id in response'
|
||||
assert result.headers.get('X-Instance-Id'), 'no X-Instance-Id in response'
|
||||
if result.status == 204:
|
||||
assert not result.body, '204 must not have a body'
|
||||
return result
|
||||
assert result.headers.get_content_type() == 'application/json', 'response is not JSON'
|
||||
if result.status >= 400:
|
||||
error = result.json['error']
|
||||
assert set(error) == {'code', 'message', 'request_id'}, 'unexpected error fields'
|
||||
assert error['message'], 'empty error message'
|
||||
assert error['request_id'] == result.headers['X-Request-Id'], 'request_id differs from header'
|
||||
return result
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
"""Значение заголовка Authorization: Basic base64(username:password) в UTF-8."""
|
||||
return 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def unique_username(prefix='t'):
|
||||
return prefix + '_' + uuid.uuid4().hex[:16]
|
||||
|
||||
|
||||
def new_password():
|
||||
# Кириллица и двоеточие: проверяем UTF-8 и деление Basic по первому двоеточию.
|
||||
return 'Пароль:' + uuid.uuid4().hex
|
||||
|
||||
|
||||
def register(username=None, password=None, display_name='Тестовый пользователь'):
|
||||
body = {'username': username or unique_username(), 'display_name': display_name, 'password': password or new_password()}
|
||||
return request('POST', '/api/v1/users', body=body), body
|
||||
|
||||
|
||||
def login(username, password, base_url=None):
|
||||
return request('POST', '/api/v1/auth/sessions', headers={'Authorization': basic(username, password)},
|
||||
base_url=base_url)
|
||||
|
||||
|
||||
def new_user(display_name='Тестовый пользователь', base_url=None):
|
||||
"""Зарегистрированный пользователь с действующим токеном: поля User + token + password."""
|
||||
response, body = register(display_name=display_name)
|
||||
assert response.status == 201, 'user was not created: %d' % response.status
|
||||
session = login(body['username'], body['password'], base_url=base_url)
|
||||
assert session.status == 201, 'login failed: %d' % session.status
|
||||
return dict(response.json, token=session.json['token'], password=body['password'])
|
||||
|
||||
|
||||
def public(user):
|
||||
"""Только поля схемы User: так пользователь выглядит в ответах API."""
|
||||
return {field: user[field] for field in USER_FIELDS}
|
||||
|
||||
|
||||
def new_chat(owner, members, title='Тестовый чат'):
|
||||
body = {'title': title, 'member_ids': [member['id'] for member in members]}
|
||||
response = request('POST', '/api/v1/chats', user=owner, body=body)
|
||||
assert response.status == 201, 'chat was not created: %d' % response.status
|
||||
return response.json
|
||||
|
||||
|
||||
def send(user, chat, text, key=AUTO):
|
||||
return request('POST', '/api/v1/chats/%s/messages' % chat['id'], user=user, body={'text': text}, key=key)
|
||||
|
||||
|
||||
def instance(response):
|
||||
"""Какая реплика API ответила."""
|
||||
return response.headers['X-Instance-Id']
|
||||
|
||||
|
||||
def pages(path, user, limit):
|
||||
"""Обходит все страницы списка и возвращает их как список списков."""
|
||||
result = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = '%s?limit=%d' % (path, limit)
|
||||
if cursor:
|
||||
url += '&cursor=' + quote(cursor, safe='')
|
||||
response = request('GET', url, user=user)
|
||||
assert response.status == 200, 'page was not read: %d' % response.status
|
||||
result.append(response.json['items'])
|
||||
cursor = response.json['next_cursor']
|
||||
if cursor is None:
|
||||
return result
|
||||
assert len(result) < 1000, 'pagination does not finish'
|
||||
|
||||
|
||||
def order_key(item):
|
||||
"""Порядок из контракта: (created_at, id) по возрастанию."""
|
||||
created_at = datetime.fromisoformat(item['created_at'][:-1] + '+00:00')
|
||||
return created_at, uuid.UUID(item['id']).int
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка защиты от гонок: N клиентов одновременно отправляют сообщения в один чат.
|
||||
|
||||
python student-tests/race.py --output evidence/race.json
|
||||
|
||||
Каждый клиент — отдельный пользователь и отдельный поток. Все потоки стартуют
|
||||
одновременно, затем история читается постранично и сравнивается с отправленным.
|
||||
Код возврата 0 — в истории ровно столько уникальных сообщений, сколько отправлено.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import api
|
||||
|
||||
|
||||
def run_race(clients=10, per_client=10, page_size=7):
|
||||
users = [api.new_user('Клиент %d' % n) for n in range(clients)]
|
||||
chat = api.new_chat(users[0], users, title='Проверка гонок')
|
||||
start = threading.Barrier(clients)
|
||||
|
||||
def client(index):
|
||||
start.wait()
|
||||
return [api.send(users[index], chat, 'race client=%d message=%d' % (index, n)) for n in range(per_client)]
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=clients) as pool:
|
||||
responses = [response for batch in pool.map(client, range(clients)) for response in batch]
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
accepted = [response.json for response in responses if response.status == 201]
|
||||
pages = api.pages('/api/v1/chats/%s/messages' % chat['id'], users[-1], page_size)
|
||||
history = [message for page in pages for message in page]
|
||||
per_sender = Counter(message['sender_id'] for message in history)
|
||||
expected = clients * per_client
|
||||
summary = {
|
||||
'base_url': api.BASE_URL,
|
||||
'clients': clients,
|
||||
'messages_per_client': per_client,
|
||||
'sent': len(responses),
|
||||
'accepted_201': len(accepted),
|
||||
'history_total': len(history),
|
||||
'history_unique_ids': len({message['id'] for message in history}),
|
||||
'history_unique_texts': len({message['text'] for message in history}),
|
||||
'history_matches_accepted': sorted(m['id'] for m in history) == sorted(m['id'] for m in accepted),
|
||||
'senders_in_history': len(per_sender),
|
||||
'min_messages_per_sender': min(per_sender.values(), default=0),
|
||||
'max_messages_per_sender': max(per_sender.values(), default=0),
|
||||
'ordered_by_created_at_and_id': history == sorted(history, key=api.order_key),
|
||||
'pages_read': len(pages),
|
||||
'page_size': page_size,
|
||||
'send_elapsed_seconds': round(elapsed, 3),
|
||||
}
|
||||
summary['ok'] = (
|
||||
summary['accepted_201'] == expected
|
||||
and summary['history_total'] == expected
|
||||
and summary['history_unique_ids'] == expected
|
||||
and summary['history_unique_texts'] == expected
|
||||
and summary['history_matches_accepted']
|
||||
and summary['senders_in_history'] == clients
|
||||
and summary['min_messages_per_sender'] == summary['max_messages_per_sender'] == per_client
|
||||
and summary['ordered_by_created_at_and_id']
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Concurrent message race check; creates synthetic users and messages')
|
||||
parser.add_argument('--clients', type=int, default=10)
|
||||
parser.add_argument('--per-client', type=int, default=10)
|
||||
parser.add_argument('--output', default=None, help='Optional JSON file for the summary')
|
||||
args = parser.parse_args()
|
||||
summary = run_race(args.clients, args.per_client)
|
||||
text = json.dumps(summary, indent=2)
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as file:
|
||||
file.write(text + '\n')
|
||||
print(text)
|
||||
print('PASS' if summary['ok'] else 'FAIL')
|
||||
return 0 if summary['ok'] else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Доступ к чатам: аутентификация (кто ты) отдельно от доступа к конкретному чату (можно ли тебе сюда)."""
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
import api
|
||||
|
||||
|
||||
class AuthenticationOrderTest(unittest.TestCase):
|
||||
def test_authentication_is_checked_before_body_and_resource(self):
|
||||
# Без токена сервер не сообщает ни об ошибке JSON, ни о наличии чата.
|
||||
self.assertEqual(api.request('POST', '/api/v1/chats', raw=b'{broken').status, 401)
|
||||
owner = api.new_user()
|
||||
chat = api.new_chat(owner, [owner])
|
||||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||||
self.assertEqual(api.request('GET', path).status, 401)
|
||||
self.assertEqual(api.request('POST', path, raw=b'{broken').status, 401)
|
||||
|
||||
def test_registration_does_not_need_a_token(self):
|
||||
response, _ = api.register()
|
||||
self.assertEqual(response.status, 201)
|
||||
|
||||
|
||||
class ForeignChatTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.alice, cls.bob, cls.eve = api.new_user('Алиса'), api.new_user('Боб'), api.new_user('Ева')
|
||||
cls.chat = api.new_chat(cls.alice, [cls.alice, cls.bob])
|
||||
cls.path = '/api/v1/chats/' + cls.chat['id']
|
||||
assert api.send(cls.alice, cls.chat, 'секрет участников').status == 201
|
||||
|
||||
def assert_not_found(self, response):
|
||||
self.assertEqual(response.status, 404)
|
||||
self.assertEqual(response.json['error']['code'], 'not_found')
|
||||
|
||||
def test_outsider_cannot_get_chat(self):
|
||||
self.assert_not_found(api.request('GET', self.path, user=self.eve))
|
||||
|
||||
def test_outsider_cannot_read_history(self):
|
||||
self.assert_not_found(api.request('GET', self.path + '/messages', user=self.eve))
|
||||
|
||||
def test_outsider_cannot_write(self):
|
||||
self.assert_not_found(api.send(self.eve, self.chat, 'чужое сообщение'))
|
||||
# Даже с неверным телом посторонний видит 404, а не подсказку о валидации.
|
||||
self.assert_not_found(api.request('POST', self.path + '/messages', user=self.eve, body={'text': ''}))
|
||||
history = [m for page in api.pages(self.path + '/messages', self.alice, 100) for m in page]
|
||||
self.assertNotIn('чужое сообщение', [m['text'] for m in history])
|
||||
self.assertNotIn(self.eve['id'], [m['sender_id'] for m in history])
|
||||
|
||||
def test_foreign_chat_looks_like_missing_chat(self):
|
||||
foreign = api.request('GET', self.path, user=self.eve)
|
||||
missing = api.request('GET', '/api/v1/chats/' + str(uuid.uuid4()), user=self.eve)
|
||||
self.assert_not_found(missing)
|
||||
self.assertEqual(foreign.json['error']['code'], missing.json['error']['code'])
|
||||
self.assertEqual(foreign.json['error']['message'], missing.json['error']['message'])
|
||||
|
||||
def test_chat_list_contains_only_own_chats(self):
|
||||
def chat_ids(user):
|
||||
return [chat['id'] for page in api.pages('/api/v1/chats', user, 100) for chat in page]
|
||||
|
||||
self.assertIn(self.chat['id'], chat_ids(self.alice))
|
||||
self.assertIn(self.chat['id'], chat_ids(self.bob))
|
||||
self.assertEqual(chat_ids(self.eve), [])
|
||||
|
||||
def test_every_member_can_read_and_write(self):
|
||||
self.assertEqual(api.request('GET', self.path, user=self.bob).json, self.chat)
|
||||
sent = api.send(self.bob, self.chat, 'ответ Боба')
|
||||
self.assertEqual(sent.status, 201)
|
||||
self.assertEqual(sent.json['sender_id'], self.bob['id'])
|
||||
|
||||
def test_x_user_id_does_not_open_a_foreign_chat(self):
|
||||
# Ева подставляет id Алисы: доступ решает только владелец токена.
|
||||
response = api.request('GET', self.path, user=self.eve, headers={'X-User-Id': self.alice['id']})
|
||||
self.assert_not_found(response)
|
||||
|
||||
def test_invalid_chat_id_is_400(self):
|
||||
for suffix in ('', '/messages'):
|
||||
with self.subTest(suffix=suffix):
|
||||
response = api.request('GET', '/api/v1/chats/not-a-uuid' + suffix, user=self.alice)
|
||||
self.assertEqual(response.status, 400)
|
||||
|
||||
def test_unknown_route_is_404(self):
|
||||
self.assert_not_found(api.request('GET', '/api/v1/unknown', user=self.alice))
|
||||
self.assert_not_found(api.request('DELETE', self.path, user=self.alice))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Балансировка: запросы одной сессии обслуживают разные реплики, состояние у них общее."""
|
||||
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()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Параллельные запросы не должны терять, дублировать или портить данные."""
|
||||
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()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Идемпотентность отправки сообщения: Idempotency-Key общий для всех реплик."""
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import api
|
||||
|
||||
|
||||
class IdempotencyTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.alice, cls.bob = api.new_user('Алиса'), api.new_user('Боб')
|
||||
cls.chat = api.new_chat(cls.alice, [cls.alice, cls.bob])
|
||||
cls.path = '/api/v1/chats/%s/messages' % cls.chat['id']
|
||||
|
||||
def history(self):
|
||||
return [m for page in api.pages(self.path, self.alice, 100) for m in page]
|
||||
|
||||
def test_replay_returns_the_same_message(self):
|
||||
key = uuid.uuid4().hex
|
||||
first = api.send(self.alice, self.chat, 'повтор ' + key, key=key)
|
||||
second = api.send(self.alice, self.chat, 'повтор ' + key, key=key)
|
||||
self.assertEqual((first.status, second.status), (201, 201))
|
||||
self.assertEqual(second.json, first.json)
|
||||
self.assertEqual([m['text'] for m in self.history()].count('повтор ' + key), 1)
|
||||
|
||||
def test_same_key_with_another_body_is_409(self):
|
||||
key = uuid.uuid4().hex
|
||||
self.assertEqual(api.send(self.alice, self.chat, 'первое тело', key=key).status, 201)
|
||||
response = api.send(self.alice, self.chat, 'другое тело', key=key)
|
||||
self.assertEqual(response.status, 409)
|
||||
self.assertEqual(response.json['error']['code'], 'conflict')
|
||||
self.assertNotIn('другое тело', [m['text'] for m in self.history()])
|
||||
|
||||
def test_json_formatting_does_not_matter(self):
|
||||
# Пробелы и запись Unicode в JSON не меняют смысл тела: это тот же повтор.
|
||||
key = uuid.uuid4().hex
|
||||
first = api.request('POST', self.path, user=self.alice, raw='{"text":"Привет"}'.encode(), key=key)
|
||||
second = api.request('POST', self.path, user=self.alice, raw=b'{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442" }', key=key)
|
||||
self.assertEqual((first.status, second.status), (201, 201))
|
||||
self.assertEqual(second.json, first.json)
|
||||
|
||||
def test_missing_key_is_400(self):
|
||||
response = api.send(self.alice, self.chat, 'без ключа', key=None)
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertNotIn('без ключа', [m['text'] for m in self.history()])
|
||||
|
||||
def test_invalid_keys_are_400(self):
|
||||
# Кириллица уходит в заголовок байтами UTF-8, как её отправил бы обычный клиент.
|
||||
cyrillic = 'кириллица'.encode('utf-8').decode('latin-1')
|
||||
for key in ('', 'a' * 129, cyrillic, 'with space', 'semi;colon', 'slash/key'):
|
||||
with self.subTest(key=key):
|
||||
self.assertEqual(api.send(self.alice, self.chat, 'ключ', key=key).status, 400)
|
||||
|
||||
def test_key_format_limits_are_accepted(self):
|
||||
# Свой чат на каждый запуск: область ключа включает чат, поэтому ключи не пересекаются с прошлыми.
|
||||
chat = api.new_chat(self.alice, [self.alice], title='Форматы ключей')
|
||||
for key in ('a' * 128, 'A.b_c:d-1', '0'):
|
||||
with self.subTest(key=key[:20]):
|
||||
self.assertEqual(api.send(self.alice, chat, 'формат ' + key, key=key).status, 201)
|
||||
|
||||
def test_key_scope_is_user_and_chat(self):
|
||||
key = uuid.uuid4().hex
|
||||
other_chat = api.new_chat(self.alice, [self.alice], title='Другой чат')
|
||||
first = api.send(self.alice, self.chat, 'одинаковый ключ', key=key)
|
||||
in_other_chat = api.send(self.alice, other_chat, 'одинаковый ключ', key=key)
|
||||
by_other_user = api.send(self.bob, self.chat, 'одинаковый ключ', key=key)
|
||||
self.assertEqual({first.status, in_other_chat.status, by_other_user.status}, {201})
|
||||
self.assertEqual(len({first.json['id'], in_other_chat.json['id'], by_other_user.json['id']}), 3)
|
||||
|
||||
def test_failed_validation_is_not_remembered(self):
|
||||
# Ответ 400 не фиксируется: тот же ключ можно использовать с исправленным телом.
|
||||
key = uuid.uuid4().hex
|
||||
self.assertEqual(api.send(self.alice, self.chat, ' ', key=key).status, 400)
|
||||
self.assertEqual(api.send(self.alice, self.chat, 'исправлено', key=key).status, 201)
|
||||
|
||||
def test_replay_checks_the_session_again(self):
|
||||
user = api.new_user('Выход')
|
||||
chat = api.new_chat(user, [user])
|
||||
key = uuid.uuid4().hex
|
||||
self.assertEqual(api.send(user, chat, 'до выхода', key=key).status, 201)
|
||||
api.request('DELETE', '/api/v1/auth/sessions/current', user=user)
|
||||
self.assertEqual(api.send(user, chat, 'до выхода', key=key).status, 401)
|
||||
|
||||
def test_parallel_requests_with_one_key_create_one_message(self):
|
||||
# Одновременные повторы расходятся по разным репликам и всё равно создают одно сообщение.
|
||||
key = uuid.uuid4().hex
|
||||
text = 'параллельно ' + key
|
||||
attempts = 20
|
||||
start = threading.Barrier(attempts)
|
||||
|
||||
def post(_):
|
||||
start.wait()
|
||||
return api.send(self.alice, self.chat, text, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=attempts) as pool:
|
||||
responses = list(pool.map(post, range(attempts)))
|
||||
self.assertEqual({response.status for response in responses}, {201})
|
||||
self.assertEqual(len({response.json['id'] for response in responses}), 1)
|
||||
self.assertGreaterEqual(len({api.instance(response) for response in responses}), 2)
|
||||
self.assertEqual([m['text'] for m in self.history()].count(text), 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Keyset-пагинация истории сообщений и списка чатов."""
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
|
||||
import api
|
||||
|
||||
|
||||
class MessagePaginationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.user = api.new_user()
|
||||
cls.chat = api.new_chat(cls.user, [cls.user])
|
||||
cls.path = '/api/v1/chats/%s/messages' % cls.chat['id']
|
||||
cls.sent = [api.send(cls.user, cls.chat, 'сообщение %d' % n).json for n in range(25)]
|
||||
|
||||
def get(self, query):
|
||||
return api.request('GET', self.path + query, user=self.user)
|
||||
|
||||
def test_walk_over_several_pages(self):
|
||||
pages = api.pages(self.path, self.user, 10)
|
||||
self.assertEqual([len(page) for page in pages], [10, 10, 5])
|
||||
history = [message for page in pages for message in page]
|
||||
# Ничего не потеряно, не повторено и не переставлено.
|
||||
self.assertEqual(history, self.sent)
|
||||
self.assertEqual(history, sorted(history, key=api.order_key))
|
||||
self.assertEqual(len({message['id'] for message in history}), 25)
|
||||
|
||||
def test_one_message_per_page(self):
|
||||
pages = api.pages(self.path, self.user, 1)
|
||||
self.assertEqual(len(pages), 25)
|
||||
self.assertEqual([page[0] for page in pages], self.sent)
|
||||
|
||||
def test_last_full_page_has_no_cursor(self):
|
||||
# 25 сообщений по 5: на пятой странице следующей записи нет, cursor сразу null.
|
||||
pages = api.pages(self.path, self.user, 5)
|
||||
self.assertEqual([len(page) for page in pages], [5, 5, 5, 5, 5])
|
||||
|
||||
def test_default_and_maximum_limit(self):
|
||||
self.assertEqual(len(self.get('').json['items']), 25)
|
||||
everything = self.get('?limit=100').json
|
||||
self.assertEqual(everything['items'], self.sent)
|
||||
self.assertIsNone(everything['next_cursor'])
|
||||
|
||||
def test_limit_can_change_between_pages(self):
|
||||
first = self.get('?limit=3').json
|
||||
second = self.get('?limit=20&cursor=' + quote(first['next_cursor'], safe='')).json
|
||||
self.assertEqual(first['items'] + second['items'], self.sent[:23])
|
||||
self.assertIsNotNone(second['next_cursor'])
|
||||
|
||||
def test_invalid_limit_is_400(self):
|
||||
for limit in ('0', '101', '-1', '1.5', 'abc', '', '1e2', '٣'):
|
||||
with self.subTest(limit=limit):
|
||||
response = self.get('?limit=' + quote(limit))
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertEqual(response.json['error']['code'], 'invalid_request')
|
||||
|
||||
def test_invalid_cursor_is_400(self):
|
||||
for cursor in ('garbage', '', '!!!', 'AAAA', quote('курсор')):
|
||||
with self.subTest(cursor=cursor):
|
||||
self.assertEqual(self.get('?cursor=' + cursor).status, 400)
|
||||
|
||||
def test_cursor_from_another_chat_is_400(self):
|
||||
other = api.new_chat(self.user, [self.user], title='Другой чат')
|
||||
for n in range(3):
|
||||
api.send(self.user, other, 'в другом чате %d' % n)
|
||||
other_cursor = api.request('GET', '/api/v1/chats/%s/messages?limit=1' % other['id'], user=self.user).json['next_cursor']
|
||||
self.assertIsNotNone(other_cursor)
|
||||
self.assertEqual(self.get('?cursor=' + quote(other_cursor, safe='')).status, 400)
|
||||
# Cursor списка чатов тоже не подходит к истории сообщений.
|
||||
chats_cursor = api.request('GET', '/api/v1/chats?limit=1', user=self.user).json['next_cursor']
|
||||
self.assertEqual(self.get('?cursor=' + quote(chats_cursor, safe='')).status, 400)
|
||||
|
||||
|
||||
class DefaultLimitTest(unittest.TestCase):
|
||||
def test_default_limit_is_50(self):
|
||||
user = api.new_user()
|
||||
chat = api.new_chat(user, [user])
|
||||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||||
for n in range(55):
|
||||
api.send(user, chat, 'сообщение %d' % n)
|
||||
first = api.request('GET', path, user=user).json
|
||||
self.assertEqual(len(first['items']), 50)
|
||||
rest = api.request('GET', path + '?cursor=' + quote(first['next_cursor'], safe=''), user=user).json
|
||||
self.assertEqual(len(rest['items']), 5)
|
||||
self.assertIsNone(rest['next_cursor'])
|
||||
|
||||
|
||||
class GrowingHistoryTest(unittest.TestCase):
|
||||
def test_empty_history(self):
|
||||
user = api.new_user()
|
||||
chat = api.new_chat(user, [user])
|
||||
page = api.request('GET', '/api/v1/chats/%s/messages' % chat['id'], user=user).json
|
||||
self.assertEqual(page, {'items': [], 'next_cursor': None})
|
||||
|
||||
def test_messages_sent_during_walk_are_not_lost(self):
|
||||
alice, bob = api.new_user(), api.new_user()
|
||||
chat = api.new_chat(alice, [alice, bob])
|
||||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||||
before = [api.send(alice, chat, 'до %d' % n).json for n in range(4)]
|
||||
first = api.request('GET', path + '?limit=2', user=bob).json
|
||||
# Пока Боб читает, Алиса дописывает; cursor Боба продолжает работать у любого участника.
|
||||
after = [api.send(alice, chat, 'после %d' % n).json for n in range(3)]
|
||||
rest = api.request('GET', path + '?limit=100&cursor=' + quote(first['next_cursor'], safe=''), user=alice).json
|
||||
self.assertEqual(first['items'] + rest['items'], before + after)
|
||||
|
||||
|
||||
class ChatListPaginationTest(unittest.TestCase):
|
||||
def test_chats_are_paged_in_creation_order(self):
|
||||
user = api.new_user()
|
||||
created = [api.new_chat(user, [user], title='Чат %d' % n) for n in range(5)]
|
||||
pages = api.pages('/api/v1/chats', user, 2)
|
||||
self.assertEqual([len(page) for page in pages], [2, 2, 1])
|
||||
chats = [chat for page in pages for chat in page]
|
||||
self.assertEqual(chats, created)
|
||||
self.assertEqual(chats, sorted(chats, key=api.order_key))
|
||||
|
||||
def test_cursor_of_another_user_is_400(self):
|
||||
alice, bob = api.new_user(), api.new_user()
|
||||
for n in range(2):
|
||||
api.new_chat(alice, [alice, bob], title='Общий %d' % n)
|
||||
alice_cursor = api.request('GET', '/api/v1/chats?limit=1', user=alice).json['next_cursor']
|
||||
response = api.request('GET', '/api/v1/chats?limit=1&cursor=' + quote(alice_cursor, safe=''), user=bob)
|
||||
self.assertEqual(response.status, 400)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Вход по Basic, Bearer-сессии, выход. X-User-Id из lab1 больше не даёт доступа."""
|
||||
import base64
|
||||
import unittest
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import api
|
||||
|
||||
ME = '/api/v1/users/me'
|
||||
SESSIONS = '/api/v1/auth/sessions'
|
||||
|
||||
|
||||
def b64(raw):
|
||||
return base64.b64encode(raw).decode('ascii')
|
||||
|
||||
|
||||
class LoginTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
response, cls.registration = api.register(display_name='Вход')
|
||||
assert response.status == 201
|
||||
cls.user = response.json
|
||||
|
||||
def assert_login_rejected(self, response):
|
||||
self.assertEqual(response.status, 401)
|
||||
self.assertEqual(response.json['error']['code'], 'unauthorized')
|
||||
self.assertEqual(response.headers['WWW-Authenticate'], 'Basic realm="messenger", charset="UTF-8"')
|
||||
return response.json['error']['message']
|
||||
|
||||
def test_successful_login(self):
|
||||
response = api.login(self.registration['username'], self.registration['password'])
|
||||
self.assertEqual(response.status, 201)
|
||||
session = response.json
|
||||
self.assertEqual(set(session), {'token', 'token_type', 'expires_at', 'user'})
|
||||
self.assertEqual(session['token_type'], 'Bearer')
|
||||
self.assertEqual(session['user'], self.user)
|
||||
# Непрозрачный случайный токен: 256 бит в base64url — 43 символа; это не id и не username.
|
||||
self.assertGreaterEqual(len(session['token']), 43)
|
||||
self.assertNotIn(self.user['id'], session['token'])
|
||||
self.assertNotIn(self.user['username'], session['token'])
|
||||
expires_at = datetime.fromisoformat(session['expires_at'][:-1] + '+00:00')
|
||||
self.assertGreater(expires_at, datetime.now(timezone.utc) + timedelta(seconds=60))
|
||||
me = api.request('GET', ME, headers={'Authorization': 'Bearer ' + session['token']})
|
||||
self.assertEqual(me.json, self.user)
|
||||
|
||||
def test_each_login_gives_a_new_token(self):
|
||||
first = api.login(self.registration['username'], self.registration['password']).json['token']
|
||||
second = api.login(self.registration['username'], self.registration['password']).json['token']
|
||||
self.assertNotEqual(first, second)
|
||||
for token in (first, second):
|
||||
self.assertEqual(api.request('GET', ME, headers={'Authorization': 'Bearer ' + token}).status, 200)
|
||||
|
||||
def test_registration_never_returns_password(self):
|
||||
response, _ = api.register()
|
||||
self.assertEqual(set(response.json), {'id', 'username', 'display_name', 'created_at'})
|
||||
|
||||
def test_wrong_password(self):
|
||||
self.assert_login_rejected(api.login(self.registration['username'], self.registration['password'] + 'x'))
|
||||
|
||||
def test_unknown_user_gets_the_same_answer(self):
|
||||
wrong_password = self.assert_login_rejected(api.login(self.registration['username'], 'Wrong-password-123'))
|
||||
unknown_user = self.assert_login_rejected(api.login(api.unique_username(), 'Wrong-password-123'))
|
||||
self.assertEqual(wrong_password, unknown_user)
|
||||
|
||||
def test_malformed_basic_header(self):
|
||||
for value in (
|
||||
'Basic',
|
||||
'Basic !!!not-base64!!!',
|
||||
'Basic ' + b64(b'no-colon-here'),
|
||||
'Basic ' + b64(b'\xff\xfe:invalid-utf8-password'),
|
||||
'Basic ' + b64(b'Upper_Case:Valid-password-123'),
|
||||
'Basic ' + b64(b'short:pw'),
|
||||
'Digest abc',
|
||||
'Bearer ' + uuid.uuid4().hex,
|
||||
):
|
||||
with self.subTest(value=value):
|
||||
response = api.request('POST', SESSIONS, headers={'Authorization': value})
|
||||
self.assert_login_rejected(response)
|
||||
self.assert_login_rejected(api.request('POST', SESSIONS))
|
||||
|
||||
def test_password_with_colons_and_unicode(self):
|
||||
password = 'Пароль:с:двоеточиями 👋'
|
||||
response, body = api.register(password=password)
|
||||
self.assertEqual(response.status, 201)
|
||||
self.assertEqual(api.login(body['username'], password).status, 201)
|
||||
self.assert_login_rejected(api.login(body['username'], 'Пароль:с:двоеточиями'))
|
||||
|
||||
def test_credentials_in_json_body_are_not_accepted(self):
|
||||
body = {'username': self.registration['username'], 'password': self.registration['password']}
|
||||
response = api.request('POST', SESSIONS, body=body)
|
||||
self.assertIn(response.status, (400, 401))
|
||||
self.assertNotIn('token', response.json)
|
||||
|
||||
|
||||
class BearerTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.alice = api.new_user('Алиса')
|
||||
cls.bob = api.new_user('Боб')
|
||||
|
||||
def assert_bearer_rejected(self, response):
|
||||
self.assertEqual(response.status, 401)
|
||||
self.assertEqual(response.json['error']['code'], 'unauthorized')
|
||||
self.assertEqual(response.headers['WWW-Authenticate'], 'Bearer realm="messenger"')
|
||||
|
||||
def test_protected_endpoints_need_a_token(self):
|
||||
for method, path in (('GET', ME), ('GET', '/api/v1/chats'), ('POST', '/api/v1/chats'),
|
||||
('GET', '/api/v1/chats/%s/messages' % uuid.uuid4()), ('DELETE', SESSIONS + '/current')):
|
||||
with self.subTest(method=method, path=path):
|
||||
self.assert_bearer_rejected(api.request(method, path))
|
||||
|
||||
def test_unknown_or_malformed_token(self):
|
||||
for value in ('Bearer ' + uuid.uuid4().hex * 2, 'Bearer', 'Bearer a b', 'Bearer ' + 'x' * 600,
|
||||
'Bearer ' + self.alice['id'], 'Token ' + self.alice['token']):
|
||||
with self.subTest(value=value[:40]):
|
||||
self.assert_bearer_rejected(api.request('GET', ME, headers={'Authorization': value}))
|
||||
|
||||
def test_basic_is_rejected_on_business_endpoints(self):
|
||||
value = api.basic(self.alice['username'], self.alice['password'])
|
||||
self.assert_bearer_rejected(api.request('GET', ME, headers={'Authorization': value}))
|
||||
|
||||
def test_x_user_id_is_ignored(self):
|
||||
self.assert_bearer_rejected(api.request('GET', ME, headers={'X-User-Id': self.alice['id']}))
|
||||
# Заголовок X-User-Id не меняет владельца сессии.
|
||||
me = api.request('GET', ME, user=self.alice, headers={'X-User-Id': self.bob['id']})
|
||||
self.assertEqual(me.json, api.public(self.alice))
|
||||
|
||||
def test_token_selects_the_user(self):
|
||||
self.assertEqual(api.request('GET', ME, user=self.alice).json, api.public(self.alice))
|
||||
self.assertEqual(api.request('GET', ME, user=self.bob).json, api.public(self.bob))
|
||||
|
||||
def test_scheme_name_is_case_insensitive(self):
|
||||
# RFC 7235: имя схемы авторизации не зависит от регистра.
|
||||
response = api.request('GET', ME, headers={'Authorization': 'bearer ' + self.alice['token']})
|
||||
self.assertEqual(response.status, 200)
|
||||
|
||||
|
||||
class LogoutTest(unittest.TestCase):
|
||||
def test_logout_revokes_only_the_current_token(self):
|
||||
user = api.new_user('Выход')
|
||||
other = api.login(user['username'], user['password']).json['token']
|
||||
response = api.request('DELETE', SESSIONS + '/current', user=user)
|
||||
self.assertEqual(response.status, 204)
|
||||
self.assertEqual(response.body, b'')
|
||||
# Отозванный токен больше не работает, повторный выход — тоже 401.
|
||||
self.assertEqual(api.request('GET', ME, user=user).status, 401)
|
||||
self.assertEqual(api.request('DELETE', SESSIONS + '/current', user=user).status, 401)
|
||||
# Другая сессия того же пользователя продолжает работать.
|
||||
self.assertEqual(api.request('GET', ME, headers={'Authorization': 'Bearer ' + other}).status, 200)
|
||||
|
||||
def test_login_again_after_logout(self):
|
||||
user = api.new_user('Снова')
|
||||
api.request('DELETE', SESSIONS + '/current', user=user)
|
||||
again = api.login(user['username'], user['password'])
|
||||
self.assertEqual(again.status, 201)
|
||||
self.assertNotEqual(again.json['token'], user['token'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Валидация входных данных: неверный JSON, пустое сообщение, дубликат username, пароль, Unicode."""
|
||||
import json
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
import api
|
||||
|
||||
USERS = '/api/v1/users'
|
||||
PASSWORD = 'Valid-password-123'
|
||||
|
||||
|
||||
def registration(**fields):
|
||||
"""Корректное тело регистрации; fields заменяют или добавляют поля."""
|
||||
body = {'username': api.unique_username(), 'display_name': 'Имя', 'password': PASSWORD}
|
||||
body.update(fields)
|
||||
return body
|
||||
|
||||
|
||||
class InvalidJsonTest(unittest.TestCase):
|
||||
def assert_invalid(self, response):
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertEqual(response.json['error']['code'], 'invalid_request')
|
||||
|
||||
def test_malformed_json_on_register(self):
|
||||
self.assert_invalid(api.request('POST', USERS, raw=b'{"username": "broken", '))
|
||||
|
||||
def test_malformed_json_on_message(self):
|
||||
user = api.new_user()
|
||||
chat = api.new_chat(user, [user])
|
||||
path = '/api/v1/chats/%s/messages' % chat['id']
|
||||
for raw in (b'not json', b'{"text": "no closing quote}', b'', b'{"text": }'):
|
||||
with self.subTest(raw=raw):
|
||||
self.assert_invalid(api.request('POST', path, user=user, raw=raw))
|
||||
# Неудачные запросы ничего не записали в историю.
|
||||
self.assertEqual(api.pages(path, user, 100), [[]])
|
||||
|
||||
def test_json_that_is_not_an_object(self):
|
||||
for raw in (b'[]', b'"text"', b'42', b'null'):
|
||||
with self.subTest(raw=raw):
|
||||
self.assert_invalid(api.request('POST', USERS, raw=raw))
|
||||
|
||||
def test_invalid_utf8(self):
|
||||
raw = json.dumps(registration(display_name='PLACEHOLDER')).encode().replace(b'PLACEHOLDER', b'\xff\xfe')
|
||||
self.assert_invalid(api.request('POST', USERS, raw=raw))
|
||||
|
||||
def test_lone_surrogate_is_rejected_not_crashed(self):
|
||||
# Всё остальное в теле корректно: ошибка именно в одиночном суррогате.
|
||||
raw = json.dumps(registration(display_name='PLACEHOLDER')).encode().replace(b'PLACEHOLDER', b'\\ud800')
|
||||
self.assert_invalid(api.request('POST', USERS, raw=raw))
|
||||
|
||||
def test_nul_character_is_rejected_not_crashed(self):
|
||||
# PostgreSQL не хранит символ NUL в text: без проверки это был бы 500.
|
||||
self.assert_invalid(api.request('POST', USERS, body=registration(display_name='a\x00b')))
|
||||
|
||||
def test_extra_fields(self):
|
||||
self.assert_invalid(api.request('POST', USERS, body=registration(is_admin=True)))
|
||||
|
||||
def test_wrong_types(self):
|
||||
for fields in ({'username': 12345}, {'display_name': ['Имя']}, {'display_name': None}, {'password': 123456789012345}):
|
||||
with self.subTest(fields=fields):
|
||||
self.assert_invalid(api.request('POST', USERS, body=registration(**fields)))
|
||||
|
||||
def test_wrong_content_type(self):
|
||||
raw = json.dumps(registration()).encode()
|
||||
self.assert_invalid(api.request('POST', USERS, raw=raw, headers={'Content-Type': 'text/plain'}))
|
||||
|
||||
|
||||
class UserValidationTest(unittest.TestCase):
|
||||
def test_duplicate_username_is_409(self):
|
||||
body = registration(display_name='Первый')
|
||||
first = api.request('POST', USERS, body=body)
|
||||
self.assertEqual(first.status, 201)
|
||||
# Совпадает только username: другие имя и пароль не помогают.
|
||||
second = api.request('POST', USERS, body=dict(body, display_name='Второй', password='Another-password-456'))
|
||||
self.assertEqual(second.status, 409)
|
||||
self.assertEqual(second.json['error']['code'], 'conflict')
|
||||
# Первый пользователь не изменился: входит со своим паролем и видит своё имя.
|
||||
session = api.login(body['username'], body['password'])
|
||||
self.assertEqual(session.json['user'], first.json)
|
||||
self.assertEqual(api.login(body['username'], 'Another-password-456').status, 401)
|
||||
|
||||
def test_bad_usernames(self):
|
||||
for username in ('ab', 'a' * 33, 'Alice', 'with space', 'дмитрий', 'dash-name', '', 'name\n', 'colon:name'):
|
||||
with self.subTest(username=username):
|
||||
self.assertEqual(api.request('POST', USERS, body=registration(username=username)).status, 400)
|
||||
|
||||
def test_username_length_limits_are_accepted(self):
|
||||
for length in (3, 32):
|
||||
with self.subTest(length=length):
|
||||
response = api.request('POST', USERS, body=registration(username=uuid.uuid4().hex[:length]))
|
||||
# Трёхсимвольное имя могло остаться от прошлого запуска: 409 тоже значит «имя допустимо».
|
||||
self.assertIn(response.status, (201, 409))
|
||||
|
||||
def test_bad_display_names(self):
|
||||
for display_name in ('', ' ', '\t\n', 'я' * 101):
|
||||
with self.subTest(display_name=display_name):
|
||||
self.assertEqual(api.request('POST', USERS, body=registration(display_name=display_name)).status, 400)
|
||||
|
||||
def test_bad_passwords(self):
|
||||
for password in ('a' * 11, 'я' * 11, 'a' * 129, ' ' * 12, '\t' * 20, 'pass\x00word-123'):
|
||||
with self.subTest(password=password[:20]):
|
||||
self.assertEqual(api.request('POST', USERS, body=registration(password=password)).status, 400)
|
||||
|
||||
def test_password_length_limits_are_accepted(self):
|
||||
# Длина считается в code points: 12 кириллических букв — это 24 байта UTF-8.
|
||||
for password in ('a' * 12, 'я' * 12, '👋' * 128):
|
||||
with self.subTest(length=len(password)):
|
||||
body = registration(password=password)
|
||||
self.assertEqual(api.request('POST', USERS, body=body).status, 201)
|
||||
self.assertEqual(api.login(body['username'], password).status, 201)
|
||||
|
||||
def test_missing_fields(self):
|
||||
for field in ('username', 'display_name', 'password'):
|
||||
with self.subTest(field=field):
|
||||
body = registration()
|
||||
del body[field]
|
||||
self.assertEqual(api.request('POST', USERS, body=body).status, 400)
|
||||
|
||||
def test_unicode_display_name_is_kept(self):
|
||||
# Длина считается в code points: 100 эмодзи — это 400 байт, но имя допустимо.
|
||||
for display_name in ('Дмитрий 👋', '李雷', '👋' * 100):
|
||||
with self.subTest(display_name=display_name):
|
||||
response = api.request('POST', USERS, body=registration(display_name=display_name))
|
||||
self.assertEqual(response.status, 201)
|
||||
self.assertEqual(response.json['display_name'], display_name)
|
||||
|
||||
|
||||
class MessageValidationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.user = api.new_user()
|
||||
cls.chat = api.new_chat(cls.user, [cls.user])
|
||||
cls.path = '/api/v1/chats/%s/messages' % cls.chat['id']
|
||||
|
||||
def test_empty_message_is_400(self):
|
||||
for text in ('', ' ', '\n\t \r\n', ' '):
|
||||
with self.subTest(text=text):
|
||||
response = api.send(self.user, self.chat, text)
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertEqual(response.json['error']['code'], 'invalid_request')
|
||||
|
||||
def test_missing_or_wrong_text(self):
|
||||
for body in ({}, {'text': None}, {'text': 123}, {'text': ['a']}, {'message': 'a'}):
|
||||
with self.subTest(body=body):
|
||||
self.assertEqual(api.request('POST', self.path, user=self.user, body=body).status, 400)
|
||||
|
||||
def test_sender_id_in_body_is_rejected(self):
|
||||
other = api.new_user()
|
||||
body = {'text': 'подмена отправителя', 'sender_id': other['id']}
|
||||
self.assertEqual(api.request('POST', self.path, user=self.user, body=body).status, 400)
|
||||
|
||||
def test_nul_in_text_is_400(self):
|
||||
self.assertEqual(api.send(self.user, self.chat, 'до\x00после').status, 400)
|
||||
|
||||
def test_text_length_limit(self):
|
||||
self.assertEqual(api.send(self.user, self.chat, 'я' * 4000).status, 201)
|
||||
self.assertEqual(api.send(self.user, self.chat, '👋' * 4000).status, 201)
|
||||
self.assertEqual(api.send(self.user, self.chat, 'я' * 4001).status, 400)
|
||||
|
||||
def test_unicode_text_is_kept(self):
|
||||
text = 'Привет, мир 👋 — 你好\nвторая строка'
|
||||
response = api.send(self.user, self.chat, text)
|
||||
self.assertEqual(response.status, 201)
|
||||
self.assertEqual(response.json['text'], text)
|
||||
self.assertEqual(response.json['sender_id'], self.user['id'])
|
||||
self.assertEqual(response.json['chat_id'], self.chat['id'])
|
||||
|
||||
def test_oversized_body_is_413(self):
|
||||
response = api.request('POST', self.path, user=self.user, body={'text': 'a' * 70000})
|
||||
self.assertEqual(response.status, 413)
|
||||
self.assertEqual(response.json['error']['code'], 'payload_too_large')
|
||||
|
||||
|
||||
class ChatValidationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.alice = api.new_user()
|
||||
cls.bob = api.new_user()
|
||||
|
||||
def create(self, title, member_ids):
|
||||
return api.request('POST', '/api/v1/chats', user=self.alice, body={'title': title, 'member_ids': member_ids})
|
||||
|
||||
def test_caller_must_be_a_member(self):
|
||||
self.assertEqual(self.create('Без меня', [self.bob['id']]).status, 400)
|
||||
|
||||
def test_duplicate_members(self):
|
||||
self.assertEqual(self.create('Дубликат', [self.alice['id'], self.bob['id'], self.bob['id']]).status, 400)
|
||||
# Тот же UUID в другом регистре — тоже дубликат.
|
||||
self.assertEqual(self.create('Дубликат', [self.alice['id'], self.alice['id'].upper()]).status, 400)
|
||||
|
||||
def test_unknown_member_rolls_back_the_whole_chat(self):
|
||||
# Чат вставляется первым, участник — вторым; ошибка на участнике откатывает и сам чат.
|
||||
title = 'Откат ' + uuid.uuid4().hex[:8]
|
||||
response = self.create(title, [self.alice['id'], str(uuid.uuid4())])
|
||||
self.assertEqual(response.status, 400)
|
||||
chats = [chat for page in api.pages('/api/v1/chats', self.alice, 100) for chat in page]
|
||||
self.assertNotIn(title, [chat['title'] for chat in chats])
|
||||
|
||||
def test_bad_member_ids(self):
|
||||
for member_ids in ([], 'not a list', [123], ['not-a-uuid'], None):
|
||||
with self.subTest(member_ids=member_ids):
|
||||
self.assertEqual(self.create('Чат', member_ids).status, 400)
|
||||
|
||||
def test_bad_titles(self):
|
||||
for title in ('', ' ', 'я' * 101, 5, 'a\x00b'):
|
||||
with self.subTest(title=title):
|
||||
self.assertEqual(self.create(title, [self.alice['id']]).status, 400)
|
||||
|
||||
def test_valid_chat_keeps_member_order(self):
|
||||
response = self.create('Проект по ВНП', [self.bob['id'], self.alice['id']])
|
||||
self.assertEqual(response.status, 201)
|
||||
self.assertEqual(response.json['title'], 'Проект по ВНП')
|
||||
self.assertEqual(response.json['member_ids'], [self.bob['id'], self.alice['id']])
|
||||
again = api.request('GET', '/api/v1/chats/' + response.json['id'], user=self.bob)
|
||||
self.assertEqual(again.json, response.json)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user