"""Самопроверка `contract.py`: неверная форма ответа роняет тест. Спек `student-tests`, сценарий «Ошибка не в формате контракта». """ import httpx import pytest from api_client import Actor from contract import assert_error, check_body def fake_response( status: int, body: object, request_id: str = "rid-1", instance_id: str | None = "api-1", ) -> httpx.Response: """Ответ API лабы 3; `instance_id=None` — без `X-Instance-Id`.""" headers = {"X-Request-Id": request_id} if instance_id is not None: headers["X-Instance-Id"] = instance_id return httpx.Response( status, json=body, headers=headers, request=httpx.Request("GET", "http://stand/api/v1/chats/x"), ) def test_contract_error_passes() -> None: body = { "error": { "code": "not_found", "message": "Not found", "request_id": "rid-1", }, } assert assert_error(fake_response(404, body), 404)["code"] == "not_found" @pytest.mark.parametrize("instance_id", [None, "", "api 1", "a" * 65]) def test_bad_instance_id_fails(instance_id: str | None) -> None: body = { "error": { "code": "not_found", "message": "Not found", "request_id": "rid-1", }, } with pytest.raises(AssertionError, match="X-Instance-Id"): assert_error(fake_response(404, body, instance_id=instance_id), 404) @pytest.mark.parametrize( ("status", "body"), [ (404, {"detail": "Not Found"}), (400, {"detail": [{"loc": ["body"], "msg": "bad"}]}), ( 404, { "error": { "code": "not_found", "message": "Not found", "request_id": "other", }, }, ), ( 404, { "error": { "code": "invalid_request", "message": "Not found", "request_id": "rid-1", }, }, ), ( 404, { "error": { "code": "not_found", "message": "Not found", "request_id": "rid-1", "detail": "x", }, }, ), ( 500, { "error": { "code": "internal_error", "message": 'File "/app/src/main.py", line 1', "request_id": "rid-1", }, }, ), ], ids=[ "fastapi-404", "fastapi-validation", "request-id-mismatch", "code-not-matching-status", "extra-field", "leaks-internals", ], ) def test_wrong_error_body_fails(status: int, body: object) -> None: # статус верный: падать должна проверка тела with pytest.raises(AssertionError): assert_error(fake_response(status, body), status) def test_success_body_checks(alice: Actor) -> None: user = alice.user check_body(user, "User") broken = { "extra field": {**user, "extra": 1}, "missing field": {k: v for k, v in user.items() if k != "username"}, "uppercase id": {**user, "id": user["id"].upper()}, "created_at without Z": { **user, "created_at": user["created_at"][:-1], }, "created_at without microseconds": { **user, "created_at": user["created_at"][:19] + "Z", }, } for name, body in broken.items(): try: check_body(body, "User") except AssertionError: continue pytest.fail(f"accepted: {name}")