"""Tests for the generic adapter layer. `test_save_fidelity.py` exercises the Traktor STORE and the bytes it writes; nothing there touches the projection. Without this file the entire generic layer — the single parse, the index refresh after each command, the cue-type translation, capabilities — would be untested by the suite that gates saves. Runs against a temp copy of the real collection, like the other suites. """ import os import shutil import sys import tempfile import warnings from pathlib import Path warnings.filterwarnings("ignore") os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-adapter-appdata-") REAL = Path(__file__).resolve().parents[1] / "collection.nml" import traktor_nml_utils as tnu # noqa: E402 from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402 from konduktor.core.adapter import InvalidCommand, LibraryAdapter, NotFound, Unsupported # noqa: E402 from konduktor.core.model import AutoHotcue # noqa: E402 from konduktor.core.pathmap import PathMapping # noqa: E402 failed = False def _raises(fn, exc) -> bool: try: fn() except exc: return True return False def check(label, cond, detail=""): global failed print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) if not cond: failed = True # ---- opening: exactly one parse --------------------------------------- print("== opening a library parses it exactly once ==") with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) parses = {"n": 0} original_init = tnu.TraktorCollection.__init__ def counting_init(self, *a, **kw): parses["n"] += 1 return original_init(self, *a, **kw) tnu.TraktorCollection.__init__ = counting_init try: adapter = TraktorAdapter(work) finally: tnu.TraktorCollection.__init__ = original_init # The whole point of collapsing the read model into the adapter: the 14MB # file used to be parsed twice into two graphs that could drift apart. check("parsed once, not twice", parses["n"] == 1, f"{parses['n']} parses") check("projection is populated", len(adapter.tracks) == 8485, str(len(adapter.tracks))) check("primary-key index agrees with the list", len(adapter.by_key) > 8000) check("implements the LibraryAdapter protocol", isinstance(adapter, LibraryAdapter)) # runtime_checkable only verifies method PRESENCE, so check a signature too. import inspect sig = inspect.signature(adapter.set_cue) check( "set_cue takes the generic cue vocabulary", {"slot", "start_sec", "cue_type", "role"} <= set(sig.parameters), str(list(sig.parameters)), ) # ---- capabilities ------------------------------------------------------- print("== capabilities describe Traktor, not an assumed floor ==") with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) caps = adapter.capabilities() check("platform reported", caps.platform == "traktor") check("the library is writable, with no read-only cause", caps.writable is True and caps.readonly_cause is None) check("version read from the NML header", caps.version == "20", str(caps.version)) check("8 hotcue slots", caps.cues.hotcue_slots == 8) check("memory cues: Traktor's cues on no pad, no limit, no colour", caps.cues.memory_cues is True and caps.cues.max_memory_cues is None and caps.cues.memory_color == "none") check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type") # Traktor colours a cue by its type, so no colour picker may be offered. check("no cue colours to pick", caps.cues.color == "none" and caps.cues.palette == []) check("flexible beatgrids supported", caps.grid.flexible is True) check("grid is lockable", caps.grid.lockable is True) check("the key can be written", caps.tracks.key_writable is True) check("save facts present for the UI to compose copy from", caps.save.app_name == "Traktor" and caps.save.overwrite_risk == "on_exit") # ---- commands refresh the projection ------------------------------------ print("== every command refreshes the read projection ==") with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) # metadata tid = next(t.id for t in adapter.tracks if t.title) adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"}) check("metadata edit is visible in the projection", adapter.track(tid).genre == "Konduktor Test Genre") # search reaches both comments, case-insensitively adapter.set_track_metadata(tid, {"comment": "Konduktor Search One", "comment2": "Konduktor Search Two"}) for q in ("search one", "SEARCH TWO"): hits = adapter.query_tracks(q=q, limit=20000).items check(f"search {q!r} finds the track by its comment", [x.id for x in hits] == [tid], f"{len(hits)} hits") # key — the projection's wheel, mode AND display text all follow t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m check("set_key returns the refreshed track", t is not None and (t.key, t.key_wheel, t.key_mode) == ("9m", 4, "minor"), f"{t and (t.key, t.key_wheel, t.key_mode)}") check("…and the index holds it (the key filter finds it)", any(x.id == tid for x in adapter.query_tracks(key="9m", limit=20000).items)) # cues — a free slot on a track with a grid, so the companion guard is clear tid2 = next( t.id for t in adapter.tracks if t.grid_marker_count and (cues := adapter.track_cues(t.id)) and len({c.slot for c in cues.cues if c.slot is not None}) < 7 ) before = adapter.track(tid2).hotcue_count used = {c.slot for c in adapter.track_cues(tid2).cues if c.slot is not None} free = next(s for s in range(8) if s not in used) fresh = adapter.set_cue(tid2, slot=free, start_sec=12.5, cue_type="cue") check("set_cue returns fresh cues", any(c.slot == free for c in fresh.cues)) check("hotcue count in the projection incremented", adapter.track(tid2).hotcue_count == before + 1) # cue type translation, both directions adapter.set_cue_type(tid2, free, "load") check("cue type round-trips through the generic vocabulary", next(c.type for c in adapter.track_cues(tid2).cues if c.slot == free) == "load") try: adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory") check("set_cue refuses role=memory (memory cues have their own commands)", False, "no error raised") except InvalidCommand: check("set_cue refuses role=memory (memory cues have their own commands)", True) try: adapter.set_cue_color(tid2, free, "#FF0000") check("cue colour is refused on Traktor", False, "no error raised") except Unsupported: check("cue colour is refused on Traktor", True) # memory cues — Traktor's cues on no pad (HOTCUE="-1") count_before = adapter.track(tid2).cue_count tc = adapter.add_memory_cue(tid2, start_sec=33.0, cue_type="fade_in") mem = [c for c in tc.cues if c.role == "memory"] check("an unnamed cue (Traktor's \"n.n.\") projects with no name", mem[0].name is None if mem else False, str(mem)) check("add_memory_cue returns fresh cues with the memory cue, by id", len(mem) == 1 and mem[0].slot is None and mem[0].id and mem[0].type == "fade_in" and abs(mem[0].start - 33.0) < 0.001, str(mem)) check("the hot cue bank is untouched (count and chips)", adapter.track(tid2).hotcue_count == before + 1 and adapter.track(tid2).cue_count == count_before + 1) tc = adapter.rename_memory_cue(tid2, mem[0].id, "Vocal in") renamed = next(c for c in tc.cues if c.role == "memory") check("rename_memory_cue names it", renamed.name == "Vocal in") tc = adapter.set_memory_cue_type(tid2, renamed.id, "load") renamed = next(c for c in tc.cues if c.role == "memory") check("set_memory_cue_type changes its type, keeping position and name", (renamed.type, renamed.name, round(renamed.start, 3)) == ("load", "Vocal in", 33.0), str(renamed)) check("a memory loop is not retyped", _raises(lambda: adapter.set_memory_cue_type( tid2, next(c.id for c in adapter.add_memory_cue( tid2, start_sec=40.0, cue_type="loop", length_sec=2.0).cues if c.role == "memory" and c.type == "loop"), "cue"), InvalidCommand)) adapter.delete_memory_cue(tid2, next(c.id for c in adapter.track_cues(tid2).cues if c.role == "memory" and c.type == "loop")) check("a memory cue colour is refused (Traktor colours by type)", _raises(lambda: adapter.set_memory_cue_color(tid2, renamed.id, "#FF0000"), Unsupported)) check("adding one with a colour is refused too", _raises(lambda: adapter.add_memory_cue(tid2, start_sec=1.0, cue_type="cue", color="#FF0000"), Unsupported)) tc = adapter.delete_memory_cue(tid2, renamed.id) check("delete_memory_cue removes it", not any(c.role == "memory" for c in tc.cues)) check("an unknown id is NotFound", _raises(lambda: adapter.delete_memory_cue(tid2, renamed.id), NotFound)) adapter.add_memory_cue(tid2, start_sec=34.0, cue_type="cue") summary = adapter._store._journal.summary() check("the history message names memory cues, apart from hotcues", "memory cue" in summary, summary) # grid grid_before = len(adapter.track_cues(tid2).grid_markers) adapter.add_grid_marker(tid2, adapter.track_cues(tid2).grid_markers[0].start + 40.0) check("grid marker added and projected", len(adapter.track_cues(tid2).grid_markers) == grid_before + 1) check("marker count reached the track projection", adapter.track(tid2).grid_marker_count == grid_before + 1) # ---- "Comment 2" ---------------------------------------------------------- # Traktor keeps it in INFO@RATING — a free-text attribute despite its name; the # stars are RANKING. Mixing the two up would corrupt either field silently. print("== Comment 2 is INFO@RATING, collection-only ==") with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) with_c2 = [t for t in adapter.tracks if t.comment2] check("real Comment 2 values are projected", len(with_c2) > 0, "none found") check("comment2 is advertised as editable", "comment2" in adapter.capabilities().tracks.editable_fields) t = next(t for t in adapter.tracks if t.title and t.rating and not t.comment2) adapter.set_track_metadata(t.id, {"comment2": "Konduktor C2"}) after = adapter.track(t.id) check("comment2 edit is visible in the projection", after.comment2 == "Konduktor C2") check("comment2 edit leaves the star rating alone", after.rating == t.rating) outcome = adapter.save() check("comment2 alone writes no file tags", not outcome.tag_results, str(outcome.tag_results)) text = work.read_text(encoding="utf-8") check("stored as INFO RATING", 'RATING="Konduktor C2"' in text) reopened = TraktorAdapter(work).track(t.id) check("comment2 round-trips through save", reopened.comment2 == "Konduktor C2" and reopened.rating == t.rating) # Clearing it removes the attribute entirely. a2 = TraktorAdapter(work) a2.set_track_metadata(t.id, {"comment2": ""}) a2.save() check("clearing comment2 drops the attribute", 'RATING="Konduktor C2"' not in work.read_text(encoding="utf-8") and TraktorAdapter(work).track(t.id).comment2 is None) # ---- analysed grid vs plain replace -------------------------------------- print("== set_analysed_grid writes Traktor's own shape, replace_grid does not ==") with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) tid = next(t.id for t in adapter.tracks if t.grid_marker_count) cues = adapter.replace_grid(tid, [(1.0, 128.0)]) check("replace_grid sets exactly the markers given", len(cues.grid_markers) == 1) check("replace_grid creates no companion cue", cues.grid_markers[0].companion is None) cues = adapter.set_analysed_grid(tid, [(1.0, 128.0)]) check("set_analysed_grid pairs the marker with a companion", cues.grid_markers[0].companion is not None) # ---- replace_cues: a pushed track brought up to date ------------------------ print("== replace_cues makes the prep exactly the given one ==") with tempfile.TemporaryDirectory() as d: from konduktor.core.model import CuePoint, GridMarker, TrackCues # noqa: E402 work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) # A real entry carrying a grid WITH its white companion, hot cues and a lock. tid = next(t.id for t in adapter.tracks if t.grid_marker_count == 1 and t.hotcue_count >= 2 and adapter.track_cues(t.id).grid_markers[0].companion is not None) want = TrackCues( grid_markers=[GridMarker(start=0.25, bpm=124.0)], grid_locked=False, cues=[CuePoint(start=4.0, length=0.0, slot=2, name="Drop"), CuePoint(start=8.0, length=2.0, slot=3, type="loop"), CuePoint(start=12.0, length=0.0, role="memory", name="Mem")]) got = adapter.replace_cues(tid, want) check("the grid is exactly the new one, no companion invented", [(m.start, m.bpm, m.companion) for m in got.grid_markers] == [(0.25, 124.0, None)], str(got.grid_markers)) check("only the given cues remain, on their pads, the memory cue as one", sorted((c.slot, c.role, c.name) for c in got.cues if c.slot is not None) == [(2, "hotcue", "Drop"), (3, "hotcue", None)] and [c.name for c in got.cues if c.role == "memory"] == ["Mem"], str(got.cues)) again = adapter.replace_cues(tid, want) check("replacing with the same prep is stable", [(c.slot, c.start, c.role) for c in again.cues] == [(c.slot, c.start, c.role) for c in got.cues]) # ---- remap rebuilds the index (track ids change) -------------------------- print("== a path remap rebuilds the projection, because track ids change ==") with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) # Use the adapter's own suggestion: the remap matches RESOLVED OS paths, # which is not the same string as Track.filepath (a display path). prefix = adapter.path_prefix_suggestions()["primary"] matched = { t.id for t in adapter.tracks if (ap := adapter.audio_path(t.id)) and str(ap).startswith(prefix) } old_id = next(iter(matched)) moved = adapter.remap_locations(PathMapping.make(prefix, "/Volumes/KonduktorTest")) n = len(moved) check("remap rewrote some locations", n > 0, str(n)) check("the old track id is gone from the index", adapter.track(old_id) is None) # Export sets follow ids through a remap with exactly this mapping. check("it reports where each track id went", old_id in moved and adapter.track(moved[old_id]) is not None) check("the index still holds every track", len(adapter.tracks) == 8485) # ---- place_cues takes the generic spec ------------------------------------ print("== batch cue placement takes a typed spec ==") with tempfile.TemporaryDirectory() as d: work = Path(d) / "collection.nml" shutil.copy2(REAL, work) adapter = TraktorAdapter(work) tid = next( t.id for t in adapter.tracks if len({c.slot for c in adapter.track_cues(t.id).cues if c.slot is not None}) < 6 ) used = {c.slot for c in adapter.track_cues(tid).cues if c.slot is not None} free = [s for s in range(8) if s not in used][:2] adapter.place_cues(tid, [AutoHotcue(slot=free[0], start=30.0, name="Drop")]) placed = next((c for c in adapter.track_cues(tid).cues if c.slot == free[0]), None) check("batch-placed cue exists with its name", placed is not None and placed.name == "Drop") print("== the counts in the table match the deck ==") # "Is this a cue?" is asked in two places — `to_track` for the library table and # `to_track_cues` for the deck — and they must give the same answer. They did # not: `to_track` counted the raw CUE_V2 list, which includes GRID MARKERS, so # every gridded track reported one cue too many and the "has cues: no" filter # could never match one. Checked across many tracks, not one, because the bug # only shows on a track that has a grid. mismatched = [] for t in adapter.tracks[:150]: tc = adapter.track_cues(t.id) if tc is None: continue if t.cue_count != len(tc.cues) or t.grid_marker_count != len(tc.grid_markers): mismatched.append( f"{t.title!r}: table {t.cue_count}/{t.grid_marker_count} " f"vs deck {len(tc.cues)}/{len(tc.grid_markers)}" ) check("cue and marker counts agree with the projected cues", not mismatched, "; ".join(mismatched[:3])) # The specific confusion, stated directly: a grid marker is not a cue. gridded = next((t for t in adapter.tracks if t.grid_marker_count > 0), None) check("a track with a grid exists to test against", gridded is not None) if gridded is not None: cues = adapter.track_cues(gridded.id) check("no grid marker is projected as a cue", all(c.type != "grid" for c in cues.cues) and gridded.cue_count == len(cues.cues)) print("== track colour ==") # `INFO@COLOR` 1-7, measured in Traktor 4.5 (kit T1): Red ... Magenta, menu order. from konduktor.adapters.traktor import projection, track_palette # noqa: E402 _entry = next(e for e in adapter._store.iter_entries() if e.info is not None) _was = _entry.info.color _seen = [] for _code in (None, 0, 1, 4, 7, 8): _entry.info.color = _code _t = projection.to_track(_entry) _seen.append((_t.color, _t.color_hex)) _entry.info.color = _was check("Traktor's track colours project by name + display RGB (none for absent/0/unknown)", _seen == [(None, None), (None, None), ("red", "#FB413E"), ("green", "#52FA52"), ("pink", "#FA51EB"), (None, None)], str(_seen)) check("Traktor offers seven colours, Violet as purple and Magenta as pink", [s.color for s in adapter.capabilities().tracks.colors] == ["red", "orange", "yellow", "green", "blue", "purple", "pink"]) check("aqua (rekordbox's) is stored as Traktor's Blue", track_palette.code_for("aqua") == 5) print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0)