"""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'' f'
{address}
{key}
' f'
') 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()