"""Договор наружного АПИ печи: что проходит в запрос и каким бывает ответ. Требования — план PLAN_2026-11-24_tsingular_api.md, §4.2 и §4.4: чужие поля запрещены, логическое значение вместо числа — отказ, все проблемы перечисляются сразу с путём поля; в ответе итог пуст ровно когда считать было не из чего, ноль запрещён. """ import json import os import re import sys import pytest from pydantic import ValidationError ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) import stove_contract as c LINE = {"name": "Дверка топочная", "qty": 1, "unit": "шт"} RID = "3f9c2a71b0e54d8c" def _stove(**over): body = {"kind": "heating", "bricks": {"ceramic": 210, "fireclay": 76}, "region": "Москва"} body.update(over) return {"stove": body} def _paths(exc): return sorted(".".join(str(p) for p in e["loc"]) for e in exc.errors()) def _answer(**over): body = { "request_id": RID, "currency": "RUB", "valid_at": "III кв. 2026", "works": {"min": 1106, "max": 1242, "min_way": 0, "max_way": 1}, "materials": {"min": 10920, "max": 10920, "min_way": 0, "max_way": 0}, "total": {"min": 12026, "max": 12162, "min_way": 0, "max_way": 1}, "missing": [], "missing_data": [], "basis": {"ways": ["по кирпичу (210+76 шт) × ФЕР 08-08-003-01", "по массе (1320 кг) × ТСН 8-31-1"], "volume_m3": {"min": 0.5396, "max": 0.5396}, "notes": [], "region": "Москва", "price_source": c.PRICE_SOURCE}, "disclaimer": c.DISCLAIMER} body.update(over) return body def test_valid_request_and_what_is_optional(): req = c.StoveRequest.model_validate(_stove(materials=[LINE], context=" сайт печей ")) s = req.stove assert s.kind == "heating" and s.bricks.ceramic == 210 and s.bricks.fireclay == 76 assert s.materials[0].qty == 1.0 and s.materials[0].unit == "шт" assert s.mass_kg is None and s.zone is None assert s.context == "сайт печей", "свободный текст обрезается по краям, длина считается после этого" for kind in c.KINDS: assert c.StoveRequest.model_validate(_stove(kind=kind)).stove.kind == kind # Явный null у необязательного поля — та же «нет значения»: многие сериализаторы шлют его так. explicit = c.StoveRequest.model_validate(_stove(mass_kg=None, zone=None, materials=None, context=None)) assert explicit.stove.mass_kg is None and explicit.stove.materials is None def test_unknown_fields_are_all_named_with_their_paths(): body = _stove(material=[LINE], weight_kg=10) body["stove"]["materials"] = [dict(LINE, prise=5)] body["extra"] = 1 with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(body) assert _paths(e.value) == ["extra", "stove.material", "stove.materials.0.prise", "stove.weight_kg"] problems = c.problems(e.value) assert len(problems) == 4 assert all(p.endswith(": неизвестное поле") for p in problems) assert "stove.materials.0.prise: неизвестное поле" in problems def test_missing_required_fields_are_named(): with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate({"stove": {"bricks": {"ceramic": 1, "fireclay": 0}}}) assert _paths(e.value) == ["stove.kind", "stove.region"] assert c.problems(e.value) == ["stove.kind: обязательное поле", "stove.region: обязательное поле"] @pytest.mark.parametrize("field,value", [ ("ceramic", True), ("fireclay", False), ("ceramic", 210.5), ("ceramic", -1), ("ceramic", 10 ** 6 + 1), ("fireclay", "76"), ("ceramic", None)]) def test_bricks_are_whole_non_negative_bounded_numbers(field, value): bricks = {"ceramic": 210, "fireclay": 76} bricks[field] = value with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(_stove(bricks=bricks)) assert _paths(e.value) == [f"stove.bricks.{field}"] def test_brick_sum_must_be_positive(): with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(_stove(bricks={"ceramic": 0, "fireclay": 0})) assert _paths(e.value) == ["stove.bricks"] assert c.problems(e.value) == ["stove.bricks: сумма кирпича должна быть больше нуля"] def test_one_brick_kind_may_be_zero(): req = c.StoveRequest.model_validate(_stove(bricks={"ceramic": 0, "fireclay": 300})) assert req.stove.bricks.ceramic == 0 and req.stove.bricks.fireclay == 300 @pytest.mark.parametrize("line,path", [ ({"name": "x", "qty": 0, "unit": "шт"}, "stove.materials.0.qty"), ({"name": "x", "qty": -1, "unit": "шт"}, "stove.materials.0.qty"), ({"name": "x", "qty": 10 ** 9 + 1, "unit": "шт"}, "stove.materials.0.qty"), ({"name": "x", "qty": True, "unit": "шт"}, "stove.materials.0.qty"), ({"name": "x", "qty": "5", "unit": "шт"}, "stove.materials.0.qty"), ({"name": "x", "qty": float("nan"), "unit": "шт"}, "stove.materials.0.qty"), ({"name": "x", "qty": float("inf"), "unit": "шт"}, "stove.materials.0.qty"), ({"name": "", "qty": 1, "unit": "шт"}, "stove.materials.0.name"), ({"name": " ", "qty": 1, "unit": "шт"}, "stove.materials.0.name"), ({"name": "у" * 201, "qty": 1, "unit": "шт"}, "stove.materials.0.name"), ({"name": "x", "qty": 1, "unit": ""}, "stove.materials.0.unit"), ({"name": "x", "qty": 1, "unit": "ш" * 21}, "stove.materials.0.unit"), ({"qty": 1, "unit": "шт"}, "stove.materials.0.name"), ({"name": "x", "unit": "шт"}, "stove.materials.0.qty"), ]) def test_bill_line_bounds(line, path): with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(_stove(materials=[line])) assert _paths(e.value) == [path] def test_bill_line_accepts_fractional_quantity_and_both_bounds(): lines = [dict(LINE, qty=0.5, unit="т"), dict(LINE, qty=10 ** 9, name="у" * 200, unit="ш" * 20)] req = c.StoveRequest.model_validate(_stove(materials=lines)) assert req.stove.materials[0].qty == 0.5 and req.stove.materials[1].qty == 10 ** 9 assert c.StoveRequest.model_validate(_stove(materials=[])).stove.materials == [], \ "пустая ведомость — та же «ведомости нет», не отказ" def test_bill_length_limit_is_two_hundred_lines(): lines = [dict(LINE, name=f"строка {i}") for i in range(200)] assert len(c.StoveRequest.model_validate(_stove(materials=lines)).stove.materials) == 200 with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(_stove(materials=lines + [LINE])) assert c.problems(e.value) == ["stove.materials: больше 200 строк"] @pytest.mark.parametrize("value", [0, -5, 10 ** 6 + 1, True, "1300", float("nan"), float("inf")]) def test_mass_is_a_positive_bounded_number(value): with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(_stove(mass_kg=value)) assert _paths(e.value) == ["stove.mass_kg"] def test_text_field_bounds(): ok = c.StoveRequest.model_validate(_stove(context="я" * 500, region="р" * 100, zone=" зона 1 ")) assert ok.stove.zone == "зона 1" assert c.StoveRequest.model_validate(_stove(zone=" ")).stove.zone is None, \ "пустая зона — та же «зоны нет»" with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(_stove(context="я" * 501, region="р" * 101, zone="з" * 101, kind="sauna")) assert _paths(e.value) == ["stove.context", "stove.kind", "stove.region", "stove.zone"] with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(_stove(region=" ")) assert _paths(e.value) == ["stove.region"] def test_request_schema_is_the_contract_the_openapi_is_built_from(): schema = c.StoveRequest.model_json_schema() assert schema["additionalProperties"] is False assert set(schema["properties"]) == {"stove"} stove = schema["$defs"][schema["properties"]["stove"]["$ref"].split("/")[-1]] assert set(stove["properties"]) == {"kind", "bricks", "mass_kg", "materials", "context", "region", "zone", "bucket_volume_l"} assert set(stove["required"]) == {"kind", "bricks", "region"} assert stove["properties"]["bricks"]["$ref"].endswith("/Bricks") assert len(stove["properties"]["materials"]["anyOf"]) == 2, "ведомость необязательна" @pytest.mark.parametrize("value", [0, 31, True, "10", float("nan")]) def test_bucket_volume_rejects_invalid_defaults(value): with pytest.raises(ValidationError): c.StoveRequest.model_validate(_stove(bucket_volume_l=value)) def test_bucket_volume_accepts_explicit_household_measure(): assert c.StoveRequest.model_validate(_stove(bucket_volume_l=12)).stove.bucket_volume_l == 12 def test_answer_without_zone_has_no_zone_key_at_all(): out = c.StoveAnswer.model_validate(_answer()).model_dump(mode="json") assert "zone" not in out["basis"] assert out["basis"]["region"] == "Москва" assert json.loads(json.dumps(out)) == out, "тело ответа переводится в JSON без подготовки" def test_answer_with_zone_keeps_it(): basis = dict(_answer()["basis"], zone="город Москва") out = c.StoveAnswer.model_validate(_answer(basis=basis)).model_dump(mode="json") assert out["basis"]["zone"] == "город Москва" def test_null_forks_and_null_volume_are_part_of_the_contract(): out = c.StoveAnswer.model_validate(_answer( works=None, materials=None, total=None, missing_data=["ведомость материалов"], basis=dict(_answer()["basis"], ways=[], volume_m3=None))).model_dump(mode="json") assert out["works"] is None and out["total"] is None and out["basis"]["volume_m3"] is None @pytest.mark.parametrize("fork", [ {"min": 0, "max": 1242, "min_way": 0, "max_way": 1}, {"min": 0, "max": 0, "min_way": 0, "max_way": 0}, {"min": 1242, "max": 1106, "min_way": 0, "max_way": 1}, {"min": 1106, "max": 1242, "min_way": 2, "max_way": 1}, {"min": 1106, "max": 1242, "min_way": 0, "max_way": -1}, {"min": 1106.5, "max": 1242, "min_way": 0, "max_way": 1}]) def test_fork_refuses_zero_inversion_dangling_index_and_kopecks(fork): with pytest.raises(ValidationError): c.StoveAnswer.model_validate(_answer(works=fork)) @pytest.mark.parametrize("over", [ {"total": None}, {"total": None, "works": None}, {"total": None, "materials": None, "works": None, "missing_data": []}, {"works": None, "materials": None}, {"works": None, "total": None}]) def test_total_is_never_empty_while_something_is_counted(over): with pytest.raises(ValidationError): c.StoveAnswer.model_validate(_answer(**over)) def test_total_null_is_legal_when_nothing_counted_and_the_cause_is_named(): nothing = {"works": None, "materials": None, "total": None, "missing_data": ["ведомость материалов"], "basis": {"ways": [], "volume_m3": None, "notes": [], "region": "Москва", "price_source": c.PRICE_SOURCE}} assert c.StoveAnswer.model_validate(_answer(**nothing)).total is None def test_answer_refuses_unknown_fields_and_foreign_currency(): with pytest.raises(ValidationError): c.StoveAnswer.model_validate(_answer(currency="USD")) with pytest.raises(ValidationError): c.StoveAnswer.model_validate(dict(_answer(), surprise=1)) with pytest.raises(ValidationError): c.StoveAnswer.model_validate(_answer(basis=dict(_answer()["basis"], notes=["x"], extra=1))) def test_no_refusal_phrase_leaves_in_english(): """Мусор всех видов: каждая фраза отказа — по-русски, то есть типы ошибок разбора все переведены.""" base = {"kind": "heating", "bricks": {"ceramic": 1, "fireclay": 1}, "region": "x"} junk = [{}, {"stove": 5}, {"stove": []}, {"stove": None}] junk += [{"stove": dict(base, **over)} for over in ( {"kind": 5}, {"kind": ["a"]}, {"kind": None}, {"bricks": 5}, {"bricks": None}, {"bricks": {"ceramic": []}}, {"bricks": {"ceramic": {}, "fireclay": 1}}, {"region": 5}, {"region": ["x"]}, {"region": None}, {"zone": 5}, {"mass_kg": [1]}, {"mass_kg": {}}, {"mass_kg": -(10 ** 7)}, {"mass_kg": float("inf")}, {"materials": 5}, {"materials": "x"}, {"materials": [5]}, {"materials": [None]}, {"context": 5}, {"context": ["x"]}, {"materials": [{"name": 5, "qty": 1, "unit": "шт"}]}, {"materials": [{"name": "x", "qty": 1, "unit": 5}]}, {"materials": [{"name": "x", "qty": [1], "unit": "шт"}]}, {"materials": [{"name": "x", "qty": None, "unit": "шт"}]}, {"materials": [{"name": "x" * 300, "qty": 1, "unit": "шт"}]})] phrases = [] for body in junk: with pytest.raises(ValidationError) as e: c.StoveRequest.model_validate(body) phrases += [text.split(": ", 1)[1] for text in c.problems(e.value)] assert len(phrases) > 20 assert not [p for p in phrases if re.search("[A-Za-z]", p)], "английская фраза ушла партнёру" def test_error_body_codes_are_a_closed_list(): body = {"detail": "фраза", "code": "invalid_request", "request_id": RID, "documentation_url": c.DOCUMENTATION_URL} assert c.StoveError.model_validate(body).code == "invalid_request" assert len(c.ERROR_CODES) == 15 and "ip_not_allowed" in c.ERROR_CODES for code in c.ERROR_CODES: assert c.StoveError.model_validate(dict(body, code=code)).code == code with pytest.raises(ValidationError): c.StoveError.model_validate(dict(body, code="teapot")) assert c.StoveError.model_validate(dict(body, code="invalid_request")).model_dump() == body