forked from mtusi2026/mtusi2026lab2
Возвращать 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>
This commit is contained in:
@@ -165,7 +165,7 @@ migrate (одноразовый) ──> postgres: применяет migrations
|
|||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| 3: публичный smoke | `python tests/smoke.py --base-url http://127.0.0.1:8080` (`make test`) | `PASS: lab2 public API scenario` | evidence/tests.txt |
|
| 3: публичный smoke | `python tests/smoke.py --base-url http://127.0.0.1:8080` (`make test`) | `PASS: lab2 public API scenario` | evidence/tests.txt |
|
||||||
| 3: минимум lab1 с новой аутентификацией | `python -m unittest discover -s student-tests -v` | 73 теста `OK`: валидация, Unicode, членство, пагинация, ошибки | evidence/tests.txt |
|
| 3: минимум lab1 с новой аутентификацией | `python -m unittest discover -s student-tests -v` | 76 тестов `OK`: валидация (в том числе 415 для неподдерживаемого Content-Type), Unicode, членство, пагинация, ошибки | evidence/tests.txt |
|
||||||
| 3: данные и действующие сессии переживают рестарт API и хранилищ | `tests/resilience.py --mode persistence` с хуком `scripts/restart.cmd` (в Linux — `restart.sh`) | `PASS`; StartedAt у api, postgres и valkey сменился, volumes и их даты создания те же | evidence/lab2-checks.txt, раздел Full restart |
|
| 3: данные и действующие сессии переживают рестарт API и хранилищ | `tests/resilience.py --mode persistence` с хуком `scripts/restart.cmd` (в Linux — `restart.sh`) | `PASS`; StartedAt у api, postgres и valkey сменился, volumes и их даты создания те же | evidence/lab2-checks.txt, раздел Full restart |
|
||||||
| 3: сборка из чистого clone, миграции с нуля | Clone ветки, `init_secrets.py`, `docker compose up -d --build --wait` в отдельном проекте с новыми volumes | Образ собран; миграции на пустом volume — `applied_now=2`, повторно — `applied_now=0`; smoke, 73 теста и тест сохранности — PASS | evidence/clean-clone.txt |
|
| 3: сборка из чистого clone, миграции с нуля | Clone ветки, `init_secrets.py`, `docker compose up -d --build --wait` в отдельном проекте с новыми volumes | Образ собран; миграции на пустом volume — `applied_now=2`, повторно — `applied_now=0`; smoke, 73 теста и тест сохранности — PASS | evidence/clean-clone.txt |
|
||||||
| 3: ключи, уникальность username | Список `pg_constraint` и индексов | Есть PK, FK, UNIQUE и CHECK, индекс истории | evidence/lab2-checks.txt, раздел Migrations |
|
| 3: ключи, уникальность username | Список `pg_constraint` и индексов | Есть PK, FK, UNIQUE и CHECK, индекс истории | evidence/lab2-checks.txt, раздел Migrations |
|
||||||
|
|||||||
+1
-1
@@ -14,6 +14,6 @@
|
|||||||
"ordered_by_created_at_and_id": true,
|
"ordered_by_created_at_and_id": true,
|
||||||
"pages_read": 15,
|
"pages_read": 15,
|
||||||
"page_size": 7,
|
"page_size": 7,
|
||||||
"send_elapsed_seconds": 0.407,
|
"send_elapsed_seconds": 0.336,
|
||||||
"ok": true
|
"ok": true
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-4
@@ -1,5 +1,5 @@
|
|||||||
# Tests against the compose stand (docker compose up -d --build --wait).
|
# Tests against the compose stand (docker compose up -d --build --wait).
|
||||||
# Date: 2026-10-07 16:03 UTC
|
# Date: 2026-10-23 10:13 UTC
|
||||||
# Host: Windows 11, Docker Desktop engine 29.8.1, Compose 5.5.1, Python 3.14.7 for the test clients;
|
# Host: Windows 11, Docker Desktop engine 29.8.1, Compose 5.5.1, Python 3.14.7 for the test clients;
|
||||||
# Intel Core Ultra 9 185H (16 cores, 22 threads), 31 GiB RAM, no CPU/RAM limits on containers.
|
# Intel Core Ultra 9 185H (16 cores, 22 threads), 31 GiB RAM, no CPU/RAM limits on containers.
|
||||||
# Code: working tree of the solution branch (commit is given in REPORT.md).
|
# Code: working tree of the solution branch (commit is given in REPORT.md).
|
||||||
@@ -64,12 +64,15 @@ test_unknown_member_rolls_back_the_whole_chat (test_validation.ChatValidationTes
|
|||||||
test_valid_chat_keeps_member_order (test_validation.ChatValidationTest.test_valid_chat_keeps_member_order) ... ok
|
test_valid_chat_keeps_member_order (test_validation.ChatValidationTest.test_valid_chat_keeps_member_order) ... ok
|
||||||
test_extra_fields (test_validation.InvalidJsonTest.test_extra_fields) ... ok
|
test_extra_fields (test_validation.InvalidJsonTest.test_extra_fields) ... ok
|
||||||
test_invalid_utf8 (test_validation.InvalidJsonTest.test_invalid_utf8) ... ok
|
test_invalid_utf8 (test_validation.InvalidJsonTest.test_invalid_utf8) ... ok
|
||||||
|
test_json_content_type_with_charset_is_accepted (test_validation.InvalidJsonTest.test_json_content_type_with_charset_is_accepted) ... ok
|
||||||
test_json_that_is_not_an_object (test_validation.InvalidJsonTest.test_json_that_is_not_an_object) ... ok
|
test_json_that_is_not_an_object (test_validation.InvalidJsonTest.test_json_that_is_not_an_object) ... ok
|
||||||
test_lone_surrogate_is_rejected_not_crashed (test_validation.InvalidJsonTest.test_lone_surrogate_is_rejected_not_crashed) ... ok
|
test_lone_surrogate_is_rejected_not_crashed (test_validation.InvalidJsonTest.test_lone_surrogate_is_rejected_not_crashed) ... ok
|
||||||
test_malformed_json_on_message (test_validation.InvalidJsonTest.test_malformed_json_on_message) ... ok
|
test_malformed_json_on_message (test_validation.InvalidJsonTest.test_malformed_json_on_message) ... ok
|
||||||
test_malformed_json_on_register (test_validation.InvalidJsonTest.test_malformed_json_on_register) ... ok
|
test_malformed_json_on_register (test_validation.InvalidJsonTest.test_malformed_json_on_register) ... ok
|
||||||
|
test_malformed_json_with_right_content_type_stays_400 (test_validation.InvalidJsonTest.test_malformed_json_with_right_content_type_stays_400) ... ok
|
||||||
test_nul_character_is_rejected_not_crashed (test_validation.InvalidJsonTest.test_nul_character_is_rejected_not_crashed) ... ok
|
test_nul_character_is_rejected_not_crashed (test_validation.InvalidJsonTest.test_nul_character_is_rejected_not_crashed) ... ok
|
||||||
test_wrong_content_type (test_validation.InvalidJsonTest.test_wrong_content_type) ... ok
|
test_wrong_content_type_is_415 (test_validation.InvalidJsonTest.test_wrong_content_type_is_415) ... ok
|
||||||
|
test_wrong_content_type_on_chat_and_message_is_415 (test_validation.InvalidJsonTest.test_wrong_content_type_on_chat_and_message_is_415) ... ok
|
||||||
test_wrong_types (test_validation.InvalidJsonTest.test_wrong_types) ... ok
|
test_wrong_types (test_validation.InvalidJsonTest.test_wrong_types) ... ok
|
||||||
test_empty_message_is_400 (test_validation.MessageValidationTest.test_empty_message_is_400) ... ok
|
test_empty_message_is_400 (test_validation.MessageValidationTest.test_empty_message_is_400) ... ok
|
||||||
test_missing_or_wrong_text (test_validation.MessageValidationTest.test_missing_or_wrong_text) ... ok
|
test_missing_or_wrong_text (test_validation.MessageValidationTest.test_missing_or_wrong_text) ... ok
|
||||||
@@ -88,7 +91,7 @@ test_unicode_display_name_is_kept (test_validation.UserValidationTest.test_unico
|
|||||||
test_username_length_limits_are_accepted (test_validation.UserValidationTest.test_username_length_limits_are_accepted) ... ok
|
test_username_length_limits_are_accepted (test_validation.UserValidationTest.test_username_length_limits_are_accepted) ... ok
|
||||||
|
|
||||||
----------------------------------------------------------------------
|
----------------------------------------------------------------------
|
||||||
Ran 73 tests in 8.689s
|
Ran 76 tests in 7.839s
|
||||||
|
|
||||||
OK
|
OK
|
||||||
[exit code 0]
|
[exit code 0]
|
||||||
@@ -110,7 +113,7 @@ $ BASE_URL=http://127.0.0.1:8080 python student-tests/race.py --output evidence/
|
|||||||
"ordered_by_created_at_and_id": true,
|
"ordered_by_created_at_and_id": true,
|
||||||
"pages_read": 15,
|
"pages_read": 15,
|
||||||
"page_size": 7,
|
"page_size": 7,
|
||||||
"send_elapsed_seconds": 0.407,
|
"send_elapsed_seconds": 0.336,
|
||||||
"ok": true
|
"ok": true
|
||||||
}
|
}
|
||||||
PASS
|
PASS
|
||||||
|
|||||||
@@ -24,5 +24,9 @@ def bad_request(message):
|
|||||||
return ApiError(400, 'invalid_request', message)
|
return ApiError(400, 'invalid_request', message)
|
||||||
|
|
||||||
|
|
||||||
|
def unsupported_media_type(message):
|
||||||
|
return ApiError(415, 'unsupported_media_type', message)
|
||||||
|
|
||||||
|
|
||||||
def not_found():
|
def not_found():
|
||||||
return ApiError(404, 'not_found', 'Объект не найден')
|
return ApiError(404, 'not_found', 'Объект не найден')
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from urllib.parse import parse_qs
|
|||||||
|
|
||||||
from . import validation
|
from . import validation
|
||||||
from .db import UnknownMember, UsernameTaken
|
from .db import UnknownMember, UsernameTaken
|
||||||
from .errors import ApiError, Unavailable, bad_request, not_found
|
from .errors import ApiError, Unavailable, bad_request, not_found, unsupported_media_type
|
||||||
from .passwords import hash_password, verify_password
|
from .passwords import hash_password, verify_password
|
||||||
from .timeutil import format_time
|
from .timeutil import format_time
|
||||||
|
|
||||||
@@ -248,7 +248,7 @@ class RequestHandler(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
def _json_body(self, body):
|
def _json_body(self, body):
|
||||||
if self.headers.get_content_type() != 'application/json':
|
if self.headers.get_content_type() != 'application/json':
|
||||||
raise bad_request('Content-Type должен быть application/json')
|
raise unsupported_media_type('Content-Type должен быть application/json')
|
||||||
return body
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -57,9 +57,35 @@ class InvalidJsonTest(unittest.TestCase):
|
|||||||
with self.subTest(fields=fields):
|
with self.subTest(fields=fields):
|
||||||
self.assert_invalid(api.request('POST', USERS, body=registration(**fields)))
|
self.assert_invalid(api.request('POST', USERS, body=registration(**fields)))
|
||||||
|
|
||||||
def test_wrong_content_type(self):
|
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()
|
raw = json.dumps(registration()).encode()
|
||||||
self.assert_invalid(api.request('POST', USERS, raw=raw, headers={'Content-Type': 'text/plain'}))
|
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):
|
class UserValidationTest(unittest.TestCase):
|
||||||
|
|||||||
Reference in New Issue
Block a user