Files
smeta-web/tests/test_ext_fetch.py
T
anor 823291424c feat(ext): Фаза 0 конвейера источников — хранилище снапшотов + загрузчик
ext_state: версионированные снапшоты (атомарная запись tmp+os.replace, sha256; перезалив
задним числом → новая ревизия, старая неприкосновенна — тихое затирание запрещено).
ext_sources: декларативный реестр источников (растёт по фазам). ext_fetch: единый httpx-
загрузчик (trust_env для прокси, ретраи+бэкофф, потоковое скачивание в .part, fail-loud
на малом размере/неверном типе). 12 тестов (моки httpx.MockTransport, без новых зависимостей).
2026-07-18 01:16:45 +10:00

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 (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