"""Сборка и чтение tsn_ref.sqlite (T5, T6): сборка из выжимок, замена с бэкапом, поиск с честными статусами, несовпадение версии схемы. """ import json import os import sqlite3 import sys import pytest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) import ext_state # noqa: E402 import scripts.build_tsn_ref as build_mod # noqa: E402 import tsn_ref # noqa: E402 def _rate_extract(code="1-1-1", pz=30.0, add=None, name="Разработка грунта экскаваторами"): return { "works": [{"code": code, "name": name, "unit": "100 м3", "table_no": "1-1", "page": 17, "pz": pz, "ot": 10.0, "em": 20.0, "mat": 0.0, "labor": 0.5, "resources": [{"code": "2.1-1-13", "quantity": 1.1415}]}], "quarantine": [], "stats": {"works_parsed": 1, "completeness": 1.0}, } def _index_extract(issue="222", value=8.0): return {"issue_no": issue, "quarter": 4, "year": 2026, "decree": "МКЭ-ОД/26-76", "addendum_no": "83", "values": [{"code": "1.1-1-1", "value": value, "page": 12}], "stats": {"values_parsed": 1}} def _snap(root, key, kind, extract, doc=None): d = root / "snapshots" / "niac_tsn" / "sec" / key d.mkdir(parents=True) (d / "extract.json").write_text(json.dumps(extract, ensure_ascii=False), encoding="utf-8") meta = {"key": key, "kind": kind, "section": "sec", "book": "ТСН-2001.3", "chapter": "1-1", "edition": "", "addendum_no": doc or "", "issue_no": None, "title": key, "file": key + ".pdf", "sha256": "sha-" + key, "url": "", "pages": 10} (d / "meta.json").write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8") @pytest.fixture() def built(tmp_path, monkeypatch): monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path / "ext") (tmp_path / "ext").mkdir() snaps = tmp_path / "ext" _snap(snaps, "rates", "rate_book", _rate_extract()) _snap(snaps, "index", "index_release", _index_extract()) out = tmp_path / "tsn_ref.sqlite" report = build_mod.build(snaps, out) return {"db": out, "report": report, "tmp": tmp_path} def test_build_creates_db_with_rows(built): assert built["report"]["ok"] is True con = sqlite3.connect(built["db"]) try: assert con.execute("SELECT COUNT(*) FROM works").fetchone()[0] == 1 assert con.execute("SELECT COUNT(*) FROM index_values").fetchone()[0] == 1 assert con.execute("SELECT COUNT(*) FROM release").fetchone()[0] == 1 assert con.execute("SELECT active FROM release").fetchone()[0] == 1 finally: con.close() def test_build_refuses_duplicate_code_with_different_money(tmp_path, monkeypatch): monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path / "ext") (tmp_path / "ext").mkdir() _snap(tmp_path / "ext", "a", "rate_book", _rate_extract(pz=30.0)) second = _rate_extract(pz=45.0) second["works"][0]["ot"], second["works"][0]["em"] = 15.0, 30.0 # деньги сходятся, цена другая _snap(tmp_path / "ext", "b", "rate_book", second) report = build_mod.build(tmp_path / "ext", tmp_path / "x.sqlite") assert report["ok"] is False assert "дубл" in " ".join(report["problems"]).lower() def test_apply_replaces_with_backup(built, tmp_path): staging = built["tmp"] / "staging.sqlite" build_mod.build(built["tmp"] / "ext", staging) target = tmp_path / "live.sqlite" target.write_bytes(b"old db content") rep = build_mod.apply(staging, target) assert rep["ok"] is True assert rep["backup"] and os.path.exists(rep["backup"]) assert target.read_bytes() != b"old db content" assert sqlite3.connect(target).execute("SELECT COUNT(*) FROM works").fetchone()[0] == 1 def test_apply_refuses_broken_staging(built): bad = built["tmp"] / "bad.sqlite" bad.write_bytes(b"not a database") rep = build_mod.apply(bad, built["tmp"] / "live.sqlite") assert rep["ok"] is False def test_find_work_by_code_and_name(built, monkeypatch): monkeypatch.setenv("TSN_REF_PATH", str(built["db"])) by_code = tsn_ref.find_work("1-1-1") assert by_code["status"] == "ok" and by_code["items"][0]["code"] == "1-1-1" by_name = tsn_ref.find_work("экскаватор") assert by_name["status"] == "ok", by_name assert tsn_ref.find_work("нет-такого").get("message") assert tsn_ref.find_work("нет-такого")["status"] in ("not_found", "quarantined") def test_missing_db_is_honest(monkeypatch, tmp_path): monkeypatch.setenv("TSN_REF_PATH", str(tmp_path / "nope.sqlite")) res = tsn_ref.find_work("1-1-1") assert res["status"] == "db_unavailable" assert "не развёрнута" in res["message"].lower() or "нет" in res["message"].lower() def test_corrupt_db_is_not_missing(monkeypatch, tmp_path): p = tmp_path / "bad.sqlite" p.write_bytes(b"garbage") monkeypatch.setenv("TSN_REF_PATH", str(p)) res = tsn_ref.find_work("1-1-1") assert res["status"] == "db_corrupt" def test_schema_mismatch_detected(built, monkeypatch): con = sqlite3.connect(built["db"]) con.execute("UPDATE meta SET value='999' WHERE key='schema_version'") con.commit() con.close() monkeypatch.setenv("TSN_REF_PATH", str(built["db"])) res = tsn_ref.find_work("1-1-1") assert res["status"] == "schema_mismatch" def test_status_line_reports_counts(built, monkeypatch): monkeypatch.setenv("TSN_REF_PATH", str(built["db"])) line = tsn_ref.status_line() assert "ТСН-2001" in line and "1" in line