feat(ext): Фаза 0 конвейера источников — хранилище снапшотов + загрузчик
ext_state: версионированные снапшоты (атомарная запись tmp+os.replace, sha256; перезалив задним числом → новая ревизия, старая неприкосновенна — тихое затирание запрещено). ext_sources: декларативный реестр источников (растёт по фазам). ext_fetch: единый httpx- загрузчик (trust_env для прокси, ретраи+бэкофф, потоковое скачивание в .part, fail-loud на малом размере/неверном типе). 12 тестов (моки httpx.MockTransport, без новых зависимостей).
This commit is contained in:
+106
@@ -0,0 +1,106 @@
|
|||||||
|
"""ext_fetch — единый способ ходить в сеть для пайплайна внешних источников (срез 0.2).
|
||||||
|
|
||||||
|
Один загрузчик на всё: JSON-эндпоинты и большие файлы (xlsx/csv/pdf). Принципы:
|
||||||
|
- прокси из окружения (httpx trust_env=True) — HTTPS_PROXY подхватится сам; EXT_NO_PROXY=1
|
||||||
|
→ trust_env=False (гос-сайты РФ могут не ходить через прокси);
|
||||||
|
- ретраи с экспоненциальным бэкоффом (сеть Минстроя нестабильна);
|
||||||
|
- потоковое скачивание в *.part + sha256 на лету + атомарный os.replace — при обрыве
|
||||||
|
целевой файл НЕ появляется (только .part для диагностики), ничего не перезаписано;
|
||||||
|
- fail-loud: размер меньше ожидаемого или не тот content-type → исключение (частичная/
|
||||||
|
битая выгрузка не должна доехать до движка как «валидные данные»).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
USER_AGENT = "smeta-web-ext/1.0 (data pipeline; +https://infosmeta.ru)"
|
||||||
|
CONNECT_TIMEOUT = 10.0
|
||||||
|
READ_TIMEOUT = 120.0 # большие xlsx (сплит-форма ~13.7МБ)
|
||||||
|
RETRIES = 3
|
||||||
|
BACKOFF_BASE = 2.0 # сон = BACKOFF_BASE ** attempt
|
||||||
|
POLITE_PAUSE = 0.0 # пауза между запросами (вежливость); ставится вызывающим при обходах
|
||||||
|
|
||||||
|
|
||||||
|
class FetchError(Exception):
|
||||||
|
"""Сетевой сбой ИЛИ неверный/битый ответ (fail-loud)."""
|
||||||
|
|
||||||
|
|
||||||
|
def _trust_env() -> bool:
|
||||||
|
return os.environ.get("EXT_NO_PROXY", "").strip().lower() not in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
def make_client(**kw) -> httpx.Client:
|
||||||
|
return httpx.Client(
|
||||||
|
trust_env=_trust_env(),
|
||||||
|
timeout=httpx.Timeout(CONNECT_TIMEOUT, read=READ_TIMEOUT, write=30.0, pool=10.0),
|
||||||
|
headers={"User-Agent": USER_AGENT},
|
||||||
|
follow_redirects=True,
|
||||||
|
**kw,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _sleep_backoff(attempt: int) -> None:
|
||||||
|
time.sleep(BACKOFF_BASE ** attempt)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_json(url: str, params: dict | None = None, *, client: httpx.Client | None = None):
|
||||||
|
"""GET → JSON, с ретраями. client передаётся в тестах (MockTransport)."""
|
||||||
|
last: Exception | None = None
|
||||||
|
for attempt in range(RETRIES):
|
||||||
|
c = client or make_client()
|
||||||
|
try:
|
||||||
|
r = c.get(url, params=params)
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
except (httpx.HTTPError, ValueError) as e:
|
||||||
|
last = e
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
_sleep_backoff(attempt)
|
||||||
|
finally:
|
||||||
|
if client is None:
|
||||||
|
c.close()
|
||||||
|
raise FetchError(f"fetch_json {url}: {type(last).__name__}: {last}")
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_file(url: str, dest: os.PathLike | str, *, params: dict | None = None,
|
||||||
|
expect_min_size: int = 1, expected_content_type: str | None = None,
|
||||||
|
client: httpx.Client | None = None) -> dict:
|
||||||
|
"""Потоково скачать в dest (через *.part). Возвращает {path, size, sha256}.
|
||||||
|
fail-loud: мал/не тот тип → FetchError, dest не создан (остаётся .part для разбора)."""
|
||||||
|
dest = Path(dest)
|
||||||
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
part = dest.with_name(dest.name + ".part")
|
||||||
|
last: Exception | None = None
|
||||||
|
for attempt in range(RETRIES):
|
||||||
|
c = client or make_client()
|
||||||
|
try:
|
||||||
|
h = hashlib.sha256()
|
||||||
|
size = 0
|
||||||
|
with c.stream("GET", url, params=params) as r:
|
||||||
|
r.raise_for_status()
|
||||||
|
ct = r.headers.get("content-type", "")
|
||||||
|
if expected_content_type and expected_content_type not in ct:
|
||||||
|
raise FetchError(f"неожиданный content-type {ct!r} (ждали {expected_content_type!r})")
|
||||||
|
with open(part, "wb") as f:
|
||||||
|
for chunk in r.iter_bytes(1 << 16):
|
||||||
|
f.write(chunk)
|
||||||
|
h.update(chunk)
|
||||||
|
size += len(chunk)
|
||||||
|
if size < expect_min_size:
|
||||||
|
raise FetchError(f"файл мал: {size} < {expect_min_size} байт (частичная выгрузка?)")
|
||||||
|
os.replace(part, dest) # атомарно: dest появляется только целым
|
||||||
|
return {"path": str(dest), "size": size, "sha256": h.hexdigest()}
|
||||||
|
except (httpx.HTTPError, FetchError) as e:
|
||||||
|
last = e
|
||||||
|
if attempt < RETRIES - 1:
|
||||||
|
_sleep_backoff(attempt)
|
||||||
|
finally:
|
||||||
|
if client is None:
|
||||||
|
c.close()
|
||||||
|
# Все ретраи исчерпаны: dest не тронут; .part (если есть) оставляем для диагностики.
|
||||||
|
raise FetchError(f"fetch_file {url}: {type(last).__name__}: {last}")
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""ext_sources — декларативный реестр внешних источников (срез 0.1; растёт по фазам).
|
||||||
|
|
||||||
|
Каждый источник — Source: тип, человекочитаемое имя для доклада, частота проверки и
|
||||||
|
функция check() → список находок (для чекера ext_check.py). check заполняется по фазам
|
||||||
|
(ФГИС, pravo, XSD и т.д.). Реестр в КОДЕ, а не в JSON, потому что «как понять, что
|
||||||
|
обновилось» — это функция, а не строка.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Source:
|
||||||
|
name: str # уникальный ключ (fgis_split_form, pravo_minstroy, …)
|
||||||
|
kind: str # 'fgis' | 'pravo' | 'xsd'
|
||||||
|
title: str # человекочитаемо для доклада оператору
|
||||||
|
freq: str # 'daily' | 'weekly' | 'monthly' | 'quarterly'
|
||||||
|
check: Callable[[], list] | None = None # () -> list[dict] находок; None пока не реализован
|
||||||
|
notes: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
SOURCES: list[Source] = [] # наполняется в фазах 1-5
|
||||||
|
|
||||||
|
|
||||||
|
def register(src: Source) -> Source:
|
||||||
|
if by_name(src.name) is not None:
|
||||||
|
raise ValueError(f"источник {src.name!r} уже зарегистрирован")
|
||||||
|
SOURCES.append(src)
|
||||||
|
return src
|
||||||
|
|
||||||
|
|
||||||
|
def by_name(name: str) -> Source | None:
|
||||||
|
return next((s for s in SOURCES if s.name == name), None)
|
||||||
+155
@@ -0,0 +1,155 @@
|
|||||||
|
"""ext_state — версионированное хранилище снапшотов внешних источников (срез 0.1).
|
||||||
|
|
||||||
|
Три роли пайплайна (check/pull/apply) пишут в РАЗНЫЕ файлы: state.json трогают только
|
||||||
|
pull/apply, watch_seen.json — только чекер. Здесь — state и снапшоты.
|
||||||
|
|
||||||
|
Ключевой инвариант (у Минстроя НЕТ версионирования, файлы перезаливаются задним числом):
|
||||||
|
- запись state атомарна (tmp + os.replace) — при сбое не остаётся полу-файла;
|
||||||
|
- регистрация снапшота с тем же ключом, но другим sha256 → НОВАЯ ревизия рядом,
|
||||||
|
старая неприкосновенна (fail-loud против тихого затирания), в meta ставится флаг
|
||||||
|
reuploaded. Тихая перезапись данных движка запрещена.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def ext_dir() -> Path:
|
||||||
|
"""Корень хранилища внешних данных. EXT_SNAPSHOT_DIR > DATA_DIR/_external."""
|
||||||
|
override = os.environ.get("EXT_SNAPSHOT_DIR")
|
||||||
|
if override:
|
||||||
|
return Path(override)
|
||||||
|
base = os.environ.get("DATA_DIR", "./smeta-web-data")
|
||||||
|
return Path(base) / "_external"
|
||||||
|
|
||||||
|
|
||||||
|
def _utcnow() -> str:
|
||||||
|
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
def _atomic_write_text(path: Path, text: str) -> None:
|
||||||
|
"""Атомарная запись: пишем во временный файл в том же каталоге, затем os.replace.
|
||||||
|
При исключении целевой файл не тронут, временный удаляется."""
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||||
|
f.write(text)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.replace(tmp, path) # атомарная замена в пределах одной ФС
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
os.unlink(tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def sha256_file(path: os.PathLike | str) -> str:
|
||||||
|
h = hashlib.sha256()
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||||
|
h.update(chunk)
|
||||||
|
return h.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
# --- state.json (пишут pull/apply) ---
|
||||||
|
|
||||||
|
def _state_path() -> Path:
|
||||||
|
return ext_dir() / "state.json"
|
||||||
|
|
||||||
|
|
||||||
|
def load_state() -> dict:
|
||||||
|
p = _state_path()
|
||||||
|
if not p.exists():
|
||||||
|
return {"sources": {}}
|
||||||
|
try:
|
||||||
|
data = json.loads(p.read_text(encoding="utf-8"))
|
||||||
|
data.setdefault("sources", {})
|
||||||
|
return data
|
||||||
|
except (json.JSONDecodeError, OSError):
|
||||||
|
# Битый state не должен ронять пайплайн — но и не затираем молча:
|
||||||
|
# возвращаем пустой, а битый останется на диске для диагностики.
|
||||||
|
return {"sources": {}}
|
||||||
|
|
||||||
|
|
||||||
|
def save_state(state: dict) -> None:
|
||||||
|
_atomic_write_text(_state_path(), json.dumps(state, ensure_ascii=False, indent=2, sort_keys=True))
|
||||||
|
|
||||||
|
|
||||||
|
# --- снапшоты ---
|
||||||
|
|
||||||
|
def register_snapshot(dest_dir: os.PathLike | str, src_file: os.PathLike | str,
|
||||||
|
*, source: str, key: str, url: str = "",
|
||||||
|
params: dict | None = None, http_status: int = 200) -> dict:
|
||||||
|
"""Положить скачанный файл в версионированный снапшот dest_dir.
|
||||||
|
|
||||||
|
Правила (fail-loud, без тихого затирания):
|
||||||
|
- dest_dir пуст → кладём файл как current, meta.json (rev=1);
|
||||||
|
- есть current с ТЕМ ЖЕ sha256 → no-op, meta.reuploaded=False (файл уже есть);
|
||||||
|
- есть current с ДРУГИМ sha256 → текущий уезжает в rev-N_<дата>/, новый становится
|
||||||
|
current, meta.reuploaded=True (Минстрой перезалил задним числом — старая ревизия цела).
|
||||||
|
|
||||||
|
Возвращает meta dict нового current.
|
||||||
|
"""
|
||||||
|
dest_dir = Path(dest_dir)
|
||||||
|
src_file = Path(src_file)
|
||||||
|
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
new_sha = sha256_file(src_file)
|
||||||
|
fname = src_file.name
|
||||||
|
current = dest_dir / fname
|
||||||
|
meta_path = dest_dir / "meta.json"
|
||||||
|
|
||||||
|
reuploaded = False
|
||||||
|
new_rev = 1
|
||||||
|
if current.exists():
|
||||||
|
old_sha = sha256_file(current)
|
||||||
|
if old_sha == new_sha:
|
||||||
|
# Уже есть ровно этот файл — ничего не меняем, только освежим last_seen_at.
|
||||||
|
meta = _read_meta(meta_path)
|
||||||
|
meta["last_seen_at"] = _utcnow()
|
||||||
|
_atomic_write_text(meta_path, json.dumps(meta, ensure_ascii=False, indent=2))
|
||||||
|
return meta
|
||||||
|
# Другой контент под тем же ключом = перезалив задним числом. Старое — в ревизию,
|
||||||
|
# не трогаем; новый current получит следующий номер ревизии.
|
||||||
|
old_rev = int(_read_meta(meta_path).get("rev", 1))
|
||||||
|
rev_dir = dest_dir / f"rev-{old_rev}_{_utcnow()[:10]}"
|
||||||
|
rev_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.move(str(current), str(rev_dir / fname))
|
||||||
|
if meta_path.exists():
|
||||||
|
shutil.move(str(meta_path), str(rev_dir / "meta.json"))
|
||||||
|
reuploaded = True
|
||||||
|
new_rev = old_rev + 1
|
||||||
|
|
||||||
|
# Копируем новый файл в current (copy, не move — исходник может быть нужен вызывающему).
|
||||||
|
shutil.copyfile(src_file, current)
|
||||||
|
meta = {
|
||||||
|
"source": source,
|
||||||
|
"key": key,
|
||||||
|
"file": fname,
|
||||||
|
"sha256": new_sha,
|
||||||
|
"size": current.stat().st_size,
|
||||||
|
"url": url,
|
||||||
|
"params": params or {},
|
||||||
|
"http_status": http_status,
|
||||||
|
"fetched_at": _utcnow(),
|
||||||
|
"last_seen_at": _utcnow(),
|
||||||
|
"rev": new_rev,
|
||||||
|
"reuploaded": reuploaded,
|
||||||
|
}
|
||||||
|
_atomic_write_text(meta_path, json.dumps(meta, ensure_ascii=False, indent=2))
|
||||||
|
return meta
|
||||||
|
|
||||||
|
|
||||||
|
def _read_meta(meta_path: Path) -> dict:
|
||||||
|
try:
|
||||||
|
return json.loads(meta_path.read_text(encoding="utf-8"))
|
||||||
|
except (json.JSONDecodeError, OSError, FileNotFoundError):
|
||||||
|
return {}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""Срез 0.2: универсальный загрузчик. Моки через httpx.MockTransport (без сети, без новых
|
||||||
|
зависимостей). Проверяем ретраи, атомарность (обрыв → нет dest), fail-loud на маленьком
|
||||||
|
файле и неверном content-type, корректный sha256.
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
import ext_fetch as ef # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _fast_backoff(monkeypatch):
|
||||||
|
monkeypatch.setattr(ef.time, "sleep", lambda *_: None) # не ждём реально в тестах
|
||||||
|
|
||||||
|
|
||||||
|
def _client(handler):
|
||||||
|
return httpx.Client(transport=httpx.MockTransport(handler))
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_json_retries_500_500_200():
|
||||||
|
calls = {"n": 0}
|
||||||
|
def handler(request):
|
||||||
|
calls["n"] += 1
|
||||||
|
if calls["n"] < 3:
|
||||||
|
return httpx.Response(500, text="err")
|
||||||
|
return httpx.Response(200, json={"ok": True, "period": 426})
|
||||||
|
with _client(handler) as c:
|
||||||
|
data = ef.fetch_json("http://x/api", client=c)
|
||||||
|
assert data["period"] == 426 and calls["n"] == 3 # два провала, третий успех
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_json_all_fail_raises():
|
||||||
|
with _client(lambda r: httpx.Response(503)) as c:
|
||||||
|
with pytest.raises(ef.FetchError):
|
||||||
|
ef.fetch_json("http://x/api", client=c)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_file_success_sha_and_no_part(tmp_path):
|
||||||
|
body = b"X" * 5000
|
||||||
|
with _client(lambda r: httpx.Response(200, content=body,
|
||||||
|
headers={"content-type": "application/octet-stream"})) as c:
|
||||||
|
res = ef.fetch_file("http://x/f.xlsx", tmp_path / "f.xlsx",
|
||||||
|
expect_min_size=1000, client=c)
|
||||||
|
import hashlib
|
||||||
|
assert res["size"] == 5000
|
||||||
|
assert res["sha256"] == hashlib.sha256(body).hexdigest()
|
||||||
|
assert (tmp_path / "f.xlsx").exists()
|
||||||
|
assert not (tmp_path / "f.xlsx.part").exists() # .part убран после успеха
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_file_too_small_fails_and_no_dest(tmp_path):
|
||||||
|
with _client(lambda r: httpx.Response(200, content=b"tiny")) as c:
|
||||||
|
with pytest.raises(ef.FetchError):
|
||||||
|
ef.fetch_file("http://x/f.xlsx", tmp_path / "f.xlsx",
|
||||||
|
expect_min_size=100000, client=c)
|
||||||
|
assert not (tmp_path / "f.xlsx").exists() # битый файл не доехал до dest
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_file_wrong_content_type_fails(tmp_path):
|
||||||
|
with _client(lambda r: httpx.Response(200, content=b"<html>err</html>",
|
||||||
|
headers={"content-type": "text/html"})) as c:
|
||||||
|
with pytest.raises(ef.FetchError):
|
||||||
|
ef.fetch_file("http://x/f.xlsx", tmp_path / "f.xlsx",
|
||||||
|
expected_content_type="spreadsheet", client=c)
|
||||||
|
assert not (tmp_path / "f.xlsx").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_trust_env_toggle(monkeypatch):
|
||||||
|
monkeypatch.delenv("EXT_NO_PROXY", raising=False)
|
||||||
|
assert ef._trust_env() is True
|
||||||
|
monkeypatch.setenv("EXT_NO_PROXY", "1")
|
||||||
|
assert ef._trust_env() is False
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""Срез 0.1: версионированное хранилище состояния/снапшотов внешних источников.
|
||||||
|
|
||||||
|
Ключевой инвариант — ТИХОЕ ЗАТИРАНИЕ ЗАПРЕЩЕНО: перезалив файла задним числом (тот же
|
||||||
|
ключ, другой sha256) создаёт новую ревизию, старая остаётся неприкосновенной.
|
||||||
|
red-green: тесты на «не затирать» и «атомарность» — первыми.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
import ext_state as es # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _use_tmp(monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
|
||||||
|
|
||||||
|
|
||||||
|
def test_ext_dir_env_override(monkeypatch, tmp_path):
|
||||||
|
_use_tmp(monkeypatch, tmp_path)
|
||||||
|
assert es.ext_dir() == tmp_path
|
||||||
|
monkeypatch.delenv("EXT_SNAPSHOT_DIR", raising=False)
|
||||||
|
monkeypatch.setenv("DATA_DIR", "/somewhere")
|
||||||
|
assert es.ext_dir() == Path("/somewhere/_external")
|
||||||
|
|
||||||
|
|
||||||
|
def test_state_roundtrip_and_no_tmp_left(monkeypatch, tmp_path):
|
||||||
|
_use_tmp(monkeypatch, tmp_path)
|
||||||
|
assert es.load_state() == {"sources": {}} # нет файла → пустой
|
||||||
|
st = es.load_state()
|
||||||
|
st["sources"]["fgis"] = {"active_period": 426}
|
||||||
|
es.save_state(st)
|
||||||
|
assert es.load_state()["sources"]["fgis"]["active_period"] == 426
|
||||||
|
# атомарность: временных .tmp не осталось
|
||||||
|
assert not list(tmp_path.glob("*.tmp"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_broken_state_returns_empty_not_crash(monkeypatch, tmp_path):
|
||||||
|
_use_tmp(monkeypatch, tmp_path)
|
||||||
|
(tmp_path / "state.json").write_text("{битый json", encoding="utf-8")
|
||||||
|
assert es.load_state() == {"sources": {}} # не падаем; битый файл цел
|
||||||
|
assert (tmp_path / "state.json").read_text(encoding="utf-8").startswith("{битый")
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_snapshot_first_time(monkeypatch, tmp_path):
|
||||||
|
_use_tmp(monkeypatch, tmp_path)
|
||||||
|
src = tmp_path / "in.xlsx"; src.write_bytes(b"AAA")
|
||||||
|
dest = tmp_path / "snap"
|
||||||
|
meta = es.register_snapshot(dest, src, source="fgis", key="split/77/426",
|
||||||
|
url="http://x", params={"periodId": 426}, http_status=200)
|
||||||
|
assert (dest / "in.xlsx").read_bytes() == b"AAA"
|
||||||
|
assert meta["rev"] == 1 and meta["reuploaded"] is False
|
||||||
|
assert meta["sha256"] == es.sha256_file(dest / "in.xlsx")
|
||||||
|
assert json.loads((dest / "meta.json").read_text())["params"]["periodId"] == 426
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_same_content_is_noop(monkeypatch, tmp_path):
|
||||||
|
_use_tmp(monkeypatch, tmp_path)
|
||||||
|
src = tmp_path / "in.xlsx"; src.write_bytes(b"AAA")
|
||||||
|
dest = tmp_path / "snap"
|
||||||
|
es.register_snapshot(dest, src, source="fgis", key="k")
|
||||||
|
meta2 = es.register_snapshot(dest, src, source="fgis", key="k")
|
||||||
|
assert meta2["rev"] == 1 and meta2["reuploaded"] is False # тот же sha → не новая ревизия
|
||||||
|
assert not list(dest.glob("rev-*")) # ревизий не создано
|
||||||
|
|
||||||
|
|
||||||
|
def test_reupload_creates_revision_old_untouched(monkeypatch, tmp_path):
|
||||||
|
"""Перезалив задним числом: старая ревизия цела, новая — current с rev=2."""
|
||||||
|
_use_tmp(monkeypatch, tmp_path)
|
||||||
|
dest = tmp_path / "snap"
|
||||||
|
a = tmp_path / "a.xlsx"; a.write_bytes(b"VERSION-A")
|
||||||
|
es.register_snapshot(dest, a, source="fgis", key="k")
|
||||||
|
b = tmp_path / "a.xlsx"; b.write_bytes(b"VERSION-B-REUPLOADED") # то же имя, другой контент
|
||||||
|
meta = es.register_snapshot(dest, b, source="fgis", key="k")
|
||||||
|
# current — новый
|
||||||
|
assert (dest / "a.xlsx").read_bytes() == b"VERSION-B-REUPLOADED"
|
||||||
|
assert meta["rev"] == 2 and meta["reuploaded"] is True
|
||||||
|
# старая ревизия существует и НЕ ТРОНУТА
|
||||||
|
rev_dirs = list(dest.glob("rev-1_*"))
|
||||||
|
assert len(rev_dirs) == 1
|
||||||
|
assert (rev_dirs[0] / "a.xlsx").read_bytes() == b"VERSION-A"
|
||||||
|
assert json.loads((rev_dirs[0] / "meta.json").read_text())["rev"] == 1
|
||||||
Reference in New Issue
Block a user