v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s

This commit is contained in:
2026-11-17 22:41:48 -08:00
parent b78b6c5275
commit f21c31940f
66 changed files with 6047 additions and 164 deletions
+464
View File
@@ -0,0 +1,464 @@
"""Round 129: the macOS port of Cassette, DJ mode's vocal splitters, AirPlay's
helper download and the rest of their machine-local paths.
Every Mac branch keys off ``lintunes.paths.IS_MAC`` (and ``FROZEN``), so
these flip it with monkeypatch. Each Mac test has a Linux twin pinning that
nothing there changed: the same paths, words and commands as before.
"""
import hashlib
import io
import os
import sys
import tarfile
from pathlib import Path
import pytest
from lintunes import paths
@pytest.fixture
def mac(monkeypatch):
monkeypatch.setattr(paths, "IS_MAC", True)
return monkeypatch
@pytest.fixture
def home(tmp_path, monkeypatch):
home = tmp_path / "home"
home.mkdir()
monkeypatch.setenv("HOME", str(home))
for var in ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME",
"XDG_STATE_HOME", "STCONFDIR", "STHOMEDIR"):
monkeypatch.delenv(var, raising=False)
from lintunes import sync_identity
sync_identity.reset_cache()
yield home
sync_identity.reset_cache()
def _syncthing_config(folder: Path, key="k3y", address="127.0.0.1:8384"):
folder.mkdir(parents=True, exist_ok=True)
(folder / "config.xml").write_text(
f'<configuration><device id="ABCDEFG-XYZ" name="Laptop"/>'
f'<gui><address>{address}</address><apikey>{key}</apikey></gui>'
f'</configuration>')
return folder
# ---- Syncthing's config ----
class TestSyncthingConfig:
def test_linux_looks_where_it_always_did(self, home):
from lintunes import sync_identity
assert sync_identity.config_dirs() == (
"$XDG_STATE_HOME/syncthing", "~/.local/state/syncthing",
"~/.config/syncthing", "~/.syncthing")
# A Mac-style folder means nothing on Linux.
_syncthing_config(home / "Library/Application Support/Syncthing")
assert sync_identity._config_dir() is None
def test_mac_finds_application_support(self, home, mac):
from lintunes import sync_identity
from lintunes.cassette import syncthing_api as st
folder = _syncthing_config(home / "Library/Application Support/Syncthing")
assert sync_identity._config_dir() == folder
assert st.read_gui_config() == st.Endpoint("127.0.0.1:8384", "k3y")
assert sync_identity.device_names() == {"ABCDEFG": "Laptop"}
def test_mac_honours_stconfdir_first(self, home, mac, tmp_path):
from lintunes import sync_identity
_syncthing_config(home / "Library/Application Support/Syncthing")
custom = _syncthing_config(tmp_path / "elsewhere", key="other")
mac.setenv("STCONFDIR", str(custom))
assert sync_identity._config_dir() == custom
mac.setenv("STCONFDIR", "") # set to nothing: skipped, not "."
assert sync_identity._config_dir() == (
home / "Library/Application Support/Syncthing")
def test_mac_still_finds_a_unix_style_home(self, home, mac):
from lintunes import sync_identity
folder = _syncthing_config(home / ".config/syncthing")
assert sync_identity._config_dir() == folder
def test_not_running_words(self, mac):
from lintunes.cassette import syncthing_api as st
hint = st.not_running_hint("press Retry")
assert "brew install" in hint and "syncthing.net" in hint
assert hint.startswith("Open the Syncthing app")
assert ", then press Retry." in hint
def test_not_running_words_on_linux_are_the_callers(self):
from lintunes.cassette import syncthing_api as st
assert st.not_running_hint("press Retry") is None
@pytest.mark.parametrize("on_mac", [False, True])
def test_service_status_when_syncthing_is_down(self, qapp, tmp_path,
monkeypatch, on_mac):
from lintunes.cassette import service as svc
from lintunes.cassette import syncthing_api as st
monkeypatch.setattr(paths, "IS_MAC", on_mac)
service = svc.CassetteService.__new__(svc.CassetteService)
svc.QObject.__init__(service)
import threading
service._lock = threading.Lock()
service._api = svc.Status("x", "", "")
service._set_api_down(st.SyncthingError("s", "d", st.NOT_RUNNING))
detail = service._api.hint
if on_mac:
assert "brew install" in detail
else:
assert detail == ("Start Syncthing, then press Retry in Sync "
"Settings ▸ General.")
# ---- the cassette folders ----
class TestCassetteFolders:
def test_root_on_linux_unchanged(self, home, monkeypatch, tmp_path):
from lintunes.cassette import state
monkeypatch.setattr(state, "load_config", lambda: {})
assert state.cassette_root() == home / ".local/share/lintunes/cassette"
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
assert state.cassette_root() == tmp_path / "xdg/lintunes/cassette"
def test_root_on_mac(self, home, mac):
from lintunes.cassette import state
mac.setattr(state, "load_config", lambda: {})
assert state.cassette_root() == (
home / "Library/Application Support/LinTunes/cassette")
mac.setattr(state, "load_config", lambda: {"cassette_root": "~/C"})
assert state.cassette_root() == home / "C"
def test_stignore_on_linux_unchanged(self, tmp_path):
from lintunes.cassette import publish
publish.prepare_out_dir(tmp_path / "out")
assert (tmp_path / "out/.stignore").read_text() == (
"// written by LinTunes\n*.tmp\n*.part\n")
publish.prepare_in_dir(tmp_path / "in")
assert (tmp_path / "in").is_dir()
assert not (tmp_path / "in/.stignore").exists()
def test_stignore_on_mac_keeps_finder_out(self, tmp_path, mac):
from lintunes.cassette import publish
publish.prepare_out_dir(tmp_path / "out")
text = (tmp_path / "out/.stignore").read_text()
assert text.startswith("// written by LinTunes\n*.tmp\n*.part\n")
assert "(?d).DS_Store" in text and "(?d)._*" in text
publish.prepare_in_dir(tmp_path / "in")
assert "(?d).DS_Store" in (tmp_path / "in/.stignore").read_text()
def test_finder_litter_is_never_a_delivery(self, tmp_path):
from lintunes.cassette import delivery
outbox = tmp_path / "outbox"
outbox.mkdir()
(outbox / ".DS_Store").write_bytes(b"x")
(outbox / "._12 ~ song.mp3").write_bytes(b"x")
(outbox / "12 ~ song.mp3").write_bytes(b"x")
assert list(delivery.list_outbox(outbox)) == [12]
def test_mac_hostname_drops_dot_local(self, mac):
from lintunes.cassette import host
mac.setattr(host.socket, "gethostname", lambda: "Travs-MacBook.local")
assert host.hostname() == "Travs-MacBook"
def test_linux_hostname_unchanged(self, monkeypatch):
from lintunes.cassette import host
monkeypatch.setattr(host.socket, "gethostname", lambda: "box.local")
assert host.hostname() == "box.local"
def test_mac_asks_syncthing_by_its_nfc_name(self, tmp_path, mac):
import unicodedata
from lintunes.cassette import service as svc
from lintunes.cassette.state import Friend, in_dir
asked = []
class Client:
def file_info(self, folder, name):
asked.append(name)
return None
service = svc.CassetteService.__new__(svc.CassetteService)
import threading
service._lock = threading.Lock()
service.root = tmp_path
friend = Friend(token="t", device_id="D", name="F", role="inviter",
out_folder="o", in_folder="i", added="")
service._state = type("S", (), {"friends": {"t": friend}})()
service.client = lambda: Client()
nfd = unicodedata.normalize("NFD", "Beyoncé.mp3")
assert service.is_complete("t", in_dir(tmp_path, "t") / nfd)
assert asked == [unicodedata.normalize("NFC", "Beyoncé.mp3")]
# ---- AirPlay's helper ----
class TestCliAirPlay:
@pytest.mark.parametrize("machine, key", [("arm64", "macos-arm64"),
("x86_64", "macos-x86_64")])
def test_mac_builds_are_pinned(self, mac, machine, key):
from lintunes.airplay import cli
mac.setattr(cli.platform, "machine", lambda: machine)
assert cli._arch() == key and cli.supported()
assert cli._asset(key) == f"cliairplay-{key}"
assert len(cli._SHA256[key]) == 64
def test_mac_download_uses_the_mac_asset(self, mac, tmp_path):
from lintunes.airplay import cli
data = b"pretend mac binary"
mac.setenv("XDG_DATA_HOME", str(tmp_path))
mac.setattr(cli.platform, "machine", lambda: "arm64")
mac.setitem(cli._SHA256, "macos-arm64", hashlib.sha256(data).hexdigest())
urls = []
path = cli.ensure_binary(fetch=lambda url: urls.append(url) or data)
assert urls == [cli._RELEASE + "cliairplay-macos-arm64"]
assert path == tmp_path / "lintunes/bin" / f"cliairplay-{cli.VERSION}-macos-arm64"
assert os.access(path, os.X_OK)
def test_linux_binary_dir_unchanged(self, home):
from lintunes.airplay import cli
assert cli.binary_dir() == home / ".local/share/lintunes/bin"
def test_https_context(self, monkeypatch):
import ssl
from lintunes.airplay import cli
assert cli.https_context() is None
monkeypatch.setattr(paths, "IS_MAC", True)
assert isinstance(cli.https_context(), ssl.SSLContext)
# ---- the splitters' venvs ----
def _uv_tarball(target: str, payload=b"#!/bin/sh\necho uv\n") -> bytes:
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
info = tarfile.TarInfo(f"uv-{target}/uv")
info.size = len(payload)
tar.addfile(info, io.BytesIO(payload))
info = tarfile.TarInfo(f"uv-{target}/uvx")
info.size = 1
tar.addfile(info, io.BytesIO(b"x"))
return buf.getvalue()
class TestVenvTool:
def test_linux_checkout_makes_venvs_as_before(self, monkeypatch):
from lintunes.dj import venv_tool
monkeypatch.setattr(paths, "FROZEN", False)
venv = Path("/v")
assert not venv_tool.uses_uv()
assert venv_tool.create_command(venv) == [sys.executable, "-m", "venv", "/v"]
assert venv_tool.install_command(venv, ["a", "b"]) == [
"/v/bin/python", "-m", "pip", "install", "--quiet", "a", "b"]
assert venv_tool.run_env() is None
assert venv_tool.child_env() is None
env = {"X": "1"}
assert venv_tool.child_env(env) is env
cmd, pre = venv_tool.niced(["x"], 5)
assert cmd == ["x"] and callable(pre)
def test_mac_makes_venvs_with_uv(self, mac, home):
from lintunes.dj import venv_tool
venv = Path("/v")
assert venv_tool.uses_uv()
uv = str(venv_tool.uv_path())
assert uv == str(home / "Library/Application Support/LinTunes/bin"
/ f"uv-{venv_tool.UV_VERSION}")
assert venv_tool.create_command(venv) == [
uv, "venv", "--quiet", "--python", venv_tool.PYTHON_VERSION, "/v"]
assert venv_tool.install_command(venv, ["a"], "https://idx") == [
uv, "pip", "install", "--quiet", "--python", "/v/bin/python",
"--index-url", "https://idx", "a"]
cmd, pre = venv_tool.niced(["x"], 19)
assert cmd == ["/usr/bin/nice", "-n", "19", "x"] and pre is None
def test_frozen_linux_uses_uv_too(self, monkeypatch):
from lintunes.dj import venv_tool
monkeypatch.setattr(paths, "FROZEN", True)
assert venv_tool.uses_uv()
def test_uv_env_is_ours_and_clean(self, mac, home):
from lintunes.dj import venv_tool
env = venv_tool.uv_env({"PYTHONHOME": "/app", "PYTHONPATH": "/app",
"VIRTUAL_ENV": "/x", "PATH": "/bin"})
assert "PYTHONHOME" not in env and "PYTHONPATH" not in env
assert "VIRTUAL_ENV" not in env and env["PATH"] == "/bin"
assert env["UV_MANAGED_PYTHON"] == "1"
assert env["UV_PYTHON_INSTALL_DIR"].startswith(str(home / "Library"))
assert env["UV_CACHE_DIR"] == str(home / "Library/Caches/LinTunes/uv")
assert os.path.isfile(env["SSL_CERT_FILE"])
@pytest.mark.parametrize("machine, target", [
("arm64", "aarch64-apple-darwin"), ("x86_64", "x86_64-apple-darwin")])
def test_uv_targets(self, mac, machine, target):
from lintunes.dj import venv_tool
mac.setattr(venv_tool.platform, "machine", lambda: machine)
assert venv_tool.uv_target() == target
assert len(venv_tool._UV_SHA256[target]) == 64
def test_ensure_uv_verifies_then_unpacks(self, mac, tmp_path):
from lintunes.dj import venv_tool
mac.setenv("XDG_DATA_HOME", str(tmp_path))
mac.setattr(venv_tool.platform, "machine", lambda: "arm64")
target = "aarch64-apple-darwin"
archive = _uv_tarball(target)
with pytest.raises(venv_tool.VenvError):
venv_tool.ensure_uv(fetch=lambda url: archive) # real pin: mismatch
assert not venv_tool.uv_path().exists()
mac.setitem(venv_tool._UV_SHA256, target, hashlib.sha256(archive).hexdigest())
urls = []
path = venv_tool.ensure_uv(fetch=lambda url: urls.append(url) or archive)
assert urls == [venv_tool._UV_RELEASE + f"uv-{target}.tar.gz"]
assert path.read_bytes() == b"#!/bin/sh\necho uv\n"
assert os.access(path, os.X_OK)
assert venv_tool.ensure_uv(fetch=lambda url: 1 / 0) == path # kept
def test_an_archive_without_uv_is_refused(self, mac, tmp_path):
from lintunes.dj import venv_tool
mac.setenv("XDG_DATA_HOME", str(tmp_path))
mac.setattr(venv_tool.platform, "machine", lambda: "arm64")
target = "aarch64-apple-darwin"
archive = _uv_tarball("something-else")
mac.setitem(venv_tool._UV_SHA256, target, hashlib.sha256(archive).hexdigest())
with pytest.raises(venv_tool.VenvError):
venv_tool.ensure_uv(fetch=lambda url: archive)
assert not venv_tool.uv_path().exists()
class TestDemucs:
def test_linux_paths_and_words_unchanged(self, home, monkeypatch, tmp_path):
from lintunes.dj import stems
monkeypatch.setattr(paths, "FROZEN", False)
assert stems.venv_dir() == home / ".local/share/lintunes/demucs"
assert stems.cache_root() == home / ".cache/lintunes/stems"
v = stems.venv_dir()
assert stems.setup_command() == (
f"python3 -m venv {v} && {v}/bin/pip install torch --index-url "
f"https://download.pytorch.org/whl/cpu && {v}/bin/pip install numpy demucs")
assert not stems.setup_in_app()
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "d"))
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "c"))
assert stems.venv_dir() == tmp_path / "d/lintunes/demucs"
assert stems.cache_root() == tmp_path / "c/lintunes/stems"
def test_mac_paths(self, home, mac):
from lintunes.dj import instant, stems
assert stems.venv_dir() == home / "Library/Application Support/LinTunes/demucs"
assert stems.cache_root() == home / "Library/Caches/LinTunes/stems"
assert instant.venv_dir() == home / "Library/Application Support/LinTunes/spleeter"
assert stems.setup_in_app()
assert "Preferences › DJ" in stems.setup_command()
def test_mac_packages(self, mac):
from lintunes.dj import stems
mac.setattr(stems.platform, "machine", lambda: "arm64")
[(_t, packages, index)] = stems.install_steps()
assert index is None and "torch==2.8.0" in packages
assert "torchaudio==2.8.0" in packages and "soundfile" in packages
mac.setattr(stems.platform, "machine", lambda: "x86_64")
[(_t, packages, index)] = stems.install_steps()
assert "torch==2.2.2" in packages and "numpy<2" in packages
def test_mac_setup_runs_uv(self, qapp, home, mac):
from lintunes.dj import stems, venv_tool
mac.setattr(stems.platform, "machine", lambda: "arm64")
mac.setattr(venv_tool, "ensure_uv", lambda fetch=None: venv_tool.uv_path())
calls = []
class Done:
returncode = 0
stderr = stdout = ""
mac.setattr(stems.subprocess, "run",
lambda cmd, **kw: calls.append((cmd, kw["env"])) or Done())
setup = stems.DemucsSetup()
said, finished, failed = [], [], []
setup.progress.connect(said.append)
setup.finished.connect(lambda: finished.append(1))
setup.failed.connect(failed.append)
setup._run()
assert failed == [] and finished == [1]
uv = str(venv_tool.uv_path())
assert calls[0][0][:2] == [uv, "venv"]
assert calls[1][0][:3] == [uv, "pip", "install"]
assert "demucs==4.0.1" in calls[1][0]
assert all(env["UV_MANAGED_PYTHON"] == "1" for _c, env in calls)
def test_mac_split_is_niced_by_command(self, tmp_path, mac):
from types import SimpleNamespace
from lintunes.dj import stems
song = tmp_path / "s.mp3"
song.write_bytes(b"x")
mac.setenv("XDG_CACHE_HOME", str(tmp_path / "c"))
mac.setattr(stems, "available", lambda: True)
mac.setattr(stems, "audio_hash", lambda path: None)
mac.setattr(stems.os, "cpu_count", lambda: 8)
seen = {}
class Proc:
stderr = SimpleNamespace(read=lambda n: b"")
def wait(self):
return 1
def popen(cmd, **kw):
seen.update(cmd=cmd, **kw)
return Proc()
mac.setattr(stems.subprocess, "Popen", popen)
mac.setenv("PYTHONHOME", "/Applications/LinTunes.app")
with pytest.raises(OSError):
stems.split(str(song), "htdemucs", True)
assert seen["cmd"][:3] == ["/usr/bin/nice", "-n", "19"]
assert seen["preexec_fn"] is None
assert "PYTHONHOME" not in seen["env"]
assert seen["env"]["OMP_NUM_THREADS"] == "2"
class TestInstant:
def test_mac_setup_runs_uv(self, qapp, home, mac):
from lintunes.dj import instant, venv_tool
mac.setattr(venv_tool, "ensure_uv", lambda fetch=None: venv_tool.uv_path())
mac.setattr(instant, "install_models", lambda fetch=None: None)
calls = []
class Done:
returncode = 0
stderr = stdout = ""
mac.setattr(instant.subprocess, "run",
lambda cmd, **kw: calls.append(cmd) or Done())
setup = instant.InstantSetup()
failed = []
setup.failed.connect(failed.append)
setup._run()
assert failed == []
uv = str(venv_tool.uv_path())
assert calls[0][:2] == [uv, "venv"]
assert calls[1][:3] == [uv, "pip", "install"]
assert f"sherpa-onnx=={instant.SHERPA_VERSION}" in calls[1]
def test_linux_setup_unchanged(self, qapp, home, monkeypatch):
from lintunes.dj import instant
monkeypatch.setattr(paths, "FROZEN", False)
monkeypatch.setattr(instant, "install_models", lambda fetch=None: None)
calls = []
class Done:
returncode = 0
stderr = stdout = ""
monkeypatch.setattr(instant.subprocess, "run",
lambda cmd, **kw: calls.append((cmd, kw.get("env"))) or Done())
instant.InstantSetup()._run()
venv = instant.venv_dir()
assert calls == [
([sys.executable, "-m", "venv", str(venv)], None),
([str(venv / "bin/python"), "-m", "pip", "install", "--quiet",
f"sherpa-onnx=={instant.SHERPA_VERSION}", "numpy"], None)]
def test_the_runner_ships_beside_the_module(self):
from lintunes.dj import instant
assert instant.RUNNER.is_file()
def test_dj_output_tries_any_rate_only_on_a_mac(monkeypatch):
from lintunes.dj import output
assert not output._converts_any_rate()
monkeypatch.setattr(paths, "IS_MAC", True)
assert output._converts_any_rate()
+579
View File
@@ -0,0 +1,579 @@
"""Round 129: the macOS port, as far as it can be checked on Linux.
Every Mac branch keys off ``lintunes.paths.IS_MAC``, so these tests flip it
with monkeypatch and fake whatever macOS would supply (pyobjc, caffeinate,
``open``, ``QFile.moveToTrash``). They also pin that Linux is unchanged:
the same paths, with and without the XDG variables set.
"""
import os
import sys
import types
from pathlib import Path
import pytest
from lintunes import paths
@pytest.fixture
def mac(monkeypatch):
monkeypatch.setattr(paths, "IS_MAC", True)
return monkeypatch
@pytest.fixture
def home(tmp_path, monkeypatch):
home = tmp_path / "home"
home.mkdir()
monkeypatch.setenv("HOME", str(home))
for var in ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME"):
monkeypatch.delenv(var, raising=False)
return home
# ---- paths: Linux unchanged, Mac under ~/Library ----
def _machine_paths():
from lintunes import config, eventlog, loudness, mpris
from lintunes.andtunes import art, sync
from lintunes.export import upload
from lintunes.importers import lossless
track = types.SimpleNamespace(track_id=7)
return {
"config": config.config_path(),
"loudness": loudness.default_cache_path(),
"converting": lossless.staging_root(),
"webmix": upload.staging_root(),
"artwork": mpris._art_cache_dir(),
"andtunes-art": art._cache_dir(),
"andtunes-flac": sync.flac_cache(track),
"eventlog": eventlog.default_log_path(),
}
def test_linux_paths_are_the_xdg_defaults(home):
got = _machine_paths()
assert got == {
"config": home / ".config/lintunes/config.json",
"loudness": home / ".cache/lintunes/loudness.json",
"converting": home / ".cache/lintunes/converting",
"webmix": home / ".cache/lintunes/webmix",
"artwork": home / ".cache/lintunes/artwork",
"andtunes-art": home / ".cache/lintunes/andtunes-art",
"andtunes-flac": home / ".cache/lintunes/andtunes-flac/7.flac",
"eventlog": home / ".cache/lintunes/control-events.log",
}
def test_linux_paths_follow_xdg_variables(home, tmp_path, monkeypatch):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "cfg"))
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
got = _machine_paths()
assert got["config"] == tmp_path / "cfg/lintunes/config.json"
assert got["loudness"] == tmp_path / "cache/lintunes/loudness.json"
assert got["webmix"] == tmp_path / "cache/lintunes/webmix"
assert got["andtunes-flac"] == tmp_path / "cache/lintunes/andtunes-flac/7.flac"
# The control log always lived under ~/.cache on Linux; still does.
assert got["eventlog"] == home / ".cache/lintunes/control-events.log"
def test_mac_paths_live_under_library(home, mac):
got = _machine_paths()
support = home / "Library/Application Support/LinTunes"
caches = home / "Library/Caches/LinTunes"
assert got["config"] == support / "config.json"
assert got["loudness"] == caches / "loudness.json"
assert got["webmix"] == caches / "webmix"
assert got["artwork"] == caches / "artwork"
assert got["eventlog"] == caches / "control-events.log"
# ---- PATH for the CLI tools ----
def test_tool_dirs_left_alone_on_linux():
from lintunes import main
env = {"PATH": "/usr/bin:/bin"}
main.add_mac_tool_dirs(env)
assert env == {"PATH": "/usr/bin:/bin"}
def test_mac_prepends_homebrew_once(mac):
from lintunes import main
env = {"PATH": "/usr/bin:/bin:/usr/local/bin"}
main.add_mac_tool_dirs(env)
dirs = env["PATH"].split(os.pathsep)
assert dirs[0] == "/opt/homebrew/bin"
assert dirs.count("/usr/local/bin") == 1
assert dirs[-2:] == ["/bin", "/usr/local/bin"]
# ---- yt-dlp's cookies ----
def test_mac_cookies_browser_from_application_support(home, mac):
from lintunes import url_import
assert url_import.default_cookies_browser() is None
(home / "Library/Application Support/Google/Chrome").mkdir(parents=True)
assert url_import.default_cookies_browser() == "chrome"
(home / "Library/Application Support/Firefox/Profiles").mkdir(parents=True)
assert url_import.default_cookies_browser() == "firefox"
def test_mac_never_offers_safari(home, mac):
from lintunes import url_import
(home / "Library/Cookies").mkdir(parents=True)
(home / "Library/Safari").mkdir(parents=True)
assert url_import.default_cookies_browser() is None
def test_linux_cookies_unchanged(home):
from lintunes import url_import
(home / ".mozilla/firefox").mkdir(parents=True)
assert url_import.default_cookies_browser() == "firefox"
# ---- trash ----
def test_mac_trash_uses_qfile(tmp_path, mac):
from PyQt6.QtCore import QFile
from lintunes import trash
song = tmp_path / "music" / "song.mp3"
song.parent.mkdir()
song.write_bytes(b"x")
bin_ = tmp_path / "Trash"
bin_.mkdir()
def fake(path):
dest = bin_ / Path(path).name
os.rename(path, dest)
return True, str(dest)
mac.setattr(QFile, "moveToTrash", staticmethod(fake))
dest = trash.send_to_trash(song)
assert dest == bin_ / "song.mp3" and dest.exists() and not song.exists()
# No freedesktop .trashinfo anywhere.
assert not list(tmp_path.rglob("*.trashinfo"))
# Undo puts it back.
trash.restore_from_trash(dest, song)
assert song.exists() and not dest.exists()
assert trash.original_path(dest) is None
def test_mac_trash_failure_leaves_the_file(tmp_path, mac):
from PyQt6.QtCore import QFile
from lintunes import trash
song = tmp_path / "song.mp3"
song.write_bytes(b"x")
mac.setattr(QFile, "moveToTrash", staticmethod(lambda p: (False, "")))
with pytest.raises(trash.TrashError):
trash.send_to_trash(song)
assert song.read_bytes() == b"x"
# ---- sleep inhibition ----
class _FakeProc:
def __init__(self, argv, **kw):
self.argv = argv
self.terminated = False
_FakeProc.made.append(self)
def poll(self):
return 0 if self.terminated else None
def terminate(self):
self.terminated = True
def wait(self, timeout=None):
return 0
def kill(self):
self.terminated = True
def test_caffeinate_flags():
from lintunes import inhibit
assert inhibit.caffeinate_command(inhibit.INHIBIT_SUSPEND, pid=42) == \
["caffeinate", "-i", "-w", "42"]
assert inhibit.caffeinate_command(
inhibit.INHIBIT_SUSPEND | inhibit.INHIBIT_LOGOUT, pid=42) == \
["caffeinate", "-i", "-s", "-m", "-w", "42"]
def test_mac_inhibitor_holds_one_caffeinate(mac):
from lintunes import inhibit
_FakeProc.made = []
mac.setattr(inhibit.shutil, "which", lambda name: "/usr/bin/" + name)
mac.setattr(inhibit.subprocess, "Popen", _FakeProc)
inh = inhibit.SleepInhibitor()
inh.inhibit()
inh.inhibit()
assert len(_FakeProc.made) == 1
assert _FakeProc.made[0].argv[:2] == ["caffeinate", "-i"]
assert _FakeProc.made[0].argv[-2:] == ["-w", str(os.getpid())]
inh.release()
assert _FakeProc.made[0].terminated
inh.release() # twice is fine
inh.inhibit()
assert len(_FakeProc.made) == 2
inhibit._release_all() # what atexit runs
assert _FakeProc.made[1].terminated
def test_mac_inhibitor_without_caffeinate_is_a_noop(mac):
from lintunes import inhibit
mac.setattr(inhibit.shutil, "which", lambda name: None)
inh = inhibit.SleepInhibitor()
inh.inhibit()
inh.release()
# ---- Now Playing ----
def test_setup_mpris_on_mac_without_pyobjc(mac, qapp):
from lintunes import mpris
mac.setitem(sys.modules, "MediaPlayer", None) # import → ImportError
assert mpris.setup_mpris(object(), object()) is None
class _Command:
def __init__(self):
self.handlers = []
self.enabled = False
def setEnabled_(self, on):
self.enabled = on
def addTargetWithHandler_(self, handler):
self.handlers.append(handler)
class _Center:
def __init__(self):
self.info = "unset"
self.state = None
def setNowPlayingInfo_(self, info):
self.info = info
def setPlaybackState_(self, state):
self.state = state
def _fake_mediaplayer():
mp = types.SimpleNamespace()
names = ("playCommand", "pauseCommand", "togglePlayPauseCommand",
"stopCommand", "nextTrackCommand", "previousTrackCommand",
"changePlaybackPositionCommand")
commands = {n: _Command() for n in names}
remote = types.SimpleNamespace(**{n: (lambda c=c: c) for n, c in commands.items()})
center = _Center()
mp.MPRemoteCommandCenter = types.SimpleNamespace(
sharedCommandCenter=lambda: remote)
mp.MPNowPlayingInfoCenter = types.SimpleNamespace(defaultCenter=lambda: center)
for key in ("MPMediaItemPropertyTitle", "MPMediaItemPropertyArtist",
"MPMediaItemPropertyAlbumTitle", "MPMediaItemPropertyPlaybackDuration",
"MPMediaItemPropertyArtwork",
"MPNowPlayingInfoPropertyElapsedPlaybackTime",
"MPNowPlayingInfoPropertyPlaybackRate"):
setattr(mp, key, key)
return mp, commands, center
def _fake_player():
from PyQt6.QtCore import QObject, pyqtSignal
class P(QObject):
track_changed = pyqtSignal(object)
playing_changed = pyqtSignal(bool)
position_changed = pyqtSignal("qint64")
def __init__(self):
super().__init__()
self.calls = []
self.current_track = None
self.playing = False
self.pos = 0
def is_playing(self):
return self.playing
def position_ms(self):
return self.pos
def duration_ms(self):
return 0
def __getattr__(self, name):
if name in ("play", "pause", "toggle_play", "stop", "next",
"previous", "seek"):
return lambda *a: self.calls.append((name, *a))
raise AttributeError(name)
return P()
def test_now_playing_routes_commands_and_mirrors_state(qapp):
from lintunes import nowplaying_mac
mp, commands, center = _fake_mediaplayer()
player = _fake_player()
np = nowplaying_mac.MacNowPlaying(player, None, mp)
assert all(c.enabled and len(c.handlers) == 1 for c in commands.values())
assert center.info is None and center.state == nowplaying_mac.STATE_STOPPED
for name, expected in (("togglePlayPauseCommand", "toggle_play"),
("nextTrackCommand", "next"),
("previousTrackCommand", "previous"),
("playCommand", "play"),
("pauseCommand", "pause")):
status = commands[name].handlers[0](object())
assert status == nowplaying_mac.STATUS_SUCCESS
assert player.calls[-1] == (expected,)
event = types.SimpleNamespace(positionTime=lambda: 12.5)
commands["changePlaybackPositionCommand"].handlers[0](event)
assert player.calls[-1] == ("seek", 12500)
player.current_track = types.SimpleNamespace(
track_id=1, name="Song", artist="Artist", album="Album",
total_time=200_000, location="")
player.playing = True
player.pos = 3000
player.track_changed.emit(player.current_track)
assert center.info["MPMediaItemPropertyTitle"] == "Song"
assert center.info["MPMediaItemPropertyArtist"] == "Artist"
assert center.info["MPMediaItemPropertyAlbumTitle"] == "Album"
assert center.info["MPMediaItemPropertyPlaybackDuration"] == 200.0
assert center.info["MPNowPlayingInfoPropertyElapsedPlaybackTime"] == 3.0
assert center.info["MPNowPlayingInfoPropertyPlaybackRate"] == 1.0
assert center.state == nowplaying_mac.STATE_PLAYING
player.playing = False
player.playing_changed.emit(False)
assert center.info["MPNowPlayingInfoPropertyPlaybackRate"] == 0.0
assert center.state == nowplaying_mac.STATE_PAUSED
np.deleteLater()
def test_now_playing_handler_from_another_thread_is_queued(qapp):
import threading
from lintunes import nowplaying_mac
mp, commands, _center = _fake_mediaplayer()
player = _fake_player()
np = nowplaying_mac.MacNowPlaying(player, None, mp)
t = threading.Thread(target=lambda: commands["nextTrackCommand"].handlers[0](None))
t.start()
t.join()
assert player.calls == [] # not run on the system's thread
qapp.processEvents()
assert player.calls == [("next",)]
np.deleteLater()
# ---- Finder reveal, shortcuts shown in menus ----
def test_reveal_uses_open_r_on_mac(mac):
from lintunes.gui import track_table
seen = []
mac.setattr(track_table.subprocess, "Popen",
lambda argv, **kw: seen.append(argv))
track_table.reveal_paths(["/Music/a.mp3", "/Music/b.mp3"])
assert seen == [["open", "-R", "/Music/a.mp3", "/Music/b.mp3"]]
def test_key_hint(qapp, monkeypatch):
from lintunes.gui.track_table import key_hint
assert key_hint("Ctrl+I") == "Ctrl+I"
assert key_hint("Del") == "Del"
monkeypatch.setattr(paths, "IS_MAC", True)
assert key_hint("Del") == "⌫"
# ---- menu bar ----
class _Prefs:
def __init__(self, value):
self.value = value
def get(self, key, default=None):
return self.value if key == "menu_bar" else default
def test_menu_bar_never_hides_on_mac(mac):
from lintunes.gui import menu_bar
assert menu_bar.hidden_by_pref(_Prefs("alt")) is False
def test_menu_bar_pref_unchanged_on_linux():
from lintunes.gui import menu_bar
assert menu_bar.hidden_by_pref(_Prefs("alt")) is True
assert menu_bar.hidden_by_pref(_Prefs("always")) is False
def test_register_shortcuts_is_a_noop_on_mac(qapp, mac):
from PyQt6.QtWidgets import QMainWindow
from lintunes.gui import menu_bar
win = QMainWindow()
win.menuBar().addMenu("&File").addAction("New")
menu_bar.register_shortcuts(win, win.menuBar())
assert win.actions() == []
mac.setattr(paths, "IS_MAC", False)
menu_bar.register_shortcuts(win, win.menuBar())
assert len(win.actions()) == 1
win.deleteLater()
# ---- the main window on a Mac ----
@pytest.fixture
def mac_window(qapp, tmp_path, mac):
from lintunes import device_sync
from lintunes.gui.main_window import MainWindow
from lintunes.library_manager import LibraryManager
from lintunes.models import Library
from lintunes.preferences import Preferences
probes = []
mac.setattr(device_sync.DeviceWatcher, "probe",
lambda self: probes.append(1))
manager = LibraryManager(Library(), tmp_path / "data")
win = MainWindow(manager, Preferences(tmp_path / "data"))
win.probes = probes
yield win
win.close()
def test_mac_window_has_no_rabbit(mac_window):
win = mac_window
for action in (win._andtunes_action, win._full_sync_action,
win._sync_settings_action, win._install_action,
win._shazam_action):
assert not action.isVisible() and not action.isEnabled()
win._refresh_connection_actions()
win._refresh_device_actions()
assert win.probes == []
for action in (win._andtunes_action, win._install_action, win._shazam_action):
assert not action.isEnabled()
def test_preferences_and_quit_go_to_the_app_menu(mac_window):
from PyQt6.QtGui import QAction
roles = {a.text(): a.menuRole() for a in mac_window.actions()
+ [a for m in mac_window.menuBar().actions() if m.menu()
for a in m.menu().actions()]}
assert roles["Preferences…"] == QAction.MenuRole.PreferencesRole
assert roles["Quit"] == QAction.MenuRole.QuitRole
def test_preferences_hide_the_menu_bar_row_on_mac(qapp, tmp_path, mac):
from lintunes.gui.preferences_dialog import PreferencesDialog
from lintunes.preferences import Preferences
from tests.test_round40 import _FakeLastFm
dialog = PreferencesDialog(Preferences(tmp_path), _FakeLastFm())
assert dialog._menu_bar_check.isHidden()
dialog.deleteLater()
# ---- files opened on the Dock icon ----
def test_file_open_events_import_as_one_batch(qapp):
import time
from PyQt6.QtCore import QEvent
from lintunes import main
class _Open: # QFileOpenEvent can't be built from Python
def __init__(self, name):
self.name = name
def type(self):
return QEvent.Type.FileOpen
def file(self):
return self.name
got = []
filt = main.FileOpenFilter(got.append)
for name in ("/m/a.mp3", "/m/b.mp3"):
assert filt.eventFilter(None, _Open(name))
deadline = time.monotonic() + 2
while not got and time.monotonic() < deadline:
qapp.processEvents()
time.sleep(0.01)
assert got == [[Path("/m/a.mp3"), Path("/m/b.mp3")]]
# ---- rsync on a Mac ----
def test_rsync_major():
from lintunes.export import upload
assert upload.rsync_major("rsync version 3.2.7 protocol version 31") == 3
assert upload.rsync_major(
"openrsync: protocol version 29\nrsync version 2.6.9 compatible") == 2
assert upload.rsync_major("") is None
def test_mac_rsync_problem_only_on_mac(monkeypatch):
from lintunes.export import upload
assert upload.mac_rsync_problem() is None
monkeypatch.setattr(paths, "IS_MAC", True)
monkeypatch.setattr(upload.subprocess, "run", lambda *a, **k:
types.SimpleNamespace(stdout="rsync version 2.6.9 protocol version 29"))
assert "brew install rsync" in upload.mac_rsync_problem()
monkeypatch.setattr(upload.subprocess, "run", lambda *a, **k:
types.SimpleNamespace(stdout="rsync version 3.4.1 protocol version 32"))
assert upload.mac_rsync_problem() is None
# ---- D-Bus optional ----
def test_modules_import_without_qtdbus(monkeypatch):
"""With QtDBus gone, mpris/inhibit/track_table still import and the
inhibitor no-ops (re-imported fresh, then restored)."""
import importlib
saved = {n: sys.modules.pop(n) for n in
("lintunes.mpris", "lintunes.inhibit") if n in sys.modules}
monkeypatch.setitem(sys.modules, "PyQt6.QtDBus", None)
try:
mpris = importlib.import_module("lintunes.mpris")
inhibit = importlib.import_module("lintunes.inhibit")
assert not mpris.HAVE_DBUS and not inhibit.HAVE_DBUS
assert mpris.setup_mpris(object(), object()) is None
assert mpris.string_array(["a"]) == ["a"]
inh = inhibit.SleepInhibitor()
inh.inhibit()
inh.release()
finally:
import lintunes
for n in ("lintunes.mpris", "lintunes.inhibit"):
sys.modules.pop(n, None)
short = n.split(".")[1]
if hasattr(lintunes, short):
delattr(lintunes, short)
sys.modules.update(saved)
for n, module in saved.items():
setattr(lintunes, n.split(".")[1], module)
def test_case_only_rename_leaves_the_file_alone(tmp_path, monkeypatch):
"""On a filesystem that ignores case, the "new" folder is the old one:
the file must not be renamed beside itself."""
import os
from types import SimpleNamespace
from lintunes.library_manager import LibraryManager
root = tmp_path / "Music"
src = root / "Rjd2" / "Deadringer" / "01 Song.mp3"
src.parent.mkdir(parents=True)
src.write_bytes(b"x")
dest = root / "RJD2" / "Deadringer" / "01 Song.mp3"
real_exists = type(src).exists
monkeypatch.setattr(type(src), "exists",
lambda p: p == dest or real_exists(p))
monkeypatch.setattr(os.path, "samefile", lambda a, b: True)
moved = []
fake = SimpleNamespace(
_ORGANIZE_FIELDS=LibraryManager._ORGANIZE_FIELDS,
organize_root=lambda: root,
_move_file=lambda s, d: moved.append((s, d)) or d)
track = SimpleNamespace(location=str(src), name="Song", artist="Rjd2",
album_artist="", album="Deadringer",
compilation=False)
for field in LibraryManager._ORGANIZE_FIELDS:
if not hasattr(track, field):
setattr(track, field, "")
assert LibraryManager._maybe_move_file(fake, track, {"artist": "RJD2"}) is None
assert moved == []
+448
View File
@@ -0,0 +1,448 @@
"""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