"""Фаза 4/5: парсеры новых источников (opendata, БИМ-дерево, XSD-скрейп). Моки MockTransport."""
import sys
from pathlib import Path
import httpx
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import ext_fetch # noqa: E402
import fgis_client as fc # noqa: E402
import xsd_client # noqa: E402
def test_opendata_list_parses_items():
resp = {"total": 2, "items": [
{"id": 2, "datasetName": "КСР", "lastChangeDate": "2026-05-20"},
{"id": 4, "datasetName": "ФСНБ-2022", "lastChangeDate": "2026-05-15"}]}
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json=resp))) as c:
items = fc.opendata_list(client=c)
assert [i["id"] for i in items] == [2, 4]
def test_opendata_list_format_error():
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"x": 1}))) as c:
with pytest.raises(fc.FgisFormatError):
fc.opendata_list(client=c)
def test_bim_tree_recursion_collects_leaf_docs():
# корень (parentGuid отсутствует) → папка F1; F1 → лист L1 (есть filePath) + папка F2; F2 → лист L2
def handler(r):
pg = r.url.params.get("parentGuid")
if pg is None:
return httpx.Response(200, json={"": [{"guid": "F1", "name": "2026", "filePath": None}]})
if pg == "F1":
return httpx.Response(200, json={"": [
{"guid": "L1", "name": "письмо A", "filePath": "/a.pdf"},
{"guid": "F2", "name": "2 кв", "filePath": None}]})
if pg == "F2":
return httpx.Response(200, json={"": [{"guid": "L2", "name": "письмо B", "filePath": "/b.pdf"}]})
return httpx.Response(200, json={"": []})
with httpx.Client(transport=httpx.MockTransport(handler)) as c:
docs = fc.bim_leaf_docs(client=c)
guids = {d["guid"] for d in docs}
assert guids == {"L1", "L2"} # только листья с filePath, папки — не документы
def test_bim_empty_root_fails_loud():
"""Пустой корень при живом API = смена схемы → raise (письма-индексы есть с 2020), не тихо []."""
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"": []}))) as c:
with pytest.raises(fc.FgisFormatError):
fc.bim_leaf_docs(client=c)
def test_bim_node_not_dict_fails_loud():
"""Узел дерева не-объект → raise (иначе .get() ниже дал бы AttributeError и убил бы чекер)."""
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"": ["строка"]}))) as c:
with pytest.raises(fc.FgisFormatError):
fc.bim_leaf_docs(client=c)
def test_bim_cap_exceeded_fails_loud():
"""Превышение потолка узлов = зацикливание/аномалия → raise, а НЕ тихая обрезка охвата."""
def handler(r):
pg = r.url.params.get("parentGuid")
if pg is None:
return httpx.Response(200, json={"": [{"guid": f"L{i}", "filePath": f"/{i}.pdf"} for i in range(5)]})
return httpx.Response(200, json={"": []})
with httpx.Client(transport=httpx.MockTransport(handler)) as c:
with pytest.raises(fc.FgisFormatError):
fc.bim_leaf_docs(max_nodes=2, client=c)
def test_xsd_schema_links_extracted():
"""Реальные имена со страницы Минстроя (сверено 2026-07): берём сметные/экспертизные схемы,
отсекаем журналы/акты И «схему пояснительной записки проекта» (её ловил старый маркер skhema)."""
html = (
'ЛСР РИМ'
'ССР'
'КА'
'эксп'
'журнал'
'общий журнал'
'ПЗ проекта'
'не zip')
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text=html))) as c:
links = xsd_client.schema_links(client=c)
names = {xsd_client._fname(u) for u in links}
assert names == {"LocalEstimateResourceIndexMethod.zip", "SummaryEstimate.zip",
"Format_predstavleniya_rezultatov_konyunkturnogo_analiza.zip",
"XML-схема заключения экспертизы.zip"}
assert all(u.startswith(xsd_client.BASE) for u in links) # абсолютные (urljoin)
def test_xsd_fail_loud_on_only_non_schema_zips():
"""Страница из одних журналов/актов → 0 схем после фильтра → FetchError,
а НЕ тихое скачивание журналов как «схем» (реальный баг, замеченный пользователем)."""
html = ('ж'
'акт')
with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text=html))) as c:
with pytest.raises(ext_fetch.FetchError):
xsd_client.schema_links(client=c)