Files
lintunes/tests/test_round107.py
T
trav e368b8eb6e v0.76.0: Convert to MP3 for songs already in the library, and for Cassette arrivals
- right-click › Convert to MP3…: lossless songs become MP3s at a chosen
  bitrate; same tracks (plays, ratings, playlists kept), originals to the
  trash, one undo step brings them back; Cancel changes nothing
- Preferences › Importing › Convert songs from Cassette friends too
- the bitrate list is just the numbers
- conversions stage in ~/.cache, not /tmp
2026-10-23 01:21:52 -07:00

222 lines
9.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Round 107: no quality labels on the bitrates, "Convert songs from Cassette
friends too", and right-click › Convert to MP3… on songs already in the
library."""
import shutil
from pathlib import Path
import pytest
from lintunes import tagging
from lintunes.importers import lossless
from lintunes.library_manager import LibraryManager
from lintunes.models import Library, Playlist, Track
from lintunes.preferences import Preferences
from tests.test_round106 import _digest, _tagged_flac, _wait
@pytest.fixture(autouse=True)
def _staging_in_tmp(tmp_path, monkeypatch):
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
@pytest.fixture
def fake_trash(tmp_path, monkeypatch):
"""send/restore that never reach the real desktop trash."""
bin_ = tmp_path / "trash-bin"
bin_.mkdir()
def send(path):
path = Path(path)
if not path.exists():
from lintunes.trash import TrashError
raise TrashError(f"{path} doesn't exist")
dest = bin_ / f"{len(list(bin_.iterdir()))}-{path.name}"
shutil.move(str(path), dest)
return dest
def restore(trashed, original):
Path(original).parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(trashed), str(original))
monkeypatch.setattr("lintunes.library_manager.trash.send_to_trash", send)
monkeypatch.setattr("lintunes.library_manager.trash.restore_from_trash",
restore)
return bin_
def _library_with_flacs(tmp_path, names):
music = tmp_path / "media" / "Music" / "Nissa" / "Big Files"
music.mkdir(parents=True)
library = Library(music_folder=str(tmp_path / "media"))
for tid, name in enumerate(names, start=1):
path = _tagged_flac(music / f"{tid:02d} {name}.flac", name, seconds=2)
fields = tagging.read_tags(path)
library.tracks[tid] = Track(
track_id=tid, name=name, artist="Nissa", album="Big Files",
location=str(path), kind=fields["kind"], play_count=7 * tid,
rating=80, total_time=fields["total_time"], size=fields["size"])
library.playlists["P"] = Playlist(name="Mix", persistent_id="P",
track_ids=list(library.tracks))
return LibraryManager(library, tmp_path / "data")
# ---- the setting ----
def test_bitrates_are_just_numbers(qapp, tmp_path):
from unittest.mock import MagicMock
from lintunes.gui.preferences_dialog import PreferencesDialog
dialog = PreferencesDialog(Preferences(tmp_path / "data"), MagicMock())
labels = [dialog._compress_kbps.itemText(i)
for i in range(dialog._compress_kbps.count())]
assert labels == ["320 kbps", "256 kbps", "192 kbps", "160 kbps", "128 kbps"]
def test_cassette_setting_needs_the_main_one(qapp, tmp_path):
from unittest.mock import MagicMock
from lintunes.gui.preferences_dialog import PreferencesDialog
prefs = Preferences(tmp_path / "data")
assert lossless.cassette_kbps(prefs) is None
dialog = PreferencesDialog(prefs, MagicMock())
assert not dialog._compress_cassette.isEnabled()
dialog._compress_check.setChecked(True)
assert dialog._compress_cassette.isEnabled()
assert lossless.cassette_kbps(prefs) is None # off by default
dialog._compress_cassette.setChecked(True)
assert lossless.cassette_kbps(prefs) == 256
dialog._compress_check.setChecked(False)
assert lossless.cassette_kbps(prefs) is None
assert not dialog._compress_cassette.isEnabled()
def test_a_lossless_cassette_arrival_is_converted(tmp_path, mp3_file):
from lintunes.cassette import delivery
outbox = tmp_path / "outbox"
outbox.mkdir()
flac = _tagged_flac(outbox / "7 ~ Huge.flac", "Huge")
sent = _digest(flac)
mp3 = shutil.copy(mp3_file, outbox / "8 ~ Small.mp3")
plan = delivery.ReceivePlan(token="t", arrivals=[
delivery.Arrival(7, flac, True, False),
delivery.Arrival(8, Path(mp3), True, False)])
music = tmp_path / "Music"
result = delivery.run_plans([], [plan], music, compress_kbps=160)
assert result.errors == []
huge, small = result.staged
assert huge.dest.name == "Huge.mp3" and huge.dest.parent.parent.name == "Nissa"
assert huge.fields["kind"] == "MPEG audio file"
assert 150 <= huge.fields["bit_rate"] <= 170
assert small.dest.name == "Small.mp3"
assert _digest(flac) == sent # the friend's copy is only read
assert not any(lossless.staging_root().iterdir())
# Off: as sent.
result = delivery.run_plans([], [plan], tmp_path / "Music2")
assert result.staged[0].dest.suffix == ".flac"
def test_the_coordinator_reads_the_setting_each_pass(qapp, tmp_path):
from unittest.mock import MagicMock
from lintunes.gui.cassette_delivery import DeliveryCoordinator
kbps = [None]
service = MagicMock()
coordinator = DeliveryCoordinator(service, MagicMock(),
compress_kbps=lambda: kbps[0])
coordinator._worker = MagicMock()
coordinator._worker.busy.return_value = False
from lintunes.cassette import delivery
plan = delivery.ReceivePlan(token="t", arrivals=[MagicMock()])
with pytest.MonkeyPatch.context() as mp:
mp.setattr(delivery, "plan_send", lambda *a: delivery.SendPlan(
token="t", outbox=tmp_path))
mp.setattr(delivery, "plan_receive", lambda *a, **k: plan)
service.state.return_value.friends = {"t": MagicMock()}
service.root = tmp_path
kbps[0] = 192
coordinator.run()
assert coordinator._worker.start.call_args.args[3] == 192
# ---- Convert to MP3 on library songs ----
def test_only_lossless_songs_are_convertible(tmp_path, mp3_file, m4a_file):
from lintunes.gui.compress_import import convertible
flac = _tagged_flac(tmp_path / "a.flac", "A")
tracks = [Track(track_id=i, location=str(p)) for i, p in
enumerate([flac, mp3_file, m4a_file, tmp_path / "gone.flac"])]
assert [t.track_id for t in convertible(tracks)] == [0]
def test_convert_swaps_files_keeps_the_track_and_undoes(qapp, tmp_path, fake_trash):
from lintunes.gui.compress_import import ConvertLibrary
manager = _library_with_flacs(tmp_path, ["Alpha", "Bravo"])
originals = {tid: (Path(t.location), _digest(Path(t.location)))
for tid, t in manager.library.tracks.items()}
batch = ConvertLibrary(manager, list(manager.library.tracks.values()), 128)
assert batch.window is not None
over = []
batch.over.connect(over.append)
batch.start()
_wait(qapp, batch)
assert over == ["Converted 2 songs to 128 kbps MP3"]
for tid, (flac, digest) in originals.items():
track = manager.library.tracks[tid]
assert track.location == str(flac.with_suffix(".mp3"))
assert Path(track.location).is_file() and not flac.exists()
assert track.kind == "MPEG audio file" and track.bit_rate <= 136
assert track.play_count == 7 * tid and track.rating == 80
assert tagging.read_tags(track.location)["name"] == track.name
assert manager.library.playlists["P"].track_ids == [1, 2]
assert len(list(fake_trash.iterdir())) == 2
assert not any(lossless.staging_root().iterdir())
manager.undo_stack.undo() # one step for the batch
for tid, (flac, digest) in originals.items():
track = manager.library.tracks[tid]
assert track.location == str(flac) and _digest(flac) == digest
assert track.kind == "FLAC audio file"
assert not flac.with_suffix(".mp3").exists()
manager.undo_stack.redo()
assert all(t.location.endswith(".mp3") and Path(t.location).is_file()
for t in manager.library.tracks.values())
def test_cancel_changes_nothing(qapp, tmp_path, fake_trash):
from lintunes.gui.compress_import import ConvertLibrary
manager = _library_with_flacs(tmp_path, ["Alpha", "Bravo"])
before = {t: tr.location for t, tr in manager.library.tracks.items()}
batch = ConvertLibrary(manager, list(manager.library.tracks.values()), 128)
over = []
batch.over.connect(over.append)
batch.start()
batch.request_cancel()
_wait(qapp, batch)
assert {t: tr.location for t, tr in manager.library.tracks.items()} == before
assert all(Path(p).exists() for p in before.values())
assert list(fake_trash.iterdir()) == []
assert not manager.undo_stack.can_undo()
assert over == ["Convert to MP3 cancelled — nothing was changed"]
assert not any(lossless.staging_root().iterdir())
def test_window_right_click_flow(qapp, tmp_path, fake_trash, monkeypatch):
from lintunes.gui.main_window import MainWindow
manager = _library_with_flacs(tmp_path, ["Alpha"])
window = MainWindow(manager, Preferences(tmp_path / "data"))
asked = []
monkeypatch.setattr(window, "_ask_convert_kbps",
lambda tracks: asked.append(len(tracks)) or 192)
try:
window._convert_to_mp3([1])
assert asked == [1]
batch = window._compress
assert batch is not None and batch.window is None # one song
assert window._sync_label.isVisibleTo(window)
_wait(qapp, batch)
assert window._compress is None
assert manager.library.tracks[1].location.endswith(".mp3")
# Nothing lossless left: says so, starts nothing.
window._convert_to_mp3([1])
assert window._compress is None and asked == [1]
finally:
window.close()