|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | 5 | import os |
| 6 | +import sys |
6 | 7 | import types |
7 | 8 | from unittest.mock import patch |
8 | 9 |
|
@@ -188,3 +189,35 @@ def test_hf_tracker_drain_returns_and_clears_buffer(monkeypatch): |
188 | 189 | assert result[0]["repo_id"] == "test/model" |
189 | 190 | # Buffer should be cleared |
190 | 191 | assert tracker.drain() == [] |
| 192 | + |
| 193 | + |
| 194 | +class _LazyModule(types.ModuleType): |
| 195 | + """Imports on attribute access, like transformers' lazy modules.""" |
| 196 | + |
| 197 | + def __init__(self, name: str) -> None: |
| 198 | + super().__init__(name) |
| 199 | + self.lookups: list[str] = [] |
| 200 | + |
| 201 | + def __getattr__(self, name: str): |
| 202 | + self.lookups.append(name) |
| 203 | + raise ModuleNotFoundError("No module named 'torchvision'") |
| 204 | + |
| 205 | + |
| 206 | +def test_patch_symbol_references_skips_lazy_attribute_lookup(monkeypatch): |
| 207 | + def original(): |
| 208 | + pass |
| 209 | + |
| 210 | + def replacement(): |
| 211 | + pass |
| 212 | + |
| 213 | + eager = types.ModuleType("eager_mod") |
| 214 | + eager.hf_hub_download = original |
| 215 | + lazy = _LazyModule("lazy_mod") |
| 216 | + monkeypatch.setitem(sys.modules, "eager_mod", eager) |
| 217 | + monkeypatch.setitem(sys.modules, "lazy_mod", lazy) |
| 218 | + |
| 219 | + count = hf_mod._patch_symbol_references("hf_hub_download", original, replacement) |
| 220 | + |
| 221 | + assert count >= 1 |
| 222 | + assert eager.hf_hub_download is replacement |
| 223 | + assert lazy.lookups == [] |
0 commit comments