"""Срез 2.1 (+ фиксы Fable): мониторинг приказов. Мок page-aware (пагинация вглубь), фильтр item без eoNumber, дедуп по seen. """ import json import os import sys from pathlib import Path import httpx import pytest sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import pravo_client as pc # noqa: E402 FIX = Path(__file__).resolve().parent / "fixtures" / "ext" / "pravo_documents.json" def _page_aware(pages: dict[int, list]): """Мок: по index=N отдаёт свою страницу items; pagesTotalCount = число страниц.""" total = len(pages) def handler(r): if r.url.path != "/api/Documents": return httpx.Response(404) idx = int(r.url.params.get("index", "1")) return httpx.Response(200, json={"items": pages.get(idx, []), "pagesTotalCount": total}) return httpx.Client(transport=httpx.MockTransport(handler)) def _fixture_items(): return json.loads(FIX.read_text(encoding="utf-8"))["items"] def test_recent_normalized(): with _page_aware({1: _fixture_items()}) as c: docs = pc.recent(client=c) assert docs and all("eoNumber" in d and "pdf_url" in d for d in docs) assert docs[0]["number"] == "362/пр" def test_new_since_paginates_backlog(): """Бэклог >1 страницы (API отдаёт новейшие первыми): новые на стр.1 И стр.2 доложены, стоп на стр.3 (целиком виденная). Раньше брали только стр.1 → бэклог терялся (баг Fable).""" tmpl = _fixture_items()[0] p1 = [{**tmpl, "eoNumber": f"NEW1-{i}"} for i in range(3)] # новые p2 = [{**tmpl, "eoNumber": f"NEW2-{i}"} for i in range(3)] # тоже новые (глубже) p3 = [{**tmpl, "eoNumber": f"OLD-{i}"} for i in range(3)] # виденные with _page_aware({1: p1, 2: p2, 3: p3}) as c: seen = {f"OLD-{i}" for i in range(3)} new = pc.new_since(seen, client=c) got = {d["eoNumber"] for d in new} assert got == {"NEW1-0", "NEW1-1", "NEW1-2", "NEW2-0", "NEW2-1", "NEW2-2"} # обе новые страницы def test_new_since_stops_when_page_all_seen(): items = _fixture_items() with _page_aware({1: items[:3], 2: items[:3]}) as c: seen = {d["eoNumber"] for d in items[:3]} # 1-я страница целиком виденная new = pc.new_since(seen, client=c) assert new == [] # глубже не пошли, дублей нет def test_item_without_eonumber_skipped(): bad = [{"number": "X", "name": "смета"}, {"eoNumber": "OK1", "number": "1", "name": "индекс"}] with _page_aware({1: bad}) as c: docs = pc.recent(client=c) assert [d["eoNumber"] for d in docs] == ["OK1"] # item без eoNumber отброшен (не None в дедупе) def test_relevance_flag(): assert pc._is_relevant({"name": "Об утверждении индексов изменения сметной стоимости"}) is True assert pc._is_relevant({"name": "О внесении изменений в ФСНБ"}) is True assert pc._is_relevant({"name": "О типовых индикаторах риска"}) is False def test_format_error_on_bad_shape(): with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"foo": 1}))) as c: with pytest.raises(pc.PravoFormatError): pc.documents(client=c) @pytest.mark.skipif(os.environ.get("EXT_SMOKE") != "1", reason="живой запрос к pravo.gov.ru только при EXT_SMOKE=1") def test_smoke_live_pravo(): docs = pc.recent() assert docs and docs[0]["eoNumber"]