Files
mtusi2026lab2/student-tests/test_validation.py
ChernikovandClaude Opus 5.5 704ce48279 Возвращать 415 unsupported_media_type для неподдерживаемого Content-Type
Запрос с Content-Type, отличным от application/json, раньше получал 400
invalid_request. Теперь _json_body отвечает 415 unsupported_media_type
(ApiError через новую функцию unsupported_media_type в errors.py), как
предусмотрено контрактом. Повреждённый JSON с верным Content-Type по-прежнему
даёт 400. Тест проверяет точный код ответа на регистрации, создании чата и
отправке сообщения; число тестов 73 -> 76, evidence/tests.txt обновлён.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:14:04 +03:00

236 lines
12 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.
"""Валидация входных данных: неверный 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):
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 assert_unsupported_media_type(self, response):
self.assertEqual(response.status, 415)
self.assertEqual(response.json['error']['code'], 'unsupported_media_type')
def test_wrong_content_type_is_415(self):
raw = json.dumps(registration()).encode()
for content_type in ('text/plain', 'application/xml', 'application/x-www-form-urlencoded', 'application/jsonx'):
with self.subTest(content_type=content_type):
self.assert_unsupported_media_type(
api.request('POST', USERS, raw=raw, headers={'Content-Type': content_type}))
def test_wrong_content_type_on_chat_and_message_is_415(self):
user = api.new_user()
chat = api.new_chat(user, [user])
headers = {'Content-Type': 'text/plain'}
self.assert_unsupported_media_type(api.request(
'POST', '/api/v1/chats', user=user, raw=json.dumps({'title': 'Т', 'member_ids': [user['id']]}).encode(),
headers=headers))
self.assert_unsupported_media_type(api.request(
'POST', '/api/v1/chats/%s/messages' % chat['id'], user=user, raw=json.dumps({'text': 'привет'}).encode(), headers=headers))
self.assertEqual(api.pages('/api/v1/chats/%s/messages' % chat['id'], user, 100), [[]])
def test_json_content_type_with_charset_is_accepted(self):
raw = json.dumps(registration()).encode()
response = api.request('POST', USERS, raw=raw, headers={'Content-Type': 'application/json; charset=utf-8'})
self.assertEqual(response.status, 201)
def test_malformed_json_with_right_content_type_stays_400(self):
self.assert_invalid(api.request('POST', USERS, raw=b'{"username": ', headers={'Content-Type': 'application/json'}))
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)
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]))
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):
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):
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)
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()