diff --git a/ext_pull.py b/ext_pull.py index 1e06e88..6496ad1 100644 --- a/ext_pull.py +++ b/ext_pull.py @@ -192,13 +192,18 @@ def pull_bim(refetch_all: bool = False) -> list[dict]: dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"] if not refetch_all and (dest_dir / "meta.json").exists(): continue # уже качали это письмо — не дёргаем гос-API повторно + file_guid = d.get("filePath") # у БИМ-узла guid — это ИДЕНТИЧНОСТЬ узла дерева, а скачивание + if not file_guid: # идёт по ОТДЕЛЬНОМУ guid файла (filePath). guid узла → 403. + failed += 1 + print(f" ✗ БИМ-письмо {d.get('name') or d['guid']}: нет filePath", file=sys.stderr) + continue try: with tempfile.TemporaryDirectory() as td: - tmp = Path(td) / _safe_name(Path(str(d.get("filePath") or "")).name, "letter.pdf") - fc.download_by_guid(d["guid"], tmp, expect_min_size=500) + tmp = Path(td) / "letter.pdf" # filePath — guid, не имя; письма-индексы это PDF + fc.download_by_guid(file_guid, tmp, expect_min_size=500) meta = ext_state.register_snapshot( dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}", - url=fc.BASE + f"/api/values/GetFileContent/{d['guid']}") + url=fc.BASE + f"/api/values/GetFileContent/{file_guid}") except ext_fetch.FetchError as e: # одно «ядовитое» письмо (удалено上游→HTML, битое) НЕ должно навсегда блокировать # хвост корпуса: инкрементальный skip иначе застревал бы на нём каждый прогон. diff --git a/tests/test_ext_pull.py b/tests/test_ext_pull.py index 49426c8..6eeecb7 100644 --- a/tests/test_ext_pull.py +++ b/tests/test_ext_pull.py @@ -64,26 +64,30 @@ def test_pull_salary_saves_json(monkeypatch, tmp_path): assert json.loads(snap.read_text())["items"][0]["code"] == "1-100-1" -def test_pull_bim_poison_letter_skipped_tail_downloaded(monkeypatch, tmp_path): - """Одно «ядовитое» письмо (FetchError) НЕ блокирует хвост: L2 качается, а частичный сбой - сигналится PartialPullError (несёт успехи) → ненулевой exit у CLI. Fable-фикс #2/(a).""" +def test_pull_bim_downloads_by_filepath_not_node_guid(monkeypatch, tmp_path): + """БИМ качается по filePath (guid ФАЙЛА), НЕ по guid УЗЛА дерева — тот даёт 403 (реальный баг, + пойман на живом обходе). Плюс: ядовитое письмо пропускается, хвост докачан, частичный сбой → + PartialPullError (exit 1). Ключ снапшота — по guid узла (стабильная идентичность письма).""" import ext_fetch monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path)) monkeypatch.setattr(fc, "bim_leaf_docs", lambda client=None: [ - {"guid": "L1", "name": "битое", "filePath": "/1.pdf"}, - {"guid": "L2", "name": "ок", "filePath": "/2.pdf"}]) + {"guid": "node1", "name": "битое", "filePath": "file1"}, + {"guid": "node2", "name": "ок", "filePath": "file2"}]) + called = [] def dl(guid, dest, client=None, expect_min_size=500): - if guid == "L1": - raise ext_fetch.FetchError("удалено上游 → HTML") + called.append(guid) + if guid == "file1": + raise ext_fetch.FetchError("403 Forbidden") Path(dest).write_bytes(b"PDF-" + b"z" * 600) return {"path": str(dest), "size": 604, "sha256": es.sha256_file(dest)} monkeypatch.setattr(fc, "download_by_guid", dl) import pytest with pytest.raises(ep.PartialPullError) as ei: ep.pull_bim() - assert [r["key"] for r in ei.value.results] == ["bim/L2"] # хвост докачан - assert (tmp_path / "snapshots/fgis/bim_letters/L2/meta.json").exists() - assert ep._drain(ep.pull_bim) == 1 # CLI видит ненулевой exit + assert set(called) == {"file1", "file2"} # по filePath, НЕ по node guid + assert [r["key"] for r in ei.value.results] == ["bim/node2"] # ключ по guid узла + assert (tmp_path / "snapshots/fgis/bim_letters/node2/meta.json").exists() + assert ep._drain(ep.pull_bim) == 1 # CLI видит ненулевой exit def test_solo_run_creates_missing_ext_dir(monkeypatch, tmp_path):