diff --git a/REPORT.md b/REPORT.md index d2a75b1..0eef7af 100644 --- a/REPORT.md +++ b/REPORT.md @@ -165,7 +165,7 @@ migrate (одноразовый) ──> postgres: применяет migrations | Критерий 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: минимум 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: сборка из чистого 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 | diff --git a/evidence/race.json b/evidence/race.json index f51fa1f..517e1c2 100644 --- a/evidence/race.json +++ b/evidence/race.json @@ -14,6 +14,6 @@ "ordered_by_created_at_and_id": true, "pages_read": 15, "page_size": 7, - "send_elapsed_seconds": 0.407, + "send_elapsed_seconds": 0.336, "ok": true } diff --git a/evidence/tests.txt b/evidence/tests.txt index 76cc7ce..88f6174 100644 --- a/evidence/tests.txt +++ b/evidence/tests.txt @@ -1,5 +1,5 @@ # 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; # 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). @@ -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_extra_fields (test_validation.InvalidJsonTest.test_extra_fields) ... 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_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_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_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_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 @@ -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 ---------------------------------------------------------------------- -Ran 73 tests in 8.689s +Ran 76 tests in 7.839s OK [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, "pages_read": 15, "page_size": 7, - "send_elapsed_seconds": 0.407, + "send_elapsed_seconds": 0.336, "ok": true } PASS diff --git a/src/messenger/errors.py b/src/messenger/errors.py index 035efea..c1de6a3 100644 --- a/src/messenger/errors.py +++ b/src/messenger/errors.py @@ -24,5 +24,9 @@ def bad_request(message): return ApiError(400, 'invalid_request', message) +def unsupported_media_type(message): + return ApiError(415, 'unsupported_media_type', message) + + def not_found(): return ApiError(404, 'not_found', 'Объект не найден') diff --git a/src/messenger/server.py b/src/messenger/server.py index e9582fd..58a3526 100644 --- a/src/messenger/server.py +++ b/src/messenger/server.py @@ -11,7 +11,7 @@ from urllib.parse import parse_qs from . import validation 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 .timeutil import format_time @@ -248,7 +248,7 @@ class RequestHandler(BaseHTTPRequestHandler): def _json_body(self, body): 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 diff --git a/student-tests/test_validation.py b/student-tests/test_validation.py index fec65a4..ca23ff5 100644 --- a/student-tests/test_validation.py +++ b/student-tests/test_validation.py @@ -57,9 +57,35 @@ class InvalidJsonTest(unittest.TestCase): with self.subTest(fields=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() - 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):