Spaces:
Running on Zero
Running on Zero
Download tests/test_space.py from loose-bits/u-space: direct link, hf CLI and curl.
- Browser
- Download file 7.31 kB
-
https://huggingface.co/spaces/loose-bits/u-space/resolve/main/tests/test_space.py
- Command line
-
hf download hf://spaces/loose-bits/u-space/tests/test_space.py
-
curl -L -o test_space.py https://huggingface.co/spaces/loose-bits/u-space/resolve/main/tests/test_space.py
7.31 kB
| """The Hugging Face Space's wiring: the knobs, the shipped cache, and the build pins. | |
| Every one of these is a thing that fails only on the Hub, minutes into a build or on the first | |
| visitor, where the feedback loop is slow and the error is someone else's log. | |
| """ | |
| import importlib | |
| import os | |
| import re | |
| from pathlib import Path | |
| import numpy as np | |
| import pytest | |
| from ulens import axes, basis | |
| ROOT = Path(__file__).resolve().parents[1] | |
| CACHE = ROOT / "space" / "cache" | |
| # ---------------------------------------------------------------------- the shipped cache | |
| def test_the_stack_ships_so_startup_needs_no_lens(): | |
| """Without it the first visitor waits on a 388 MB checkpoint and a basis build.""" | |
| st = axes.load_stack(CACHE / "stacks" / "qwen3.5-4b-v1.npz") | |
| assert st.U.shape[1:] == (2560, 4) | |
| assert len(st.blocks) == 31 | |
| assert st.meta.get("terms_version") == "v1", "field() rebuilds when the version disagrees" | |
| def test_both_single_block_bases_ship(block): | |
| """20 is where the state is read, 23 where the axes decode; both are asked for by name.""" | |
| cone = basis.load(CACHE / "bases" / f"qwen3.5-4b-b{block}-v1.npz") | |
| assert cone.block == block | |
| assert cone.names[0] == "ambiguity" | |
| def test_the_vocabulary_norms_ship_for_the_decode_block(): | |
| n = np.load(CACHE / "vocab_norms" / "qwen3.5-4b-b23.npy") | |
| assert n.ndim == 1 and n.dtype == np.float32 and np.all(n > 0) | |
| def test_the_cache_layout_is_the_one_the_resolvers_look_in(monkeypatch): | |
| """`ULENS_CACHE` is the only thing pointing the package at these files.""" | |
| monkeypatch.setenv("ULENS_CACHE", str(CACHE)) | |
| assert basis.stack_path("qwen3.5-4b").exists() | |
| assert basis.cache_path("qwen3.5-4b", 20).exists() | |
| assert basis.cache_path("qwen3.5-4b", 23).exists() | |
| # ---------------------------------------------------------------------- the knobs | |
| def test_the_budget_and_thinking_knobs(monkeypatch, env, tokens, default, think): | |
| """The Space pays for a run out of the visitor's quota, so it ships smaller defaults.""" | |
| for k in ("ULENS_APP_MAX_TOKENS", "ULENS_APP_THINK"): | |
| monkeypatch.delenv(k, raising=False) | |
| for k, v in env.items(): | |
| monkeypatch.setenv(k, v) | |
| monkeypatch.setenv("ULENS_APP_LOAD_MODEL", "0") | |
| app = importlib.reload(importlib.import_module("ulens.app")) | |
| try: | |
| assert (app.MAX_TOKENS, app.BUDGET_DEFAULT, app.THINK_DEFAULT) == (tokens, default, think) | |
| finally: | |
| for k in ("ULENS_APP_MAX_TOKENS", "ULENS_APP_THINK"): | |
| os.environ.pop(k, None) | |
| importlib.reload(app) | |
| # ---------------------------------------------------------------------- the build | |
| def test_torch_is_pinned_below_what_zerogpu_refuses(): | |
| """ZeroGPU supports 2.8.0 through 2.13.0. The package asks only for >=2.0, so pip would | |
| otherwise resolve to the newest release and the Space would never get a GPU.""" | |
| req = (ROOT / "requirements.txt").read_text() | |
| m = re.search(r"^torch==(\d+)\.(\d+)\.", req, re.M) | |
| assert m, "requirements.txt must pin torch exactly" | |
| assert (int(m.group(1)), int(m.group(2))) <= (2, 13) | |
| def test_the_space_front_matter_names_the_entry_point_that_exists(): | |
| head = (ROOT / "README.md").read_text().split("---")[1] | |
| assert re.search(r"^sdk:\s*gradio\s*$", head, re.M), "ZeroGPU is Gradio-only" | |
| app_file = re.search(r"^app_file:\s*(\S+)\s*$", head, re.M) | |
| assert app_file and (ROOT / app_file.group(1)).exists() | |
| def test_the_entry_point_sets_the_cache_before_importing_the_package(): | |
| """Import order is load-bearing: `basis.cache_dir()` reads the variable at call time, but | |
| anything that resolves at import would miss a value set afterwards.""" | |
| src = (ROOT / "space.py").read_text() | |
| assert src.index('os.environ.setdefault("ULENS_CACHE"') < src.index("from ulens") | |
| def test_the_entry_point_puts_src_on_the_path_before_importing_it(): | |
| """The package is imported from `src/`, not installed — see requirements.txt.""" | |
| src = (ROOT / "space.py").read_text() | |
| assert 'sys.path.insert(0, str(HERE / "src"))' in src | |
| assert src.index("sys.path.insert") < src.index("from ulens") | |
| def test_requirements_does_not_install_the_package_from_a_path(): | |
| """The Hub mounts requirements.txt alone at /tmp and runs pip from a directory that is not | |
| the repo, so `.` and `-e .` have no pyproject.toml to find: the first build died on | |
| `Directory '.[app]' is not installable`.""" | |
| for line in _req_lines(): | |
| assert not line.startswith((".", "-e", "./")), line | |
| def _req_lines() -> list[str]: | |
| return [ln.strip() for ln in (ROOT / "requirements.txt").read_text().splitlines() | |
| if ln.strip() and not ln.lstrip().startswith("#")] | |
| def test_requirements_covers_every_dependency_of_the_app_extra(): | |
| """requirements.txt restates what `pip install ulens[app]` would have pulled in, so it can | |
| drift from pyproject.toml. gradio is the one exception: the Hub installs the version named | |
| by `sdk_version` in the README and a second pin here would fight it.""" | |
| import tomllib | |
| pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text()) | |
| proj = pyproject["project"] | |
| extras = proj["optional-dependencies"] | |
| def closure(name: str) -> set[str]: | |
| """Package names `ulens[<name>]` resolves to, following `ulens[...]` self-references.""" | |
| out = set() | |
| for dep in extras[name]: | |
| if dep.startswith("ulens["): | |
| out |= closure(dep.split("[")[1].rstrip("]")) | |
| else: | |
| out.add(_name(dep)) | |
| return out | |
| wanted = closure("app") | {_name(d) for d in proj["dependencies"]} | |
| have = {_name(ln) for ln in _req_lines()} | |
| missing = wanted - have - {"gradio"} | |
| assert not missing, f"requirements.txt is missing {sorted(missing)}" | |
| def _name(dep: str) -> str: | |
| """The distribution name of a requirement line, normalised.""" | |
| return re.split(r"[\[<>=!~ ;]", dep, maxsplit=1)[0].strip().lower().replace("_", "-") | |
| def test_the_link_bar_clears_the_badge_the_hub_pins_over_the_page(monkeypatch): | |
| """A page served from hf.space gets an owner/likes badge fixed at the top right, ~280px | |
| wide, which covered "Read the blog" and "See the code" entirely on the first deploy.""" | |
| monkeypatch.setenv("SPACE_ID", "loose-bits/u-space") | |
| monkeypatch.setenv("ULENS_APP_LOAD_MODEL", "0") | |
| app = importlib.reload(importlib.import_module("ulens.app")) | |
| try: | |
| assert app.ON_SPACE | |
| assert "ul-hosted" in app.intro_html() | |
| assert ".ul-hosted .ul-links { margin-right:" in app.CSS | |
| finally: | |
| os.environ.pop("SPACE_ID", None) | |
| importlib.reload(app) | |
| def test_the_link_bar_is_unchanged_off_the_hub(monkeypatch): | |
| monkeypatch.delenv("SPACE_ID", raising=False) | |
| monkeypatch.setenv("ULENS_APP_LOAD_MODEL", "0") | |
| app = importlib.reload(importlib.import_module("ulens.app")) | |
| assert not app.ON_SPACE | |
| assert "ul-hosted" not in app.intro_html() | |