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:
@@ -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