|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Unit tests for scripts/prepare_embedding_model.py — the build-time embedding |
| 3 | +model downloader. |
| 4 | +
|
| 5 | +Focus is the mirror-fallback layer added to survive huggingface.co's per-IP |
| 6 | +HTTP 429 throttling of shared CI egress IPs: each file is tried against every |
| 7 | +endpoint in order (huggingface.co -> hf-mirror.com by default), each endpoint |
| 8 | +getting its own bounded backoff retry, and only an all-source failure raises. |
| 9 | +
|
| 10 | +Pure stdlib + mock: no network, no numpy/onnxruntime, so this runs on every |
| 11 | +workstation regardless of the embedding bundle state. |
| 12 | +""" |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import importlib.util |
| 16 | +import io |
| 17 | +import urllib.error |
| 18 | +import urllib.request |
| 19 | +from pathlib import Path |
| 20 | + |
| 21 | +import pytest |
| 22 | + |
| 23 | + |
| 24 | +_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "prepare_embedding_model.py" |
| 25 | + |
| 26 | + |
| 27 | +@pytest.fixture |
| 28 | +def prep(monkeypatch): |
| 29 | + """Load the script as a module and neutralize real backoff sleeps.""" |
| 30 | + spec = importlib.util.spec_from_file_location("prepare_embedding_model", _SCRIPT) |
| 31 | + module = importlib.util.module_from_spec(spec) |
| 32 | + spec.loader.exec_module(module) |
| 33 | + monkeypatch.setattr(module.time, "sleep", lambda *_: None) |
| 34 | + # Default env: tests opt into HF_ENDPOINT(S) explicitly where relevant. |
| 35 | + monkeypatch.delenv("HF_ENDPOINTS", raising=False) |
| 36 | + monkeypatch.delenv("HF_ENDPOINT", raising=False) |
| 37 | + return module |
| 38 | + |
| 39 | + |
| 40 | +class _FakeResp(io.BytesIO): |
| 41 | + status = 200 |
| 42 | + |
| 43 | + def __enter__(self): |
| 44 | + return self |
| 45 | + |
| 46 | + def __exit__(self, *exc): |
| 47 | + self.close() |
| 48 | + |
| 49 | + |
| 50 | +def _http_error(url, code): |
| 51 | + return urllib.error.HTTPError(url, code, "err", {}, None) |
| 52 | + |
| 53 | + |
| 54 | +def _install_urlopen(monkeypatch, prep, behavior, *, record=None): |
| 55 | + """Patch the module's urlopen with a callable mapping url -> bytes | Exception.""" |
| 56 | + |
| 57 | + def fake_urlopen(request, timeout=120): |
| 58 | + url = request.full_url if hasattr(request, "full_url") else request |
| 59 | + if record is not None: |
| 60 | + record.append(url) |
| 61 | + result = behavior(url) |
| 62 | + if isinstance(result, Exception): |
| 63 | + raise result |
| 64 | + return _FakeResp(result) |
| 65 | + |
| 66 | + monkeypatch.setattr(prep.urllib.request, "urlopen", fake_urlopen) |
| 67 | + |
| 68 | + |
| 69 | +# --- endpoint resolution --------------------------------------------------- |
| 70 | + |
| 71 | +def test_endpoints_default(prep): |
| 72 | + assert prep._endpoints() == ["https://huggingface.co", "https://hf-mirror.com"] |
| 73 | + |
| 74 | + |
| 75 | +def test_hf_endpoint_pins_single_mirror(prep, monkeypatch): |
| 76 | + monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com") |
| 77 | + assert prep._endpoints() == ["https://hf-mirror.com"] |
| 78 | + |
| 79 | + |
| 80 | +def test_hf_endpoints_list_takes_precedence_and_is_cleaned(prep, monkeypatch): |
| 81 | + monkeypatch.setenv("HF_ENDPOINT", "https://ignored.example") |
| 82 | + monkeypatch.setenv("HF_ENDPOINTS", "https://a.example/ , https://b.example ,, ") |
| 83 | + assert prep._endpoints() == ["https://a.example", "https://b.example"] |
| 84 | + |
| 85 | + |
| 86 | +# --- download fallback ----------------------------------------------------- |
| 87 | + |
| 88 | +def test_falls_back_to_mirror_on_persistent_429(prep, monkeypatch, tmp_path): |
| 89 | + def behavior(url): |
| 90 | + if "huggingface.co" in url: |
| 91 | + return _http_error(url, 429) |
| 92 | + return b"FROM-MIRROR" |
| 93 | + |
| 94 | + _install_urlopen(monkeypatch, prep, behavior) |
| 95 | + dest = tmp_path / "tokenizer.json" |
| 96 | + prep._download( |
| 97 | + "tokenizer.json", dest, repo="r/m", revision="abc", |
| 98 | + endpoints=["https://huggingface.co", "https://hf-mirror.com"], force=False, |
| 99 | + ) |
| 100 | + assert dest.read_bytes() == b"FROM-MIRROR" |
| 101 | + |
| 102 | + |
| 103 | +def test_non_retryable_404_on_first_source_still_falls_through(prep, monkeypatch, tmp_path): |
| 104 | + def behavior(url): |
| 105 | + if "huggingface.co" in url: |
| 106 | + return _http_error(url, 404) |
| 107 | + return b"OK2" |
| 108 | + |
| 109 | + _install_urlopen(monkeypatch, prep, behavior) |
| 110 | + dest = tmp_path / "x" |
| 111 | + prep._download( |
| 112 | + "x", dest, repo="r/m", revision="abc", |
| 113 | + endpoints=["https://huggingface.co", "https://hf-mirror.com"], force=False, |
| 114 | + ) |
| 115 | + assert dest.read_bytes() == b"OK2" |
| 116 | + |
| 117 | + |
| 118 | +def test_all_sources_failing_raises_listing_every_source(prep, monkeypatch, tmp_path): |
| 119 | + _install_urlopen(monkeypatch, prep, lambda url: _http_error(url, 429)) |
| 120 | + with pytest.raises(RuntimeError) as excinfo: |
| 121 | + prep._download( |
| 122 | + "f.bin", tmp_path / "f.bin", repo="r/m", revision="abc", |
| 123 | + endpoints=["https://huggingface.co", "https://hf-mirror.com"], force=False, |
| 124 | + ) |
| 125 | + message = str(excinfo.value) |
| 126 | + assert "all 2 source(s)" in message |
| 127 | + assert "huggingface.co" in message and "hf-mirror.com" in message |
| 128 | + |
| 129 | + |
| 130 | +def test_primary_success_does_not_contact_mirror(prep, monkeypatch, tmp_path): |
| 131 | + seen: list[str] = [] |
| 132 | + _install_urlopen(monkeypatch, prep, lambda url: b"PRIMARY", record=seen) |
| 133 | + dest = tmp_path / "x" |
| 134 | + prep._download( |
| 135 | + "x", dest, repo="r/m", revision="abc", |
| 136 | + endpoints=["https://huggingface.co", "https://hf-mirror.com"], force=False, |
| 137 | + ) |
| 138 | + assert dest.read_bytes() == b"PRIMARY" |
| 139 | + assert len(seen) == 1 and "huggingface.co" in seen[0] |
| 140 | + |
| 141 | + |
| 142 | +def test_existing_nonempty_file_is_kept_without_any_request(prep, monkeypatch, tmp_path): |
| 143 | + dest = tmp_path / "x" |
| 144 | + dest.write_bytes(b"already-here") |
| 145 | + |
| 146 | + def explode(url): |
| 147 | + raise AssertionError("should not hit the network when file already exists") |
| 148 | + |
| 149 | + _install_urlopen(monkeypatch, prep, explode) |
| 150 | + prep._download( |
| 151 | + "x", dest, repo="r/m", revision="abc", |
| 152 | + endpoints=["https://huggingface.co", "https://hf-mirror.com"], force=False, |
| 153 | + ) |
| 154 | + assert dest.read_bytes() == b"already-here" |
| 155 | + |
| 156 | + |
| 157 | +def test_sends_stable_user_agent(prep, monkeypatch, tmp_path): |
| 158 | + captured: dict[str, str] = {} |
| 159 | + |
| 160 | + def fake_urlopen(request, timeout=120): |
| 161 | + captured["ua"] = request.get_header("User-agent") |
| 162 | + return _FakeResp(b"data") |
| 163 | + |
| 164 | + monkeypatch.setattr(prep.urllib.request, "urlopen", fake_urlopen) |
| 165 | + prep._download_one("https://huggingface.co/r/m/resolve/abc/x", tmp_path / "x") |
| 166 | + assert captured["ua"] == prep._USER_AGENT |
0 commit comments