merge: вливание feat/admin-v2 в линию прода
Сведение двух линий: серверная feat/robokassa-activation (cb4ad96cf) + маковская feat/admin-v2 (d6c9c18, 94 коммита от корня760a4c7d1). Конфликт один — health_checks.py, разрешён --ours (серверная версия — надмножество: полным диффом проверено, у мака только переносы строк). План: docs/PLAN_2026-11-25_merge_lines.md, ред. 8. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
"""Проверка инструмента приёмки матрицы покрытия (20.11.2026).
|
||||
|
||||
21.11 добавлена сверка регионального отпечатка с манифестами в общем хранилище.
|
||||
Инструмент — мой глаз по поручению «все справочники страны»: он обязан ловить дыры и
|
||||
ложные числа, а не соглашаться с матрицей. Проверки гоняют его на выдуманных матрицах;
|
||||
мутации: убрать проверку формы или сверку с базой — краснеет соответствующая проверка.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
@@ -33,9 +35,11 @@ def _база_derived(tmp_path, fsnb=100, tsn=10, prices=1000):
|
||||
con.commit(); con.close()
|
||||
con = sqlite3.connect(d / "fgis_ref" / "fgis_ref.sqlite")
|
||||
con.execute("create table prices(id integer)")
|
||||
con.execute("create table zone_snapshots(subject_id integer, period_id integer)")
|
||||
con.execute("create table zone_snapshots(subject_id integer, zone_id integer, "
|
||||
"period_id integer, rows_loaded integer, sha256 text, "
|
||||
"salary_loaded integer, salary_sha256 text)")
|
||||
con.executemany("insert into prices values(?)", [(i,) for i in range(prices)])
|
||||
con.execute("insert into zone_snapshots values(1, 423)")
|
||||
con.execute("insert into zone_snapshots values(1, 1, 423, 90, 'abc', 25, 'def')")
|
||||
con.commit(); con.close()
|
||||
return d
|
||||
|
||||
@@ -98,3 +102,238 @@ def test_нет_с_настоящей_причиной_проходит(tmp_path
|
||||
r = _строка(source="ТЕР", kind="нормы", region="Казань", status="нет",
|
||||
reason="регион публикует только платно, открытого адреса нет")
|
||||
assert _запустить(tmp_path, [r], d) == 0
|
||||
|
||||
|
||||
def test_пропавшая_зона_в_периоде_ловится(tmp_path):
|
||||
"""ЯНАО, 5-я зона: в 2026-Q1 строка есть, в 2026-Q2 её нет — матрица молчит о зоне."""
|
||||
d = _база_derived(tmp_path)
|
||||
rows = []
|
||||
for pid, zs in (("2026-Q1", (241, 242, 245)), ("2026-Q2", (241, 242))):
|
||||
for z in zs:
|
||||
rows.append(_строка(region="Ямало-Ненецкий автономный округ", period=pid,
|
||||
subject_id=320, zone_id=z, rows_count=90))
|
||||
assert _запустить(tmp_path, rows, d) == 1
|
||||
|
||||
|
||||
def test_полный_набор_зон_проходит(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
rows = [_строка(region="Ямало-Ненецкий автономный округ", period=pid,
|
||||
subject_id=320, zone_id=z, rows_count=90)
|
||||
for pid in ("2026-Q1", "2026-Q2") for z in (241, 242, 245)]
|
||||
assert _запустить(tmp_path, rows, d) == 0
|
||||
|
||||
|
||||
def test_повтор_строки_зоны_ловится(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
r = _строка(region="Ямало-Ненецкий автономный округ", period="2026-Q1",
|
||||
subject_id=320, zone_id=241, rows_count=90)
|
||||
assert _запустить(tmp_path, [r, dict(r)], d) == 1
|
||||
|
||||
|
||||
def _фгис_строка(**к):
|
||||
базовая = _строка(source="fgis_split_form", kind="цены ресурсов",
|
||||
region="Хабаровский край", period="2026-Q1", subject_id=1,
|
||||
zone_id=1, rows_count=90, sha256="abc",
|
||||
provenance_ref="zone_snapshots/1/1/423")
|
||||
базовая.update(к)
|
||||
return базовая
|
||||
|
||||
|
||||
def test_провенанс_сходится_со_снимком(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить(tmp_path, [_фгис_строка()], d) == 0
|
||||
|
||||
|
||||
def test_чужой_хэш_в_матрице_ловится(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить(tmp_path, [_фгис_строка(sha256="zzz")], d) == 1
|
||||
|
||||
|
||||
def test_число_строк_против_снимка_ловится(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить(tmp_path, [_фгис_строка(rows_count=80)], d) == 1
|
||||
|
||||
|
||||
def test_ссылка_на_несуществующий_снимок_ловится(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить(tmp_path, [_фгис_строка(provenance_ref="zone_snapshots/1/2/423")], d) == 1
|
||||
|
||||
|
||||
def test_оплата_труда_сверяется_своими_колонками(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
r = _фгис_строка(source="fgis_salary", kind="оплата труда", rows_count=25, sha256="def")
|
||||
assert _запустить(tmp_path, [r], d) == 0
|
||||
r2 = _фгис_строка(source="fgis_salary", kind="оплата труда", rows_count=25, sha256="zzz")
|
||||
assert _запустить(tmp_path, [r2], d) == 1
|
||||
|
||||
|
||||
def _регион_строка(tmp_path, **к):
|
||||
"""Строка ter_region «есть» с каталогом regional/<код>/ и манифестом."""
|
||||
d = tmp_path / "regional" / "1" / "ter"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
манифест = d / "x.sha256"
|
||||
манифест.write_text("abc file.pdf\n", encoding="utf-8")
|
||||
хэш = hashlib.sha256(манифест.read_bytes()).hexdigest()
|
||||
базовая = _строка(source="ter_region", kind="ТЕР", region="Область", period="2025",
|
||||
status="есть", url="https://x", sha256=хэш, rows_count=90,
|
||||
subject_id=1, zone_id=None,
|
||||
provenance="хранится в _external/regional/1/ter/ (sha256sum -c)")
|
||||
базовая.update(к)
|
||||
return базовая
|
||||
|
||||
|
||||
def _запустить_с_реестром(tmp_path, rows, derived, entries):
|
||||
p = tmp_path / "coverage.json"
|
||||
p.write_text(json.dumps({"rows": rows}, ensure_ascii=False), encoding="utf-8")
|
||||
reg = tmp_path / "regional_files.json"
|
||||
reg.write_text(json.dumps({"entries": entries}, ensure_ascii=False), encoding="utf-8")
|
||||
return cc.main(["--coverage", str(p), "--derived", str(derived), "--regional", str(reg)])
|
||||
|
||||
|
||||
def test_реестр_нет_а_матрица_в_работе_ловится(tmp_path):
|
||||
"""Калининград 21.11: в реестре «нет», а матрица осталась «в работе» — расхождение."""
|
||||
d = _база_derived(tmp_path)
|
||||
r = _строка(source="ter_region", kind="ТЕР", region="Область", period="2025",
|
||||
status="в работе", reason="этап 3", url=None, sha256=None,
|
||||
rows_count=0, subject_id=276, zone_id=None)
|
||||
assert _запустить_с_реестром(tmp_path, [r], d, [{"subject_id": 276, "subject": "Область",
|
||||
"kind": "ТЕР", "status": "нет",
|
||||
"reason": "база отменена"}]) == 1
|
||||
|
||||
|
||||
def test_реестр_и_матрица_совпадают_проходят(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
r = _строка(source="ter_region", kind="ТЕР", region="Область", period="2025",
|
||||
status="есть", url="https://x", sha256="abc", rows_count=90,
|
||||
subject_id=276, zone_id=None, provenance="реестр")
|
||||
assert _запустить_с_реестром(tmp_path, [r], d, [{"subject_id": 276, "subject": "Область",
|
||||
"kind": "ТЕР", "status": "есть",
|
||||
"rows": 90, "sha256": "abc"}]) == 0
|
||||
|
||||
|
||||
def test_региональный_отпечаток_сходится_с_манифестом(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить(tmp_path, [_регион_строка(tmp_path)], d) == 0
|
||||
|
||||
|
||||
def test_чужой_региональный_отпечаток_ловится(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить(tmp_path, [_регион_строка(tmp_path, sha256="zzz")], d) == 1
|
||||
|
||||
|
||||
def test_москва_сверяется_с_нашей_базой(tmp_path):
|
||||
"""Москва держится на файл нашей базы: отпечаток обязан совпасть с tsn_ref.sqlite."""
|
||||
d = _база_derived(tmp_path)
|
||||
хэш = hashlib.sha256((d / "tsn" / "tsn_ref.sqlite").read_bytes()).hexdigest()
|
||||
r = _строка(source="ter_region", kind="ТЕР", region="Москва", period="2025",
|
||||
status="есть", url="https://x", sha256=хэш, rows_count=90,
|
||||
subject_id=323, zone_id=None,
|
||||
provenance="derived/tsn/tsn_ref.sqlite (works); 814 PDF на niac")
|
||||
assert _запустить(tmp_path, [r], d) == 0
|
||||
assert _запустить(tmp_path, [dict(r, sha256="zzz")], d) == 1
|
||||
|
||||
|
||||
def test_одиночный_файл_сверяется_без_манифеста(tmp_path):
|
||||
"""Петербург записан отпечатком самого файла: манифеста нет, файл — есть."""
|
||||
d = _база_derived(tmp_path)
|
||||
файл = tmp_path / "regional" / "1" / "tssc" / "file.pdf"
|
||||
файл.parent.mkdir(parents=True)
|
||||
файл.write_bytes(b"%PDF-1.4 test")
|
||||
хэш = hashlib.sha256(файл.read_bytes()).hexdigest()
|
||||
r = _регион_строка(tmp_path, sha256=хэш)
|
||||
assert _запустить(tmp_path, [r], d) == 0
|
||||
|
||||
|
||||
def test_нет_каталога_региональных_файлов_ловится(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
r = _регион_строка(tmp_path, subject_id=2)
|
||||
assert _запустить(tmp_path, [r], d) == 1
|
||||
|
||||
|
||||
def _ожидание(**к):
|
||||
базовая = {"subject_id": 320, "zone_id": 245, "period": "2026-Q2",
|
||||
"reason": "на портале ФГИС ЦС форм за период нет"}
|
||||
базовая.update(к)
|
||||
return базовая
|
||||
|
||||
|
||||
def _клетки_нет(reason="на портале ФГИС ЦС форм за период нет"):
|
||||
строки = []
|
||||
for source, kind in (("fgis_split_form", "цены ресурсов"),
|
||||
("fgis_salary", "оплата труда"),
|
||||
("fgis_indices_gosr", "индексы ГОСР")):
|
||||
строки.append(_фгис_строка(source=source, kind=kind, status="нет",
|
||||
region="Ямало-Ненецкий автономный округ",
|
||||
subject_id=320, zone_id=245, period="2026-Q2",
|
||||
sha256=None, rows_count=0, reason=reason,
|
||||
provenance_ref=None))
|
||||
return строки
|
||||
|
||||
|
||||
def _запустить_с_ожиданиями(tmp_path, rows, derived, ожидания):
|
||||
p = tmp_path / "coverage.json"
|
||||
p.write_text(json.dumps({"rows": rows}, ensure_ascii=False), encoding="utf-8")
|
||||
e = tmp_path / "coverage_expectations.json"
|
||||
e.write_text(json.dumps(ожидания, ensure_ascii=False), encoding="utf-8")
|
||||
return cc.main(["--coverage", str(p), "--derived", str(derived),
|
||||
"--expectations", str(e)])
|
||||
|
||||
|
||||
def test_ожидание_и_клетка_сходятся(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить_с_ожиданиями(tmp_path, _клетки_нет(), d, [_ожидание()]) == 0
|
||||
|
||||
|
||||
def test_клетка_нет_без_ожидания_ловится(tmp_path, capsys):
|
||||
"""22.11.2026: статическая копия ожиданий в реестре — клетка переживёт пересборку."""
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить_с_ожиданиями(tmp_path, _клетки_нет(), d, []) == 1
|
||||
assert "без строки ожиданий" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_устаревшее_ожидание_ловится(tmp_path, capsys):
|
||||
"""Формы появились, а ожидание осталось — матрица соврёт «нет» после пересборки."""
|
||||
d = _база_derived(tmp_path)
|
||||
rows = [_фгис_строка(source="fgis_split_form", kind="цены ресурсов", status="есть")]
|
||||
assert _запустить_с_ожиданиями(
|
||||
tmp_path, rows, d,
|
||||
[_ожидание(subject_id=1, zone_id=1, period="2026-Q1")]) == 1
|
||||
assert "ожидание устарело" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_ожидание_после_пересборки_не_краснит(tmp_path, capsys):
|
||||
"""Обход добавил ожидание позже воскресной пересборки — это предупреждение."""
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить_с_ожиданиями(tmp_path, _клетки_нет(), d,
|
||||
[_ожидание(), _ожидание(period="2027-Q1")]) == 0
|
||||
assert "ещё нет в матрице" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_повтор_ожидания_ловится(tmp_path, capsys):
|
||||
d = _база_derived(tmp_path)
|
||||
assert _запустить_с_ожиданиями(tmp_path, _клетки_нет(), d,
|
||||
[_ожидание(), _ожидание()]) == 1
|
||||
assert "повторяется" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_битый_файл_ожиданий_ловится(tmp_path, capsys):
|
||||
d = _база_derived(tmp_path)
|
||||
p = tmp_path / "coverage.json"
|
||||
p.write_text(json.dumps({"rows": _клетки_нет()}, ensure_ascii=False), encoding="utf-8")
|
||||
e = tmp_path / "coverage_expectations.json"
|
||||
e.write_text("{не json", encoding="utf-8")
|
||||
assert cc.main(["--coverage", str(p), "--derived", str(d),
|
||||
"--expectations", str(e)]) == 1
|
||||
assert "не читается" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_индексы_госр_сверяются_с_файлом_снимка(tmp_path):
|
||||
d = _база_derived(tmp_path)
|
||||
мета = tmp_path / "snapshots" / "fgis" / "indices_gosr" / "1" / "1" / "423" / "meta.json"
|
||||
мета.parent.mkdir(parents=True)
|
||||
мета.write_text(json.dumps({"sha256": "abc"}), encoding="utf-8")
|
||||
r = _фгис_строка(source="fgis_indices_gosr", kind="индексы ГОСР", rows_count=673,
|
||||
provenance_ref="indices_gosr/1/1/423")
|
||||
assert _запустить(tmp_path, [r], d) == 0
|
||||
assert _запустить(tmp_path, [dict(r, sha256="zzz")], d) == 1
|
||||
assert _запустить(tmp_path, [dict(r, provenance_ref="indices_gosr/1/2/423")], d) == 1
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Планировщик ожиданий ежедневного обхода зон (22.11.2026)."""
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
|
||||
import fgis_zone_scan as z # noqa: E402
|
||||
|
||||
def p(i, name): return {"id": i, "name": name}
|
||||
PORTAL = {(320, 245): [p(421, "1 квартал 2025 г."), p(422, "2 квартал 2025 г."),
|
||||
p(423, "3 квартал 2025 г."), p(424, "4 квартал 2025 г."),
|
||||
p(425, "1 квартал 2026 г."), p(426, "2 квартал 2026 г.")]}
|
||||
|
||||
def test_new_period_added_when_not_loaded():
|
||||
adds, rem = z.plan([], PORTAL, known={(320, 245, 425)}, horizon=2)
|
||||
assert any(a["period"] == "2026-Q2" for a in adds)
|
||||
assert not any(a["period"] == "2026-Q1" for a in adds)
|
||||
|
||||
def test_expectation_not_duplicated():
|
||||
ex = [{"subject_id": 320, "zone_id": 245, "period": "2026-Q2"}]
|
||||
adds, _ = z.plan(ex, PORTAL, known={(320, 245, 425)}, horizon=2)
|
||||
assert not [a for a in adds if a["period"] == "2026-Q2"]
|
||||
|
||||
def test_old_expectation_removed_by_horizon():
|
||||
ex = [{"subject_id": 320, "zone_id": 245, "period": "2024-Q4"}]
|
||||
_, rem = z.plan(ex, PORTAL, known=set(), horizon=2)
|
||||
assert ex[0] in rem
|
||||
|
||||
def test_zone_gone_removes_all_its_expectations():
|
||||
ex = [{"subject_id": 999, "zone_id": 1, "period": "2025-Q1"}]
|
||||
_, rem = z.plan(ex, PORTAL, known=set(), horizon=2, zones_by_subject={999: set()})
|
||||
assert ex[0] in rem
|
||||
|
||||
|
||||
def test_network_failure_keeps_expectations():
|
||||
"""Сбой периодов не доказывает уход зоны: ожидание остаётся."""
|
||||
ex = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
|
||||
_, rem = z.plan(ex, {}, known=set(), horizon=2, zones_by_subject={1: {7}})
|
||||
assert rem == []
|
||||
|
||||
|
||||
def test_unknown_subject_keeps_expectations():
|
||||
"""Список зон субъекта не прочитан — трогать его ожидания нельзя."""
|
||||
ex = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
|
||||
_, rem = z.plan(ex, {}, known=set(), horizon=2, zones_by_subject={})
|
||||
assert rem == []
|
||||
|
||||
|
||||
def _scan_stand(tmp_path, monkeypatch, periods, known=(), expect=None,
|
||||
pull_error=None, fail_periods=False, fail_subjects=False):
|
||||
db = tmp_path / "fgis.sqlite"
|
||||
con = sqlite3.connect(db)
|
||||
con.execute("create table zone_snapshots(subject_id int, zone_id int, period_id int)")
|
||||
con.executemany("insert into zone_snapshots values (?,?,?)", known)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
class Client:
|
||||
def country_subjects(self):
|
||||
if fail_subjects:
|
||||
raise RuntimeError("сеть недоступна")
|
||||
return [{"id": 1}]
|
||||
|
||||
def price_zones(self, sid):
|
||||
return [{"id": 7}]
|
||||
|
||||
def periods(self, zid):
|
||||
if fail_periods:
|
||||
raise RuntimeError("таймаут")
|
||||
return periods
|
||||
|
||||
def pull_split_form(sid, zid, pid):
|
||||
if pull_error:
|
||||
raise RuntimeError(pull_error)
|
||||
|
||||
monkeypatch.setitem(sys.modules, "fgis_client", Client())
|
||||
monkeypatch.setitem(sys.modules, "ext_pull",
|
||||
types.SimpleNamespace(pull_split_form=pull_split_form))
|
||||
expect_path = tmp_path / "expect.json"
|
||||
if expect is not None:
|
||||
expect_path.write_text(json.dumps(expect, ensure_ascii=False), encoding="utf-8")
|
||||
state_path = tmp_path / "state.json"
|
||||
log_path = tmp_path / "scan.log"
|
||||
monkeypatch.setenv("SCAN_LOCK", str(tmp_path / "scan.lock"))
|
||||
monkeypatch.delenv("OPERATOR_EMAIL", raising=False)
|
||||
monkeypatch.setattr(sys, "argv", [
|
||||
"fgis_zone_scan.py", "--expect", str(expect_path), "--state", str(state_path),
|
||||
"--log", str(log_path), "--db", str(db)])
|
||||
code = z.main()
|
||||
return code, expect_path, state_path, log_path
|
||||
|
||||
|
||||
def test_new_period_is_added_and_run_marked_success(tmp_path, monkeypatch):
|
||||
periods = [p(1, "1 квартал 2025"), p(2, "2 квартал 2025"), p(3, "3 квартал 2025"),
|
||||
p(4, "4 квартал 2025 г."), p(5, "1 квартал 2026 г.")]
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, periods, known={(1, 7, 4)}, expect=[])
|
||||
assert code == 0
|
||||
assert "добавлено=1" in log.read_text(encoding="utf-8")
|
||||
data = json.loads(state.read_text(encoding="utf-8"))
|
||||
assert data["failures"] == [] and data["last_success"]
|
||||
|
||||
|
||||
def test_expired_expectation_is_removed(tmp_path, monkeypatch):
|
||||
periods = [p(1, "1 квартал 2025"), p(2, "2 квартал 2025"), p(3, "3 квартал 2025"),
|
||||
p(4, "4 квартал 2025 г."), p(5, "1 квартал 2026 г.")]
|
||||
old = [{"subject_id": 1, "zone_id": 7, "period": "2024-Q1", "reason": "старое"}]
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, periods, known={(1, 7, 3), (1, 7, 4), (1, 7, 5)}, expect=old)
|
||||
assert code == 0
|
||||
assert "снято=1" in log.read_text(encoding="utf-8")
|
||||
assert json.loads(expect.read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_network_failure_keeps_files_and_marks_no_success(tmp_path, monkeypatch):
|
||||
old = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1", "reason": "нет форм"}]
|
||||
before = json.dumps(old, ensure_ascii=False)
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, [], expect=old, fail_periods=True)
|
||||
assert code == 1
|
||||
assert expect.read_text(encoding="utf-8") == before
|
||||
data = json.loads(state.read_text(encoding="utf-8"))
|
||||
assert data["failures"] and not data.get("last_success")
|
||||
assert "сбоев=1" in log.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_country_list_failure_keeps_expectations(tmp_path, monkeypatch):
|
||||
old = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
|
||||
before = json.dumps(old, ensure_ascii=False)
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, [], expect=old, fail_subjects=True)
|
||||
assert code == 1
|
||||
assert expect.read_text(encoding="utf-8") == before
|
||||
assert json.loads(state.read_text(encoding="utf-8"))["failures"]
|
||||
@@ -715,3 +715,41 @@ def test_old_canaries_are_marked_as_retired():
|
||||
head = open(os.path.join(ROOT, "scripts", name), encoding="utf-8").read()[:1500]
|
||||
assert "снят с расписания" in head, name
|
||||
assert "health_checks.py" in head, name
|
||||
|
||||
|
||||
# --- Д. Свежесть ежедневного обхода зон ФГИС -----------------------------------
|
||||
|
||||
def _zone_state(tmp_path, monkeypatch, **state):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
now = datetime.now(timezone.utc)
|
||||
state.setdefault("last_success", (now - timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M:%SZ"))
|
||||
path = tmp_path / "zone_state.json"
|
||||
path.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
|
||||
monkeypatch.setenv("ZONE_SCAN_STATE", str(path))
|
||||
return path
|
||||
|
||||
|
||||
def test_zone_scan_fresh_success_is_green(env, tmp_path, monkeypatch):
|
||||
_, h, _ = env
|
||||
_zone_state(tmp_path, monkeypatch, last_attempt="2026-11-22T06:00:00Z", failures=[])
|
||||
c = h.check_zone_scan()
|
||||
assert c.ok and c.name == "zone_scan"
|
||||
assert "возраст" in c.detail
|
||||
|
||||
|
||||
def test_zone_scan_stale_success_is_red(env, tmp_path, monkeypatch):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
_, h, _ = env
|
||||
old = (datetime.now(timezone.utc) - timedelta(hours=40)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
_zone_state(tmp_path, monkeypatch, last_success=old, failures=[])
|
||||
c = h.check_zone_scan()
|
||||
assert not c.ok and "возраст" in c.detail
|
||||
|
||||
|
||||
def test_zone_scan_failed_last_run_is_red(env, tmp_path, monkeypatch):
|
||||
_, h, _ = env
|
||||
_zone_state(tmp_path, monkeypatch, last_attempt="2026-11-22T06:00:00Z",
|
||||
failures=["periods 1/7: Timeout"])
|
||||
c = h.check_zone_scan()
|
||||
assert not c.ok
|
||||
assert "сбоями" in c.detail and "periods 1/7" in c.detail
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Инъекция факта региональной базы в контекст агента (22.11.2026)."""
|
||||
import sqlite3, sys
|
||||
from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import main # noqa: E402
|
||||
|
||||
def _env(tmp_path, monkeypatch):
|
||||
db = tmp_path / "regional_ref.sqlite"
|
||||
con = sqlite3.connect(db)
|
||||
con.executescript("""
|
||||
create table subjects(code integer primary key, name text);
|
||||
create table sources(id integer primary key, subject_id int, kind text, edition text,
|
||||
act text, file_sha text, manifest_sha text, imported_at text);
|
||||
create table works(id integer primary key, subject_id int, kind text, code text,
|
||||
name text, unit text, price real, source_id int);
|
||||
create table prices(id integer primary key, subject_id int, kind text, code text,
|
||||
name text, unit text, price_otp real, price_smet real, source_id int);
|
||||
""")
|
||||
con.execute("insert into subjects values(337,'Оренбургская область')")
|
||||
con.execute("insert into sources values(1,337,'ТЕР','ред. 2014','приказ','sha1','sha2','now')")
|
||||
con.execute("insert into works values(1,337,'ТЕР','01-01-001-01','15 м³','м3',3270.04,1)")
|
||||
con.commit(); con.close()
|
||||
reg = tmp_path / "reference_sources.json"
|
||||
reg.write_text('{"subjects":[{"code":337,"name":"Оренбургская область"}]}', encoding="utf-8")
|
||||
monkeypatch.setenv("REGIONAL_REF_PATH", str(db))
|
||||
monkeypatch.setenv("REGIONAL_REGISTRY", str(reg))
|
||||
|
||||
def test_injects_found_rate(tmp_path, monkeypatch):
|
||||
_env(tmp_path, monkeypatch)
|
||||
fact = main._regional_fact("Какая расценка по коду 01-01-001-01 в Оренбургской области?")
|
||||
assert fact and "РЕГИОНАЛЬНОЙ БАЗЫ" in fact and "3270.04" in fact and "sha2" in fact
|
||||
|
||||
def test_ignores_without_code(tmp_path, monkeypatch):
|
||||
_env(tmp_path, monkeypatch)
|
||||
assert main._regional_fact("Расценка в Оренбургской области?") is None
|
||||
@@ -0,0 +1,46 @@
|
||||
"""MCP-инструмент regional_rate: три состояния, отсутствие базы, регистрация."""
|
||||
import sqlite3, sys
|
||||
from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import smeta_mcp # noqa: E402
|
||||
import regional_ref # noqa: E402
|
||||
|
||||
def _db(tmp_path: Path) -> Path:
|
||||
db = tmp_path / "regional_ref.sqlite"
|
||||
con = sqlite3.connect(db)
|
||||
con.executescript("""
|
||||
create table subjects(code integer primary key, name text);
|
||||
create table sources(id integer primary key, subject_id int, kind text, edition text,
|
||||
act text, file_sha text, manifest_sha text, imported_at text);
|
||||
create table works(id integer primary key, subject_id int, kind text, code text,
|
||||
name text, unit text, price real, source_id int);
|
||||
create table prices(id integer primary key, subject_id int, kind text, code text,
|
||||
name text, unit text, price_otp real, price_smet real, source_id int);
|
||||
""")
|
||||
con.execute("insert into subjects values(337,'Оренбургская область')")
|
||||
con.execute("insert into sources values(1,337,'ТЕР','ред. 2014','приказ','sha1','sha2','now')")
|
||||
con.execute("insert into works values(1,337,'ТЕР','01-01-001-01','15 м³','м3',3270.04,1)")
|
||||
con.commit(); con.close(); return db
|
||||
|
||||
def test_tool_registered():
|
||||
assert "regional_rate" in smeta_mcp.TOOLS
|
||||
assert smeta_mcp.TOOLS["regional_rate"]["fn"] is smeta_mcp.tool_regional_rate
|
||||
|
||||
def test_found_regional_label_and_provenance(tmp_path, monkeypatch):
|
||||
db = _db(tmp_path); monkeypatch.setenv("REGIONAL_REF_PATH", str(db))
|
||||
r = smeta_mcp.tool_regional_rate(code="01-01-001-01", subject_id=337, kind="ТЕР")
|
||||
assert r["status"] == "ok" and r["base"] == "региональная"
|
||||
assert r["subject"] == "Оренбургская область" and r["price"] == 3270.04
|
||||
assert r["file_sha"] == "sha1" and r["manifest_sha"] == "sha2"
|
||||
|
||||
def test_code_missing_and_kind_missing(tmp_path, monkeypatch):
|
||||
db = _db(tmp_path); monkeypatch.setenv("REGIONAL_REF_PATH", str(db))
|
||||
assert smeta_mcp.tool_regional_rate(code="99-99-999-99", subject_id=337)["status"] == "code_not_found"
|
||||
r = smeta_mcp.tool_regional_rate(code="101-0001", subject_id=337, kind="ТССЦ")
|
||||
assert r["status"] == "kind_not_loaded"
|
||||
|
||||
def test_db_unavailable_not_silent(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("REGIONAL_REF_PATH", str(tmp_path / "missing.sqlite"))
|
||||
r = smeta_mcp.tool_regional_rate(code="01-01-001-01", subject_id=337)
|
||||
assert r["status"] == "db_unavailable" and "недоступна" in r["message"]
|
||||
Reference in New Issue
Block a user