Files
SnapOtter/packages/ai/python/tests/test_offline_guard.py
T
SnapOtterandGitHub d10d0f544f fix: release QA hardening across processing, media, security, and CI gates (#649)
A release-readiness QA pass over the whole product. The commits split into
defects a user would hit and gates that were reporting green while measuring
nothing.

## Fixes that change behaviour

Rate limiting was bypassable on every install: TRUST_PROXY defaulted to true, so
request.ip came from a client-set header and a forged X-Forwarded-For got past
the login limiter. The default is now a private-network trust list.

A transient Postgres outage stranded in-flight jobs, leaving finished output on
disk with no row pointing at it. A reconciler now resolves those rows and adopts
the bytes rather than dropping the work.

A Redis connection that moved to a new address wedged every read-blocked
consumer, so completions stopped signalling while health still answered 200.
Socket timeouts plus subscriber pings recover it.

Installing more than one AI bundle left the shared venv multi-versioned and
silently broke three tools. The installer now reconciles distributions to one
version each.

Converting an image to JXL at quality 1 through 4 returned a 500, because
libjxl 0.7 rejects the distance those values compute. The quality is floored at
what the encoder honours. A missing ffmpeg was also reported to the user as a
corrupt upload; it now says the engine is unavailable.

RAW uploads reached an unpatched LibRaw on arm64, so it is built from source at
0.22.2, and the release scan was split so it can fail on an unfixed critical
instead of hiding it behind ignore-unfixed.

## Gates that could not fail

Two mutation lanes ran zero mutants because Stryker crawled the gitignored docs
build; coverage discarded its whole report on any failing test; the lint gate
skipped root tests, scripts, and two workspaces; and several generated matrices
counted a host missing ffmpeg as a passing tool. Each now measures what it
claims.

Full evidence and the outstanding release items are tracked locally and are not
part of this branch.
2026-07-27 15:37:30 +08:00

145 lines
5.4 KiB
Python

"""Contract tests for offline_guard: the strict-offline download gate and the
best-effort bundle-weight symlink helpers. Pure (os + filesystem), no models,
so this runs on any Python the sidecar supports."""
import os
import sys
import pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import offline_guard # noqa: E402
# --- downloads_allowed ------------------------------------------------------
def test_downloads_blocked_by_default(monkeypatch):
monkeypatch.delenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", raising=False)
assert offline_guard.downloads_allowed() is False
@pytest.mark.parametrize("value", ["0", "false", "FALSE", "False", "yes", "anything"])
def test_downloads_blocked_without_explicit_opt_in(monkeypatch, value):
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", value)
assert offline_guard.downloads_allowed() is False
@pytest.mark.parametrize("value", ["1", "true", "TRUE", "True"])
def test_downloads_allowed_for_explicit_opt_in(monkeypatch, value):
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", value)
assert offline_guard.downloads_allowed() is True
# --- ensure_download_allowed ------------------------------------------------
def test_ensure_noop_when_explicitly_allowed(monkeypatch):
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", "1")
assert offline_guard.ensure_download_allowed("thing") is None
def test_ensure_raises_actionable_error_by_default(monkeypatch):
monkeypatch.delenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", raising=False)
with pytest.raises(RuntimeError) as exc:
offline_guard.ensure_download_allowed("MyModel weight")
assert "SNAPOTTER_ALLOW_MODEL_DOWNLOAD=1" in str(exc.value)
def test_ensure_raises_actionable_error_when_blocked(monkeypatch):
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", "0")
with pytest.raises(RuntimeError) as exc:
offline_guard.ensure_download_allowed("MyModel weight")
msg = str(exc.value)
assert "MyModel weight" in msg
assert "SNAPOTTER_ALLOW_MODEL_DOWNLOAD" in msg
# --- link_bundled_weight ----------------------------------------------------
def test_link_already_present_returns_true_without_symlink(tmp_path):
link = tmp_path / "present.pth"
link.write_text("x")
target = tmp_path / "target.pth" # intentionally absent
assert offline_guard.link_bundled_weight(str(link), str(target)) is True
assert not link.is_symlink() # left untouched
def test_link_target_missing_returns_false(tmp_path):
link = tmp_path / "missing" / "link.pth"
target = tmp_path / "nope.pth" # absent
assert offline_guard.link_bundled_weight(str(link), str(target)) is False
assert not link.exists()
def test_link_creates_symlink_and_parent_dirs(tmp_path):
target = tmp_path / "bundle" / "weight.pth"
target.parent.mkdir()
target.write_text("weights")
link = tmp_path / "nested" / "dir" / "weight.pth"
assert offline_guard.link_bundled_weight(str(link), str(target)) is True
assert link.is_symlink()
assert link.read_text() == "weights" # resolves to the target bytes
def test_link_oserror_returns_false_when_symlink_fails(tmp_path, monkeypatch):
target = tmp_path / "t.pth"
target.write_text("w")
link = tmp_path / "l.pth"
def raise_oserror(*_a, **_k):
raise OSError("read-only fs")
monkeypatch.setattr(offline_guard.os, "symlink", raise_oserror)
# symlink fails and the link never materialised -> False.
assert offline_guard.link_bundled_weight(str(link), str(target)) is False
# --- prepare_gfpgan_helper_weights / prepare_codeformer_weights -------------
def test_prepare_gfpgan_links_present_weights(tmp_path, monkeypatch):
models = tmp_path / "models"
facelib = models / "gfpgan" / "facelib"
facelib.mkdir(parents=True)
for fname in offline_guard.GFPGAN_HELPER_WEIGHTS:
(facelib / fname).write_text("w")
monkeypatch.chdir(tmp_path) # link paths are cwd-relative
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", "0") # would raise on any miss
offline_guard.prepare_gfpgan_helper_weights(str(models)) # must not raise
for fname in offline_guard.GFPGAN_HELPER_WEIGHTS:
assert (tmp_path / "gfpgan" / "weights" / fname).exists()
def test_prepare_gfpgan_raises_offline_when_weight_missing(tmp_path, monkeypatch):
models = tmp_path / "models" # nothing installed
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", "0")
with pytest.raises(RuntimeError):
offline_guard.prepare_gfpgan_helper_weights(str(models))
def test_prepare_codeformer_links_present_weights(tmp_path, monkeypatch):
models = tmp_path / "models"
layout = [
("codeformer", "codeformer.pth"),
("gfpgan", "facelib", "detection_Resnet50_Final.pth"),
("gfpgan", "facelib", "parsing_parsenet.pth"),
("realesrgan", "RealESRGAN_x2plus.pth"),
]
for parts in layout:
p = models.joinpath(*parts)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("w")
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", "0")
offline_guard.prepare_codeformer_weights(str(models)) # must not raise
def test_prepare_codeformer_raises_offline_when_missing(tmp_path, monkeypatch):
models = tmp_path / "models"
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", "0")
with pytest.raises(RuntimeError):
offline_guard.prepare_codeformer_weights(str(models))