229 lines
9.4 KiB
Python
229 lines
9.4 KiB
Python
"""Публичная витрина показывает нормативный корпус."""
|
|
import json
|
|
import sqlite3
|
|
import sys
|
|
from pathlib import Path
|
|
import pytest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
if str(ROOT) not in sys.path:
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def isolated_normative_project(tmp_path, monkeypatch):
|
|
"""Тесты с маленьким корпусом не наследуют путь к нормативной базе стенда."""
|
|
import public_documents
|
|
|
|
monkeypatch.setenv("SMETA_PROJECT_DIR", str(tmp_path / "empty_norms"))
|
|
public_documents.clear_cache()
|
|
yield
|
|
public_documents.clear_cache()
|
|
|
|
|
|
def _tsn(root: Path, key: str, title: str, fetched: str):
|
|
d = root / "snapshots" / "niac_tsn" / "collections" / key
|
|
d.mkdir(parents=True)
|
|
(d / "extract.json").write_text("{}", encoding="utf-8")
|
|
(d / "meta.json").write_text(json.dumps({"title": title, "fetched_at": fetched,
|
|
"key": key}), encoding="utf-8")
|
|
|
|
|
|
def _bim(root: Path, key: str, fetched: str):
|
|
d = root / "snapshots" / "fgis" / "bim_letters" / key
|
|
d.mkdir(parents=True)
|
|
(d / "letter.pdf").write_bytes(b"%PDF-1.4")
|
|
(d / "meta.json").write_text(json.dumps({"source": "fgis_bim",
|
|
"fetched_at": fetched}), encoding="utf-8")
|
|
|
|
|
|
def test_counts_only_available_public_documents_and_orders_feed(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path)
|
|
public_documents.clear_cache()
|
|
_tsn(tmp_path, "older", "ТСН: старый", "2026-10-01T10:00:00Z")
|
|
_tsn(tmp_path, "newer", "ТСН: новый", "2026-11-18T10:00:00Z")
|
|
_bim(tmp_path, "letter", "2026-11-01T10:00:00Z")
|
|
incomplete = tmp_path / "snapshots" / "niac_tsn" / "collections" / "incomplete"
|
|
incomplete.mkdir()
|
|
(incomplete / "meta.json").write_text('{"title":"не загружен"}', encoding="utf-8")
|
|
|
|
result = public_documents.snapshot()
|
|
assert result["count"] == 3
|
|
assert [(d["source"], d["loaded"][1]) for d in result["recent"]] == [
|
|
("ТСН Москвы", "18.11.2026"), ("ФГИС ЦС", "01.11.2026"),
|
|
("ТСН Москвы", "01.10.2026")]
|
|
|
|
|
|
def test_one_batch_does_not_hide_other_document_updates(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path)
|
|
for i in range(5):
|
|
_tsn(tmp_path, f"batch-{i}", f"ТСН {i}", f"2026-11-17T18:44:{i:02d}Z")
|
|
_bim(tmp_path, "letter", "2026-11-14T17:04:17Z")
|
|
public_documents.clear_cache()
|
|
|
|
recent = public_documents.snapshot()["recent"]
|
|
assert len(recent) == 2
|
|
assert recent[0]["source"] == "ТСН Москвы"
|
|
assert "5" in recent[0]["title"]
|
|
assert recent[1]["source"] == "ФГИС ЦС"
|
|
assert "1" in recent[1]["title"]
|
|
assert "</span> <span class=\"public-doc-meta\">" in public_documents.render()
|
|
|
|
|
|
def test_public_markup_escapes_titles_and_has_honest_empty_state(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path)
|
|
public_documents.clear_cache()
|
|
html = public_documents.render()
|
|
assert "Документы пока не загружены" in html
|
|
assert 'id="public-gesn-norms">—<' in html
|
|
|
|
_tsn(tmp_path, "xss", "Безопасный документ", "2026-11-18T10:00:00Z")
|
|
public_documents.clear_cache()
|
|
public_documents.snapshot()["recent"][0]["title"] = '<img src=x onerror=alert(1)>'
|
|
html = public_documents.render()
|
|
assert "<img" in html
|
|
assert "<img" not in html
|
|
assert str(tmp_path) not in html
|
|
assert 'id="public-tsn-works">—<' in html
|
|
|
|
|
|
def test_landing_contains_public_documents_section():
|
|
html = (ROOT / "static" / "chat.html").read_text(encoding="utf-8")
|
|
assert 'id="public-documents"' in html
|
|
assert "{{PUBLIC_DOCUMENTS}}" in html
|
|
|
|
|
|
def test_homepage_renders_public_feed_without_login(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
import main
|
|
from fastapi.testclient import TestClient
|
|
|
|
monkeypatch.chdir(ROOT)
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: tmp_path)
|
|
public_documents.clear_cache()
|
|
_tsn(tmp_path, "new", "ТСН: опубликованный", "2026-11-18T10:00:00Z")
|
|
response = TestClient(main.app).get("/?v=" + main.APP_VERSION)
|
|
assert response.status_code == 200
|
|
assert 'id="public-gesn-norms"' in response.text
|
|
assert "Обновлено документов ТСН Москвы: 1" in response.text
|
|
assert "{{PUBLIC_DOCUMENTS}}" not in response.text
|
|
|
|
|
|
def test_isolated_stage_reads_only_exported_public_summary(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
|
|
source = tmp_path / "production"
|
|
stage = tmp_path / "stage"
|
|
_tsn(source, "public", "Общий норматив", "2026-11-18T10:00:00Z")
|
|
_bim(source, "letter", "2026-11-17T10:00:00Z")
|
|
public_documents.export_summary(source, stage / "landing_documents.json")
|
|
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: stage)
|
|
public_documents.clear_cache()
|
|
data = public_documents.snapshot()
|
|
assert data["count"] == 2
|
|
assert [(doc["source"], doc["loaded"][1]) for doc in data["recent"]] == [
|
|
("ТСН Москвы", "18.11.2026"), ("ФГИС ЦС", "17.11.2026")]
|
|
|
|
|
|
def test_counts_builtin_normative_literature_too(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
|
|
ext = tmp_path / "ext"
|
|
project = tmp_path / "norms"
|
|
literature = project / "literature" / "methods"
|
|
literature.mkdir(parents=True)
|
|
(literature / "method.pdf").write_bytes(b"%PDF-1.4")
|
|
(literature / "appendix.htm").write_text("нормы", encoding="utf-8")
|
|
(literature / "notes.txt").write_text("не документ", encoding="utf-8")
|
|
gesn = project / "data" / "gesn_extra"
|
|
gesn.mkdir(parents=True)
|
|
(gesn / "gesn_01.json").write_text(json.dumps({
|
|
"01-01-001-01": {"name": "Работа 1"},
|
|
"01-01-001-02": {"name": "Работа 2"},
|
|
"broken": {"error": "нет данных"}}), encoding="utf-8")
|
|
_tsn(ext, "tsn", "ТСН", "2026-11-18T10:00:00Z")
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: ext)
|
|
monkeypatch.setenv("SMETA_PROJECT_DIR", str(project))
|
|
public_documents.clear_cache()
|
|
|
|
result = public_documents.snapshot()
|
|
assert result["count"] == 3
|
|
assert result["norm_count"] == 2
|
|
assert 'id="public-gesn-norms">2<' in public_documents.render()
|
|
assert [doc["title"] for doc in result["recent"]] == ["Обновлено документов ТСН Москвы: 1"]
|
|
|
|
|
|
def test_all_normative_databases_have_separate_counters(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
|
|
ext = tmp_path / "ext"
|
|
specs = {
|
|
"fsnb/fsnb_ref.sqlite": {"works": 3, "resources": 5},
|
|
"fgis_ref/fgis_ref.sqlite": {"items": 7, "ksr": 11,
|
|
"zone_snapshots": 2},
|
|
"tsn/tsn_ref.sqlite": {"works": 13, "price_items": 17},
|
|
"regional_ref/regional_ref.sqlite": {"works": 19, "prices": 23},
|
|
}
|
|
for relative, tables in specs.items():
|
|
path = ext / "derived" / relative
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with sqlite3.connect(path) as con:
|
|
for table, count in tables.items():
|
|
if table == "zone_snapshots":
|
|
con.execute("CREATE TABLE zone_snapshots (rows_loaded INTEGER)")
|
|
con.executemany("INSERT INTO zone_snapshots VALUES (?)", [(31,), (37,)])
|
|
else:
|
|
con.execute(f"CREATE TABLE {table} (id INTEGER)")
|
|
con.executemany(f"INSERT INTO {table} VALUES (?)",
|
|
[(n,) for n in range(count)])
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: ext)
|
|
result = public_documents.snapshot()
|
|
assert result["metrics"] == {
|
|
"fsnb_works": 3, "fsnb_resources": 5,
|
|
"fgis_items": 7, "ksr": 11, "fgis_price_rows": 68,
|
|
"tsn_works": 13, "tsn_prices": 17,
|
|
"regional_works": 19, "regional_prices": 23,
|
|
"bim_letters": None, "tsn_documents": None,
|
|
"gesn_norms": None, "fssc_regions": None,
|
|
"literature_files": None,
|
|
}
|
|
markup = public_documents.render()
|
|
assert "ФСНБ" in markup and "ФГИС ЦС" in markup
|
|
assert "ТСН Москвы" in markup and "Региональные базы" in markup
|
|
assert "КСР" in markup and "ГЭСН" in markup
|
|
assert "ФССЦ" in markup and "БИМ" in markup
|
|
assert "нормативных файлов-источников" not in markup
|
|
|
|
|
|
def test_export_preserves_database_counters_without_copying_databases(tmp_path, monkeypatch):
|
|
import ext_state
|
|
import public_documents
|
|
|
|
source = tmp_path / "source"
|
|
db = source / "derived" / "fsnb" / "fsnb_ref.sqlite"
|
|
db.parent.mkdir(parents=True)
|
|
with sqlite3.connect(db) as con:
|
|
con.execute("CREATE TABLE works (id INTEGER)")
|
|
con.execute("CREATE TABLE resources (id INTEGER)")
|
|
con.execute("INSERT INTO works VALUES (1)")
|
|
stage = tmp_path / "stage"
|
|
public_documents.export_summary(source, stage / "landing_documents.json")
|
|
monkeypatch.setattr(ext_state, "ext_dir", lambda: stage)
|
|
public_documents.clear_cache()
|
|
assert public_documents.snapshot()["metrics"]["fsnb_works"] == 1
|
|
assert not (stage / "derived").exists()
|