Fable нашёл (воспроизвёл запуском) потерю данных: потеря meta.json → тихое уничтожение старого архива (rev дефолтился в 1). Исправлено: register_snapshot crash-safe (staging→ архив в УНИКАЛЬНУЮ ревизию из ФС→атомарная подмена→meta), реконструкция meta при потере, flock (ext_lock/update_state), fsync каталога, абсолютный ext_dir (cron-мина), уникальный staging в fetch_file (гонка). Срез 1.1: fgis_client (alive/subjects/zones/periods/latest, валидация формы) на РЕАЛЬНЫХ фикстурах с ФГИС. 21 тест.
77 lines
3.0 KiB
Python
77 lines
3.0 KiB
Python
"""Срез 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 list(tmp_path.glob("f.xlsx.part*")) # staging (в т.ч. .part.<pid>) убран
|
|
|
|
|
|
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
|