Диск norm_registry.json был засеян СТАРЫМ SEED (без topic/valid_from) → pick по теме не находил (topic не выводится миграцией-на-чтении). load() накладывает код-SEED на записи confirmed_by=seed (новые поля доходят до диска БЕЗ перезаписи; операторские записи не трогаются). Писатели читают сырой диск (_read), overlay не персистится. Пустой docs → SEED-факты всё равно в блоке (безопаснее). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
158 lines
9.0 KiB
Python
158 lines
9.0 KiB
Python
"""Реестр статусов нормативных документов: засев, prompt_block, human-gate, fail-soft."""
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||
import ext_state as es # noqa: E402
|
||
import norm_registry as nr # noqa: E402
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def _tmp(monkeypatch, tmp_path):
|
||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
|
||
return tmp_path
|
||
|
||
|
||
def test_seed_on_first_load(_tmp):
|
||
reg = nr.load()
|
||
assert "gsn-81-05-02-2007" in reg["docs"] and reg["docs"]["gsn-81-05-02-2007"]["status"] == "repealed"
|
||
assert (_tmp / "norm_registry.json").exists() # засев записан на диск
|
||
|
||
|
||
def test_prompt_block_marks_repealed_and_active(_tmp):
|
||
b = nr.prompt_block()
|
||
# отменённые ГСН — с явной пометкой, действующие методики — как действующие
|
||
assert "ГСН 81-05-02-2007" in b and "ОТМЕНЁН" in b
|
||
assert "325/пр" in b and "332/пр" in b
|
||
assert "ФРСН" in b # правило про неизвестные документы
|
||
|
||
|
||
def test_failsoft_corrupt_file_keeps_base_facts(_tmp):
|
||
(_tmp / "norm_registry.json").write_text("{битый", encoding="utf-8")
|
||
b = nr.prompt_block() # не падает
|
||
assert "ГСН 81-05-02-2007" in b and "ОТМЕНЁН" in b # базовые факты из SEED всё равно есть
|
||
|
||
|
||
def test_pending_candidate_not_in_prompt_until_confirmed(_tmp):
|
||
"""Money-gate: авто-кандидат НЕ влияет на промпт до подтверждения оператором."""
|
||
cand = {"doc_id": "gsn-99-test", "basis": "999/пр", "title": "ГСН-99 тестовый",
|
||
"status": "repealed"}
|
||
nr.propose(cand)
|
||
assert "ГСН-99" not in nr.prompt_block() # pending → в промпт НЕ идёт
|
||
assert any(c["doc_id"] == "gsn-99-test" for c in nr.pending())
|
||
# оператор подтвердил → теперь в реестре и в промпте
|
||
assert nr.confirm("999/пр", "gsn-99-test", "approve", "yuri") is True
|
||
assert "ГСН-99" in nr.prompt_block()
|
||
assert not nr.pending() # из очереди убран
|
||
|
||
|
||
def test_reject_candidate_not_applied(_tmp):
|
||
nr.propose({"doc_id": "x-reject", "basis": "111/пр", "title": "X отклонён", "status": "repealed"})
|
||
assert nr.confirm("111/пр", "x-reject", "reject", "yuri") is True
|
||
assert "x-reject" not in nr.load()["docs"] and "X отклонён" not in nr.prompt_block()
|
||
|
||
|
||
def test_propose_dedup(_tmp):
|
||
c = {"doc_id": "d1", "basis": "222/пр", "title": "Дубль", "status": "repealed"}
|
||
nr.propose(c)
|
||
nr.propose(c)
|
||
assert sum(1 for x in nr.pending() if x["doc_id"] == "d1") == 1 # дедуп по (basis, doc_id)
|
||
|
||
|
||
def test_writer_does_not_clobber_corrupt_file(_tmp):
|
||
"""Д1: битый файл (мог хранить подтверждённые записи) — propose/confirm НЕ затирают его SEED-ом,
|
||
а падают (fail-loud), чтобы оператор восстановил вручную."""
|
||
(_tmp / "norm_registry.json").write_text("{битый json", encoding="utf-8")
|
||
with pytest.raises(RuntimeError):
|
||
nr.propose({"doc_id": "x", "basis": "1/пр", "title": "t", "status": "repealed"})
|
||
# файл не перезаписан
|
||
assert (_tmp / "norm_registry.json").read_text(encoding="utf-8").startswith("{битый")
|
||
|
||
|
||
def test_confirm_rejects_bad_decision(_tmp):
|
||
"""Д2: опечатка в decision не должна тихо стать reject."""
|
||
nr.propose({"doc_id": "y", "basis": "2/пр", "title": "t", "status": "repealed"})
|
||
with pytest.raises(ValueError):
|
||
nr.confirm("2/пр", "y", "aprove", "yuri") # опечатка → ошибка, не тихий reject
|
||
assert any(c["doc_id"] == "y" for c in nr.pending()) # кандидат на месте
|
||
|
||
|
||
def test_base_facts_survive_empty_docs(_tmp):
|
||
"""Д3 + overlay: пустой docs на диске → код-SEED накладывается → базовые статусы (отменённые
|
||
ГСН) ВСЁ РАВНО в блоке (не пусто, не откат к весам). Заглушка — только на исключении."""
|
||
(_tmp / "norm_registry.json").write_text('{"docs": {}, "pending": []}', encoding="utf-8")
|
||
s = nr.prompt_block_or_stub()
|
||
assert s and "ГСН 81-05-02-2007" in s and "ОТМЕНЁН" in s # базовые факты из SEED-overlay
|
||
|
||
|
||
def test_asof_boundary_winter(_tmp):
|
||
"""Граница действия зимнего удорожания: 07.08.2021 — ещё ГСН-2007, 08.08.2021 — уже 325/пр."""
|
||
assert nr.doc_status_on("gsn-81-05-02-2007", "2021-08-07") == "active"
|
||
assert nr.doc_status_on("gsn-81-05-02-2007", "2021-08-08") == "repealed"
|
||
assert nr.doc_status_on("prikaz-325-pr", "2021-08-07") == "not_yet"
|
||
assert nr.doc_status_on("prikaz-325-pr", "2021-08-08") == "active"
|
||
|
||
|
||
def test_pick_by_epoch(_tmp):
|
||
"""Ретро-выбор документа по теме и дате — та эпоха, что действовала."""
|
||
assert nr.pick("winter", "2019-06-01") == "gsn-81-05-02-2007"
|
||
assert nr.pick("winter", "2026-01-01") == "prikaz-325-pr"
|
||
assert nr.pick("temp_buildings", "2019-06-01") == "gsn-81-05-01-2001"
|
||
assert nr.pick("temp_buildings", "2026-01-01") == "prikaz-332-pr"
|
||
|
||
|
||
def test_as_of_block_epochs(_tmp):
|
||
b2019 = nr.as_of_block("2019-06-01")
|
||
assert "ГСН 81-05-02-2007" in b2019 and "ГСН 81-05-01-2001" in b2019
|
||
assert "325/пр" not in b2019 # ещё не действовал
|
||
b2026 = nr.as_of_block("2026-01-01")
|
||
assert "325/пр" in b2026 and "332/пр" in b2026 and "ГСН 81-05-02-2007" not in b2026
|
||
|
||
|
||
def test_asof_rejects_malformed_date(_tmp):
|
||
"""A1 (Fable): кривая/неполная дата НЕ должна выдать норму чужой эпохи как действовавшую."""
|
||
for bad in ("2021-1-5", "2019", "", "вчера", "2021/08/08"):
|
||
assert nr.pick("winter", bad) is None # не подставляем наугад
|
||
assert nr.doc_status_on("prikaz-325-pr", bad) == "unknown"
|
||
assert "неполн" in nr.as_of_block(bad).lower() or "формат" in nr.as_of_block(bad).lower()
|
||
# именно из-за 2021-1-5 > 2021-08-08 посимвольно раньше выдавалось 325/пр — теперь отказ
|
||
assert nr.pick("winter", "2021-01-05") == "gsn-81-05-02-2007" # корректная дата — верная эпоха
|
||
|
||
|
||
def test_repealed_without_end_date_not_active_forever(_tmp):
|
||
"""A2 (Fable): отменённый БЕЗ подтверждённой даты отмены не должен числиться действующим вечно."""
|
||
(_tmp / "norm_registry.json").write_text(__import__("json").dumps({
|
||
"docs": {"x": {"title": "X", "topic": "nr", "status": "repealed",
|
||
"valid_from": "2010-01-01", "confirmed_by": "op"}}, # тема вне SEED, не seed
|
||
"pending": []}, ensure_ascii=False), encoding="utf-8")
|
||
assert nr.doc_status_on("x", "2026-01-01") == "unknown" # НЕ active
|
||
assert nr.pick("nr", "2026-01-01") is None
|
||
|
||
|
||
def test_pick_overlap_refuses(_tmp):
|
||
"""A3 (Fable): два активных документа одной темы на дату (ошибка данных) → None, не молча старый."""
|
||
(_tmp / "norm_registry.json").write_text(__import__("json").dumps({
|
||
"docs": {
|
||
"old": {"title": "Старый", "topic": "nr", "status": "active", "valid_from": "2015-01-01", "confirmed_by": "op"},
|
||
"new": {"title": "Новый", "topic": "nr", "status": "active", "valid_from": "2020-01-01", "confirmed_by": "op"}},
|
||
"pending": []}, ensure_ascii=False), encoding="utf-8")
|
||
assert nr.pick("nr", "2026-01-01") is None # перекрытие → отказ, не «Старый»
|
||
|
||
|
||
def test_prompt_block_default_unchanged_by_temporal(_tmp):
|
||
"""Обратная совместимость: prompt_block() без даты по-прежнему даёт статус «на сегодня»."""
|
||
b = nr.prompt_block()
|
||
assert "325/пр" in b and "ОТМЕНЁН" in b and "ГСН 81-05-02-2007" in b
|
||
|
||
|
||
def test_prompt_block_survives_nondict_successor(_tmp):
|
||
"""Запись-не-dict в successor не роняет блок (load валидирует только верхний уровень)."""
|
||
import json as _j
|
||
(_tmp / "norm_registry.json").write_text(_j.dumps({
|
||
"docs": {"a": {"title": "A", "status": "repealed", "successor": "b"}, "b": "не-dict"},
|
||
"pending": []}, ensure_ascii=False), encoding="utf-8")
|
||
b = nr.prompt_block() # не падает
|
||
assert "A" in b and "ОТМЕНЁН" in b
|