"""Round 129: the Mac app's packaging, offline. Nothing here needs a Mac or the network: release checks are fed canned GitHub answers, the bundled-tool fetcher is fed local archives, and the icon/Info.plist builders are pure. What only a Mac can check (PyInstaller, codesign, hdiutil) runs in .github/workflows/mac.yml. """ import hashlib import importlib.util import io import json import plistlib import re import subprocess import sys import tarfile import zipfile from pathlib import Path from unittest.mock import MagicMock import pytest from lintunes import __version__, release_info ROOT = Path(__file__).resolve().parent.parent MAC = ROOT / "packaging" / "mac" def _load(name, path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module # ---- versions and the release answer ---- @pytest.mark.parametrize("text, expected", [ ("v0.92.0", (0, 92, 0)), ("0.92.0", (0, 92, 0)), ("v1.2", (1, 2, 0)), (" v10.0.3 ", (10, 0, 3)), ("v1.2.3-beta", None), ("latest", None), ("", None), (None, None), (123, None), ]) def test_parse_version(text, expected): assert release_info.parse_version(text) == expected def test_versions_compare_as_numbers_not_strings(): assert release_info.is_newer("v0.100.0", "0.99.0") assert release_info.is_newer("v1.0.0", "0.999.999") assert release_info.is_newer("0.92.1", "0.92.0") assert not release_info.is_newer("v0.92.0", "0.92.0") assert not release_info.is_newer("v0.9.0", "0.10.0") assert not release_info.is_newer("nonsense", "0.1.0") assert not release_info.is_newer("v1.0.0", "garbage") GOOD = { "tag_name": "v0.95.0", "html_url": "https://github.com/someone/lintunes/releases/tag/v0.95.0", "draft": False, "prerelease": False, "assets": [{"name": "LinTunes-0.95.0-AppleSilicon.dmg"}], } def test_parse_latest_release(): assert release_info.parse_latest_release(GOOD) == ( "0.95.0", "https://github.com/someone/lintunes/releases/tag/v0.95.0") @pytest.mark.parametrize("change", [ {"draft": True}, {"prerelease": True}, {"tag_name": "nightly"}, {"tag_name": None}, {"html_url": "https://evil.example/releases/v0.95.0"}, {"html_url": None}, ]) def test_unusable_releases_are_ignored(change): assert release_info.parse_latest_release({**GOOD, **change}) is None @pytest.mark.parametrize("payload", [None, [], "text", {"message": "Not Found"}]) def test_garbage_answers_are_ignored(payload): assert release_info.parse_latest_release(payload) is None def test_no_repo_means_no_checks(): assert release_info.latest_release_url("") is None assert release_info.releases_page("") is None assert release_info.latest_release_url("not a repo") is None assert release_info.latest_release_url("a/b/c") is None assert (release_info.latest_release_url("owner/name") == "https://api.github.com/repos/owner/name/releases/latest") def test_the_shipped_constants(): # Empty until the GitHub mirror exists; anything else must be owner/name. assert (release_info.GITHUB_REPO == "" or release_info.valid_repo(release_info.GITHUB_REPO)) assert release_info.BUNDLE_ID == "org.lintunes.LinTunes" assert "@" not in release_info.USER_AGENT # ---- the updater's release path ---- def _response(status, payload=None, raises=None): r = MagicMock() r.status_code = status if raises: r.json.side_effect = raises else: r.json.return_value = payload return r def test_fetch_latest_release(): from lintunes import updater calls = [] def get(url, timeout, headers): calls.append((url, headers)) return _response(200, GOOD) assert updater.fetch_latest_release("o/n", get=get) == ( "0.95.0", GOOD["html_url"]) url, headers = calls[0] assert url == "https://api.github.com/repos/o/n/releases/latest" assert headers["User-Agent"] == release_info.USER_AGENT assert "Authorization" not in headers @pytest.mark.parametrize("get", [ lambda *a, **k: _response(404, {"message": "Not Found"}), lambda *a, **k: _response(403, {"message": "rate limit"}), lambda *a, **k: _response(200, raises=ValueError("not json")), lambda *a, **k: (_ for _ in ()).throw(OSError("offline")), ]) def test_fetch_is_quiet_on_failure(get): from lintunes import updater assert updater.fetch_latest_release("o/n", get=get) is None def test_fetch_never_asks_without_a_repo(): from lintunes import updater get = MagicMock() assert updater.fetch_latest_release("", get=get) is None get.assert_not_called() def test_release_mode_never_runs_git(qapp, monkeypatch): from lintunes import updater run = MagicMock(side_effect=AssertionError("git ran")) monkeypatch.setattr(updater.subprocess, "run", run) u = updater.Updater(release_mode=True) assert u.short_hash() is None u.update_async() # a no-op: the button opens a page monkeypatch.setattr(release_info, "GITHUB_REPO", "") assert not u.enabled u.start_checking() # no repo: no timers, no checks assert u._timer is None run.assert_not_called() def test_release_mode_reports_only_a_newer_release(qapp, monkeypatch): from lintunes import updater u = updater.Updater(release_mode=True) seen = [] u.release_available.connect(lambda v, page: seen.append((v, page))) monkeypatch.setattr(updater, "fetch_latest_release", lambda: ("999.0.0", GOOD["html_url"])) u._check_release() assert seen == [("999.0.0", GOOD["html_url"])] monkeypatch.setattr(updater, "fetch_latest_release", lambda: (__version__, GOOD["html_url"])) u._check_release() monkeypatch.setattr(updater, "fetch_latest_release", lambda: None) u._check_release() assert len(seen) == 1 assert not u._busy def test_a_checkout_keeps_the_git_path(qapp): from lintunes import paths, updater assert not paths.FROZEN assert updater.Updater().release_mode is False def test_version_button_opens_the_release_page(qapp, monkeypatch): from lintunes import updater from lintunes.gui import version_button u = updater.Updater(release_mode=True) button = version_button.VersionButton(u) opened = [] monkeypatch.setattr(version_button.QDesktopServices, "openUrl", lambda url: opened.append(url.toString()) or True) confirm = MagicMock(return_value=True) monkeypatch.setattr(button, "_confirm", confirm) monkeypatch.setattr(u, "update_async", MagicMock()) button.click() # nothing ready: nothing happens assert opened == [] u.release_available.emit("999.0.0", GOOD["html_url"]) assert button.text() == f"v{__version__}*" assert "999.0.0" in button.toolTip() button.click() assert opened == [GOOD["html_url"]] confirm.assert_not_called() # no "pull and restart?" question u.update_async.assert_not_called() # ---- bundled tools ---- def test_tools_manifest_is_pinned(): fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py") tools = fetch.load_manifest() assert set(tools) == {"ffmpeg", "ffprobe", "fpcalc"} for name, tool in tools.items(): assert tool["version"] and tool["license"] assert set(tool["arch"]) == set(fetch.ARCHES) for entry in tool["arch"].values(): assert entry["url"].startswith("https://") assert re.fullmatch(r"[0-9a-f]{64}", entry["sha256"]) assert entry["member"].endswith(name) # The two architectures are different files. for tool in tools.values(): assert tool["arch"]["arm64"]["sha256"] != tool["arch"]["x86_64"]["sha256"] def _zip_with(member, data): buf = io.BytesIO() with zipfile.ZipFile(buf, "w") as z: z.writestr(member, data) return buf.getvalue() def _tar_with(member, data): buf = io.BytesIO() with tarfile.open(fileobj=buf, mode="w:gz") as t: info = tarfile.TarInfo(member) info.size = len(data) t.addfile(info, io.BytesIO(data)) return buf.getvalue() def test_fetch_verifies_then_extracts_only_the_member(tmp_path, monkeypatch): fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py") archives = { "https://example.org/ff.zip": _zip_with("ffmpeg", b"FFMPEG"), "https://example.org/fp.tar.gz": _tar_with("dir/fpcalc", b"FPCALC"), } downloads = [] def download(url, dest): downloads.append(url) dest.write_bytes(archives[url]) monkeypatch.setattr(fetch, "download", download) manifest = { "ffmpeg": {"version": "1", "arch": {"arm64": { "url": "https://example.org/ff.zip", "member": "ffmpeg", "sha256": hashlib.sha256(archives["https://example.org/ff.zip"]).hexdigest()}}}, "fpcalc": {"version": "1", "arch": {"arm64": { "url": "https://example.org/fp.tar.gz", "member": "dir/fpcalc", "sha256": hashlib.sha256(archives["https://example.org/fp.tar.gz"]).hexdigest()}}}, } out = tmp_path / "tools" made = fetch.fetch("arm64", out, manifest) assert [p.name for p in made] == ["ffmpeg", "fpcalc"] assert (out / "ffmpeg").read_bytes() == b"FFMPEG" assert (out / "fpcalc").read_bytes() == b"FPCALC" assert (out / "fpcalc").stat().st_mode & 0o111 assert not (out / "dir").exists() # A second run uses the verified cache. fetch.fetch("arm64", out, manifest) assert len(downloads) == 2 def test_fetch_refuses_a_wrong_hash(tmp_path, monkeypatch): fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py") monkeypatch.setattr(fetch, "download", lambda url, dest: dest.write_bytes(_zip_with("ffmpeg", b"EVIL"))) manifest = {"ffmpeg": {"version": "1", "arch": {"arm64": { "url": "https://example.org/ff.zip", "member": "ffmpeg", "sha256": "0" * 64}}}} with pytest.raises(fetch.VerifyError): fetch.fetch("arm64", tmp_path / "tools", manifest) assert not (tmp_path / "tools" / "ffmpeg").exists() def test_fetch_refuses_plain_http(tmp_path): fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py") with pytest.raises(fetch.VerifyError): fetch.download("http://example.org/x.zip", tmp_path / "x") # ---- icon ---- def test_icns_container_round_trips(): pytest.importorskip("PIL") from PIL import Image icons = _load("lintunes_make_icons", ROOT / "scripts" / "make_icons.py") master = icons.mac_master(Image.new("RGB", (64, 64), (10, 200, 30))) assert master.size == (1024, 1024) # The ~10 % margin is transparent; the middle isn't. assert master.getpixel((20, 20))[3] == 0 assert master.getpixel((512, 512))[3] == 255 entries = icons.read_icns(icons.icns_bytes(master)) assert [k for k, _ in entries] == [k for k, _ in icons.ICNS_TYPES] for (kind, size), (_, png) in zip(icons.ICNS_TYPES, entries): assert png[:8] == b"\x89PNG\r\n\x1a\n" assert Image.open(io.BytesIO(png)).size == (size, size) def test_the_committed_icns(): icons = _load("lintunes_make_icons", ROOT / "scripts" / "make_icons.py") \ if importlib.util.find_spec("PIL") else None blob = (MAC / "LinTunes.icns").read_bytes() assert blob[:4] == b"icns" if icons: kinds = {k for k, _ in icons.read_icns(blob)} assert {b"ic10", b"ic09", b"ic07", b"icp4"} <= kinds # ---- Info.plist, spec, signing, workflow ---- def test_info_plist(): plist = _load("lintunes_mac_plist", MAC / "plist.py") info = plist.info_plist() assert info["CFBundleIdentifier"] == release_info.BUNDLE_ID assert info["CFBundleShortVersionString"] == __version__ assert info["NSHighResolutionCapable"] is True assert info["LSMinimumSystemVersion"] == plist.MINIMUM_MACOS assert info["LSApplicationCategoryType"] == "public.app-category.music" assert info["NSLocalNetworkUsageDescription"] for service in ("_googlecast._tcp", "_raop._tcp", "_airplay._tcp"): assert service in info["NSBonjourServices"] doc = info["CFBundleDocumentTypes"][0] assert doc["LSHandlerRank"] == "Alternate" assert "public.mp3" in doc["LSItemContentTypes"] plistlib.dumps(info) # serializable as PyInstaller will def test_the_spec_ships_what_the_app_reads_and_not_the_r1_app(): spec = (MAC / "LinTunes.spec").read_text() for needed in ("tink.wav", "airhorn.mp3", '"templates"', "tables.npz", "_spleeter_run.py", "drag-icon.png", "rthook_certifi.py", "argv_emulation=False", "LinTunes.icns"): assert needed in spec, needed code = "\n".join(line.split("#")[0] for line in spec.splitlines()) assert "andTunes.apk" not in code and "buttons" not in code assert "android" not in code for path in ("launch.py", "rthook_certifi.py", "THIRD-PARTY.md", "licenses/GPL-3.0.txt", "licenses/LGPL-2.1.txt", "licenses/chromaprint-LICENSE.md"): assert (MAC / path).is_file(), path for path in ("lintunes/dj/_spleeter_run.py", "packaging/drag-icon.png", "lintunes/kaleidostrobe/tables.npz", "lintunes/sounds/tink.wav", "lintunes/sounds/airhorn.mp3"): assert (ROOT / path).is_file(), path def test_entitlements_parse(): ent = plistlib.loads((MAC / "entitlements.plist").read_bytes()) assert ent["com.apple.security.cs.allow-unsigned-executable-memory"] is True assert "com.apple.security.app-sandbox" not in ent @pytest.mark.parametrize("script", ["build.sh", "smoke_test.sh"]) def test_shell_scripts_parse(script): subprocess.run(["bash", "-n", str(MAC / script)], check=True) def test_build_pins_pyinstaller_and_refuses_linux(): text = (MAC / "build.sh").read_text() assert re.search(r'^PYINSTALLER_VERSION="\d+\.\d+\.\d+"$', text, re.M) if sys.platform != "darwin": proc = subprocess.run(["bash", str(MAC / "build.sh")], capture_output=True, text=True) assert proc.returncode != 0 and "Mac" in proc.stderr def test_workflow_actions_are_pinned_to_commits(): workflows = list((ROOT / ".github" / "workflows").glob("*.yml")) assert workflows for wf in workflows: text = wf.read_text() for uses in re.findall(r"uses:\s*(\S+)", text): if uses.startswith("./"): continue assert re.fullmatch(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}", uses), uses assert "permissions:" in text def test_workflow_least_privilege(): text = (ROOT / ".github" / "workflows" / "mac.yml").read_text() top = text.split("\njobs:")[0] assert re.search(r"^permissions:\n contents: read$", top, re.M) assert text.count("contents: write") == 1 def test_requirements_match_setup(): reqs = (ROOT / "requirements.txt").read_text() setup = (ROOT / "setup.py").read_text() assert "pyatv" in reqs for pkg in ("pyobjc-framework-Cocoa", "pyobjc-framework-MediaPlayer"): for text in (reqs, setup): line = next(l for l in text.splitlines() if pkg in l) assert 'sys_platform == "darwin"' in line def _origin_host(): """The git host this checkout came from, read at run time so the test itself never names it.""" try: url = subprocess.run(["git", "-C", str(ROOT), "remote", "get-url", "origin"], capture_output=True, text=True, timeout=10).stdout.strip() except Exception: # noqa: BLE001 return None m = re.match(r"^(?:\w+://)?(?:[^@/]+@)?([^/:]+)", url) host = m[1] if m else None return host if host and host != "github.com" else None def test_the_mac_files_never_name_the_private_host(): host = _origin_host() if not host: pytest.skip("no private origin to check against") files = [ROOT / "docs" / d for d in ("mac.md", "mac-release.md", "mac-testing.md")] files += [p for p in MAC.rglob("*") if p.is_file() and p.suffix in (".sh", ".py", ".md", ".json", ".spec", ".plist")] files += list((ROOT / ".github").rglob("*.yml")) files.append(ROOT / "lintunes" / "release_info.py") for path in files: assert host not in path.read_text(), path