Files
mtusi2026lab2/student-tests/test_users_and_errors.py
T
Alexey BodanyukandClaude Opus 5.5 893beaa79a chore: перенос решения lab1 (src, student-tests, Dockerfile, lock) без изменений
Исходная точка lab2: код из solution/bvt2302-bodanyuk лабы 1, коммит 472c1bd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 19:05:00 +03:00

140 lines
6.6 KiB
Python
Raw 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.
"""Registration, identification (X-User-Id), strict JSON validation and the error format."""
from __future__ import annotations
import datetime as dt
import uuid
import pytest
def test_health_endpoints(api):
assert api.call("GET", "/health/live", 200, schema="Health").json() == {"status": "ok"}
assert api.call("GET", "/health/ready", 200, schema="Health").json() == {"status": "ok"}
def test_readiness_is_503_while_draining(api, app):
app.state.draining = True
body = api.call("GET", "/health/ready", 503).json()
assert body["error"]["code"] == "unavailable"
assert api.call("GET", "/health/live", 200).json() == {"status": "ok"}
def test_register_returns_user_with_server_fields_and_unicode(api):
user = api.user("alice", display_name="Алиса 👩‍💻 Ωμέγα")
assert user["display_name"] == "Алиса 👩‍💻 Ωμέγα"
assert uuid.UUID(user["id"]).version == 4
assert user["created_at"].endswith("Z")
dt.datetime.fromisoformat(user["created_at"].replace("Z", "+00:00"))
assert set(user) == {"id", "username", "display_name", "created_at"}
def test_duplicate_username_is_409(api):
body = {"username": "dup_" + uuid.uuid4().hex[:8], "display_name": "Первый"}
api.call("POST", "/api/v1/users", 201, json_body=body)
error = api.call("POST", "/api/v1/users", 409, json_body={**body, "display_name": "Второй"}).json()
assert error["error"]["code"] == "conflict"
def test_display_name_limit_is_in_code_points(api):
api.call("POST", "/api/v1/users", 201, json_body={"username": "emoji_ok", "display_name": "😀" * 100})
api.call("POST", "/api/v1/users", 400, json_body={"username": "emoji_bad", "display_name": "😀" * 101})
@pytest.mark.parametrize("raw", [
b"{", # malformed JSON
b"", # empty body
b"[]", # not an object
b'"alice"',
b"null",
b'{"username": "abc_def", "display_name": NaN}', # NaN is not JSON
b'{"username": "abc_def", "display_name": "\xff\xfe"}', # invalid UTF-8
b'{"username": "abc_def", "display_name": "\\ud800"}', # lone surrogate
b'{"username": "abc_def", "display_name": "x"}{"a": 1}', # two objects glued together
])
def test_malformed_json_is_400(api, raw):
error = api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"}).json()
assert error["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("body", [
{"username": "abc_def"}, # missing field
{"username": "abc_def", "display_name": "x", "extra": 1}, # unknown field
{"username": "abc_def", "display_name": "x", "password": "p"}, # lab2 field is not accepted yet
{"username": 123, "display_name": "x"}, # wrong type
{"username": "abc_def", "display_name": None},
{"username": "abc_def", "display_name": ["x"]},
{"username": "abc_def", "display_name": ""},
{"username": "abc_def", "display_name": " \t\n "}, # only whitespace
{"username": "ab", "display_name": "x"}, # too short
{"username": "a" * 33, "display_name": "x"}, # too long
{"username": "Alice", "display_name": "x"}, # upper case
{"username": "алиса", "display_name": "x"}, # non-ASCII
{"username": "abc-def", "display_name": "x"},
{"username": "abc_def\n", "display_name": "x"}, # `$` trap in regex
])
def test_invalid_user_fields_are_400(api, body):
api.call("POST", "/api/v1/users", 400, json_body=body)
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "application/json; charset=latin-1"])
def test_wrong_content_type_is_400(api, content_type):
raw = b'{"username": "abc_def", "display_name": "x"}'
api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": content_type})
def test_json_with_utf8_charset_is_accepted(api):
raw = '{"username": "charset_ok", "display_name": "Юникод"}'.encode()
api.call("POST", "/api/v1/users", 201, raw=raw, headers={"Content-Type": "application/json; charset=UTF-8"})
def test_oversized_body_is_413(api):
body = {"username": "big_body", "display_name": "x" * 70_000}
assert api.call("POST", "/api/v1/users", 413, json_body=body).json()["error"]["code"] == "payload_too_large"
@pytest.mark.parametrize("header", [None, "", "not-a-uuid", str(uuid.uuid4()), "11111111-1111-4111-8111-11111111111"])
def test_missing_or_unknown_identity_is_401(api, header):
headers = {} if header is None else {"X-User-Id": header}
for method, path in [("GET", "/api/v1/users/me"), ("GET", "/api/v1/chats"), ("GET", f"/api/v1/chats/{uuid.uuid4()}")]:
error = api.call(method, path, 401, headers=headers).json()
assert error["error"]["code"] == "unauthorized"
def test_me_returns_selected_user(api):
alice, bob = api.user("alice"), api.user("bob")
assert api.call("GET", "/api/v1/users/me", 200, user=alice, schema="User").json() == alice
assert api.call("GET", "/api/v1/users/me", 200, user=bob).json() == bob
upper = api.call("GET", "/api/v1/users/me", 200, headers={"X-User-Id": alice["id"].upper()}).json()
assert upper == alice
def test_unknown_route_and_method_use_error_format(api):
assert api.call("GET", "/api/v1/nope", 404).json()["error"]["code"] == "not_found"
api.call("DELETE", "/api/v1/users", 405)
def test_request_id_is_unique_and_propagated(api):
first = api.call("GET", "/health/live", 200).headers["x-request-id"]
second = api.call("GET", "/health/live", 200).headers["x-request-id"]
assert first != second
assert api.call("GET", "/health/live", 200, headers={"X-Request-Id": "trace-42"}).headers["x-request-id"] == "trace-42"
def test_unexpected_exception_is_500_without_details(api, app, monkeypatch):
def boom(*_args, **_kwargs):
raise RuntimeError("secret internal detail")
monkeypatch.setattr(app.state.store, "get_user", boom)
response = api.call("GET", "/api/v1/users/me", 500, headers={"X-User-Id": str(uuid.uuid4())})
assert response.json()["error"]["code"] == "internal_error"
assert "secret" not in response.text
def test_swagger_ui_and_contract_are_served(api):
page = api.call("GET", "/docs", 200)
assert "swagger-ui" in page.text
spec = api.call("GET", "/openapi.json", 200).json()
assert spec["info"]["title"].startswith("MTUSI Messenger")
assert spec["servers"] == [{"url": "/", "description": "этот сервер"}]
assert "/api/v1/chats/{chat_id}/messages" in spec["paths"]