Spaces:
Running
Running
File size: 5,686 Bytes
7f84efa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | """Linux desktop targets: AppImage + Arch PKGBUILD (Neutralinojs Hosted Wrapper)."""
import io
import json
import os
import shutil
import subprocess
import tarfile
from pathlib import Path
import pytest
from backend.app.converters.base import BuildContext
from backend.app.converters.desktop import common as dc
SAMPLE = {
"repo_id": "gradio/hello_world",
"owner": "gradio",
"name": "hello_world",
"title": "Hello World",
"short_description": "demo",
"sdk": "gradio",
"embed_url": "https://gradio-hello-world.hf.space",
"space_url": "https://huggingface.co/spaces/gradio/hello_world",
}
def _tools_dir() -> Path | None:
for c in (os.environ.get("SPACEFORGE_TOOLS"), "/opt/spaceforge-tools", "/workspace/sf-tools"):
if c and (Path(c) / "neutralino" / dc.NEUTRALINO_BIN_NAME).is_file():
return Path(c)
return None
@pytest.fixture
def fake_neutralino(tmp_path, monkeypatch):
b = tmp_path / "fake-neutralino"
b.write_bytes(b"\x7fELF fake neutralino binary for tests")
b.chmod(0o755)
monkeypatch.setenv("SPACEFORGE_NEUTRALINO_BIN", str(b))
return b
def test_pkg_name_sanitized():
assert dc.pkg_name(SAMPLE) == "spaceforge-gradio-hello-world"
assert dc.pkg_name({"owner": "2Btainment", "name": "Repo.Space__X"}) == "spaceforge-2btainment-repo-space-x"
assert dc.pkg_name({"repo_id": "", "name": ""}) == "spaceforge-app"
def test_neutralino_config_points_to_space():
cfg = dc.neutralino_config(SAMPLE)
assert cfg["url"] == "https://gradio-hello-world.hf.space"
assert cfg["enableNativeAPI"] is False and cfg["nativeBlockList"] == ["*"]
assert cfg["applicationId"].startswith("com.spaceforge.")
def test_icon_is_png():
png = dc.icon_png("x/y", size=32)
assert png[:8] == b"\x89PNG\r\n\x1a\n"
def test_desktop_entry_no_injection():
info = dict(SAMPLE, title="Evil\nExec=rm -rf /")
entry = dc.desktop_entry(info, exec_name="p", icon_name="p", wm_class="p")
assert [l for l in entry.splitlines() if l.startswith("Exec=")] == ["Exec=p %U"]
def test_appdir_layout(tmp_path, fake_neutralino):
from backend.app.converters.desktop.linux_appimage import build_appdir
appdir = tmp_path / "x.AppDir"
appdir.mkdir()
meta = build_appdir(SAMPLE, appdir)
pkg = meta["pkg"]
assert (appdir / "AppRun").stat().st_mode & 0o111
assert (appdir / f"{pkg}.desktop").is_file()
assert (appdir / f"{pkg}.png").is_file() and (appdir / ".DirIcon").is_symlink()
cfg = json.loads((appdir / "usr" / "lib" / pkg / "neutralino.config.json").read_text())
assert cfg["url"] == SAMPLE["embed_url"]
readme = (appdir / "README.md").read_text()
assert "webkit2gtk-4.1" in readme and "gtk3" in readme
r = subprocess.run(["bash", "-n", str(appdir / "AppRun")], capture_output=True)
assert r.returncode == 0, r.stderr
@pytest.mark.asyncio
async def test_pkgbuild_tarball(tmp_path, fake_neutralino):
from backend.app.converters.desktop.arch_pkgbuild import ArchPkgbuildConverter
r = await ArchPkgbuildConverter().convert(BuildContext("t", tmp_path, SAMPLE))
assert r.ok and r.artifact and r.artifact.filename == "hello_world-pkgbuild.tar.gz"
pkg = "spaceforge-gradio-hello-world"
with tarfile.open(r.artifact.path) as tf:
names = tf.getnames()
assert f"{pkg}/PKGBUILD" in names and f"{pkg}/README.md" in names
pb = tf.extractfile(f"{pkg}/PKGBUILD").read().decode()
readme = tf.extractfile(f"{pkg}/README.md").read().decode()
tf.extractall(tmp_path / "x", filter="data")
assert f"pkgname={pkg}" in pb
assert "depends=('webkit2gtk-4.1' 'gtk3'" in pb
assert "/opt/$pkgname" in pb and "/usr/bin/$pkgname" in pb and "hicolor" in pb
assert readme.startswith(f"tar xf {pkg}-pkgbuild.tar.gz") or "makepkg -si" in readme
r2 = subprocess.run(["bash", "-n", str(tmp_path / "x" / pkg / "PKGBUILD")], capture_output=True)
assert r2.returncode == 0, r2.stderr
# sha256sums match the bundled sources
import hashlib
import re
srcs = re.findall(r"^ '([^']+)'$", pb.split("sha256sums=(")[0].split("source=(")[1], re.M)
sums = re.findall(r"^ '([0-9a-f]{64})'$", pb.split("sha256sums=(")[1], re.M)
assert len(srcs) == len(sums) > 0
for s, h in zip(srcs, sums):
assert hashlib.sha256((tmp_path / "x" / pkg / s).read_bytes()).hexdigest() == h
@pytest.mark.asyncio
async def test_real_appimage_pack(tmp_path, monkeypatch):
tools = _tools_dir()
if not tools or not shutil.which("file"):
pytest.skip("pinned desktop tools not installed (scripts/fetch_desktop_tools.sh)")
monkeypatch.setenv("SPACEFORGE_TOOLS", str(tools))
monkeypatch.delenv("SPACEFORGE_NEUTRALINO_BIN", raising=False)
import importlib
importlib.reload(dc)
from backend.app.converters.desktop import linux_appimage as la
importlib.reload(la)
r = await la.LinuxAppImageConverter().convert(BuildContext("t", tmp_path, SAMPLE))
assert r.ok and r.artifact and r.artifact.filename == "hello_world-x86_64.AppImage"
head = r.artifact.path.read_bytes()[:16]
assert head[:4] == b"\x7fELF" and head[8:11] == b"AI\x02"
ex = tmp_path / "ex"
ex.mkdir()
p = subprocess.run([str(r.artifact.path), "--appimage-extract"], cwd=ex, capture_output=True, timeout=120)
assert p.returncode == 0, p.stderr
root = ex / "squashfs-root"
assert (root / "AppRun").is_file()
assert (root / "spaceforge-gradio-hello-world.desktop").is_file()
cfg = json.loads((root / "usr/lib/spaceforge-gradio-hello-world/neutralino.config.json").read_text())
assert cfg["url"] == "https://gradio-hello-world.hf.space"
|