Files
lintunes/tests/test_round129_os.py
T
trav f21c31940f
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
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
2026-11-17 22:41:48 -08:00

580 lines
20 KiB
Python

"""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 == []