mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
1396 lines
64 KiB
Python
1396 lines
64 KiB
Python
"""Regression guard for save fidelity — the Traktor adapter's byte contract.
|
|
|
|
This is deliberately a TRAKTOR test: it constructs the store directly and
|
|
asserts on rendered bytes, which is exactly the level the guarantee lives at.
|
|
The generic layer above it is covered by test_traktor_adapter.py.
|
|
|
|
This is the test that would have caught the lxml reformatting bug. It asserts
|
|
two invariants against a COPY of the real collection:
|
|
|
|
A. NO-OP SAVE IS BYTE-IDENTICAL.
|
|
Loading and saving with zero edits must reproduce the file exactly. Any
|
|
serialization change (lxml, a different render pipeline, dropped
|
|
float-format/layout post-processing) breaks this immediately.
|
|
|
|
B. AN EDIT IS FULLY LOCALIZED.
|
|
Editing one playlist must change ONLY that playlist's block. Everything
|
|
else in the file — other playlists, folders, smart playlists, and the
|
|
entire COLLECTION — must stay byte-for-byte identical.
|
|
|
|
Run: `python test_save_fidelity.py` in the backend venv (see run_tests.sh).
|
|
"""
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
from types import SimpleNamespace
|
|
import warnings
|
|
from pathlib import Path
|
|
|
|
warnings.filterwarnings("ignore")
|
|
|
|
# Isolate version-history commits (triggered by every save()) to a throwaway dir
|
|
# so the tests never touch the real app-data dir. Set before importing konduktor.
|
|
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-appdata-")
|
|
|
|
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
|
|
|
from konduktor.adapters.traktor.store import PlaylistError, TraktorStore # noqa: E402
|
|
|
|
failed = 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
|
|
|
|
|
|
def playlist_block_span(data: bytes, uuid: str):
|
|
"""Byte span of a playlist's <PLAYLIST …UUID="…">…</PLAYLIST> block."""
|
|
i = data.find(f'UUID="{uuid}"'.encode())
|
|
start = data.rfind(b"<PLAYLIST ", 0, i)
|
|
end = data.find(b"</PLAYLIST>", i) + len(b"</PLAYLIST>")
|
|
return start, end
|
|
|
|
|
|
def _raises_playlist(fn) -> bool:
|
|
try:
|
|
fn()
|
|
except PlaylistError:
|
|
return True
|
|
return False
|
|
|
|
|
|
def _raises_any(fn) -> bool:
|
|
try:
|
|
fn()
|
|
except Exception:
|
|
return True
|
|
return False
|
|
|
|
|
|
def tag_lines(b: bytes) -> list[str]:
|
|
return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines()
|
|
|
|
|
|
def diff_count(a: bytes, b: bytes) -> int:
|
|
import difflib
|
|
|
|
la, lb = tag_lines(a), tag_lines(b)
|
|
return sum(
|
|
1
|
|
for d in difflib.unified_diff(la, lb, n=0)
|
|
if d[:1] in "+-" and not d.startswith(("+++", "---"))
|
|
)
|
|
|
|
|
|
# ---- Invariant A: no-op save is byte-identical ------------------------
|
|
print("== A. no-op save is byte-identical ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
before = work.read_bytes()
|
|
store = TraktorStore(work)
|
|
store.save() # no edits
|
|
after = work.read_bytes()
|
|
check("whole file identical after no-op save", before == after)
|
|
if before != after:
|
|
for i, (x, y) in enumerate(zip(before, after)):
|
|
if x != y:
|
|
check.detail = i
|
|
print(f" first byte diff @ {i}")
|
|
print(" before:", before[max(0, i - 50) : i + 50])
|
|
print(" after :", after[max(0, i - 50) : i + 50])
|
|
break
|
|
|
|
# ---- Invariant B: an edit is fully localized --------------------------
|
|
print("== B. edit touches only the edited playlist ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
|
|
store = TraktorStore(work)
|
|
|
|
def walk(n):
|
|
yield n
|
|
if n.subnodes:
|
|
for c in n.subnodes.node:
|
|
yield from walk(c)
|
|
|
|
target = next(
|
|
n for n in walk(store._root()) if n.playlist and n.playlist.uuid and len(n.playlist.entry or []) >= 5
|
|
)
|
|
uuid = target.playlist.uuid
|
|
keys = store.entry_keys(uuid)
|
|
|
|
store.set_entries(uuid, store.entries_for(list(reversed(keys))))
|
|
store.save()
|
|
edited = work.read_bytes()
|
|
|
|
check("file actually changed", original != edited)
|
|
|
|
# Blank out the edited playlist's block in both; the remainder must match.
|
|
os_, oe = playlist_block_span(original, uuid)
|
|
es_, ee = playlist_block_span(edited, uuid)
|
|
rest_original = original[:os_] + b"@@BLOCK@@" + original[oe:]
|
|
rest_edited = edited[:es_] + b"@@BLOCK@@" + edited[ee:]
|
|
check(
|
|
"everything outside the edited playlist is byte-identical",
|
|
rest_original == rest_edited,
|
|
)
|
|
|
|
# A pure reorder must preserve the exact set of lines in the block (only
|
|
# their order changes). If the block were reformatted, the multiset differs.
|
|
before_lines = sorted(tag_lines(original[os_:oe]))
|
|
after_lines = sorted(tag_lines(edited[es_:ee]))
|
|
check(
|
|
"edited block is a pure reorder (line multiset unchanged, no reformat)",
|
|
before_lines == after_lines,
|
|
)
|
|
n = diff_count(original[os_:oe], edited[es_:ee])
|
|
print(f" edited-block changed lines: {n} (reordered {len(keys)} entries)")
|
|
|
|
# ---- Invariant C: a track-metadata edit is fully localized -------------
|
|
print("== C. track metadata edit touches only that track's ENTRY ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
|
|
store = TraktorStore(work)
|
|
# pick the first track that has a resolvable primary key
|
|
entry = store._nml.collection.entry[0]
|
|
loc = entry.location
|
|
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
|
|
|
store.set_track_metadata(track_id, {"genre": "KONDUKTOR-FIDELITY-TEST", "rating": 4})
|
|
store.save()
|
|
edited = work.read_bytes()
|
|
|
|
check("file actually changed", original != edited)
|
|
|
|
# The edited ENTRY's <INFO> block is where the change lands. Blank out the
|
|
# whole entry span in both and require the remainder to be byte-identical.
|
|
def entry_span(data: bytes, file_name: str):
|
|
marker = f'FILE="{file_name}"'.encode()
|
|
i = data.find(marker)
|
|
start = data.rfind(b"<ENTRY ", 0, i)
|
|
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
|
return start, end
|
|
|
|
os_, oe = entry_span(original, loc.file)
|
|
es_, ee = entry_span(edited, loc.file)
|
|
check(
|
|
"everything outside the edited track's ENTRY is byte-identical",
|
|
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
|
)
|
|
n = diff_count(original[os_:oe], edited[es_:ee])
|
|
check("edited ENTRY diff is tiny (<= 6 tag-lines)", n <= 6, f"got {n}")
|
|
print(f" edited-ENTRY changed tag-lines: {n}")
|
|
|
|
# Re-parses and the edit persisted.
|
|
from traktor_nml_utils import TraktorCollection
|
|
|
|
reparsed = TraktorCollection(path=work)
|
|
e0 = reparsed.nml.collection.entry[0]
|
|
check("re-parses + genre persisted", e0.info.genre == "KONDUKTOR-FIDELITY-TEST")
|
|
check("rating persisted (4 stars => RANKING 204)", e0.info.ranking == 204)
|
|
|
|
# ---- Invariant D: a hotcue edit is fully localized ---------------------
|
|
print("== D. hotcue create touches only that track's ENTRY ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
|
|
store = TraktorStore(work)
|
|
entry = store._nml.collection.entry[0]
|
|
loc = entry.location
|
|
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
|
|
|
# Use a free slot so we exercise the create path (not overwrite an existing).
|
|
used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None}
|
|
slot = next(s for s in range(8) if s not in used)
|
|
store.set_hotcue(track_id, slot, 42.5, 0)
|
|
store.save()
|
|
edited = work.read_bytes()
|
|
|
|
check("file actually changed", original != edited)
|
|
|
|
def entry_span(data: bytes, file_name: str):
|
|
marker = f'FILE="{file_name}"'.encode()
|
|
i = data.find(marker)
|
|
start = data.rfind(b"<ENTRY ", 0, i)
|
|
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
|
return start, end
|
|
|
|
os_, oe = entry_span(original, loc.file)
|
|
es_, ee = entry_span(edited, loc.file)
|
|
check(
|
|
"everything outside the edited track's ENTRY is byte-identical",
|
|
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
|
)
|
|
n = diff_count(original[os_:oe], edited[es_:ee])
|
|
check("edited ENTRY diff is tiny (<= 3 tag-lines)", n <= 3, f"got {n}")
|
|
|
|
from traktor_nml_utils import TraktorCollection
|
|
|
|
reparsed = TraktorCollection(path=work)
|
|
e0 = reparsed.nml.collection.entry[0]
|
|
new_cue = next((c for c in (e0.cue_v2 or []) if c.hotcue == slot), None)
|
|
check("re-parses + hotcue persisted", new_cue is not None)
|
|
check("hotcue START stored in ms", new_cue is not None and abs(new_cue.start - 42500.0) < 1)
|
|
|
|
# Create then delete must round-trip back to a byte-identical file.
|
|
store2 = TraktorStore(work) # reload the edited file
|
|
store2.delete_hotcue(track_id, slot)
|
|
store2.save()
|
|
check("create+delete round-trips to the original bytes", work.read_bytes() == original)
|
|
|
|
# ---- Invariant E: a beatgrid edit is fully localized -------------------
|
|
print("== E. grid marker edit touches only that track's ENTRY ==")
|
|
from konduktor.adapters.traktor import beatgrid as bg # noqa: E402
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
|
|
store = TraktorStore(work)
|
|
|
|
def _key(e):
|
|
loc = e.location
|
|
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else ""
|
|
|
|
# An entry with a tempo and exactly ONE marker whose companion (if any) sits
|
|
# at an EXACTLY equal START. That predicate is load-bearing: a companion a
|
|
# fraction of a ms off would be normalised to exact by the first move, so the
|
|
# byte-revert below would fail through no fault of the code.
|
|
def _clean_single(e):
|
|
ms = bg.grid_markers(e)
|
|
if not (e.tempo and len(ms) == 1):
|
|
return False
|
|
comp = bg.companions(e).get(0)
|
|
return comp is None or comp.start == ms[0].start
|
|
|
|
entry = next(e for e in store._nml.collection.entry if _clean_single(e))
|
|
loc = entry.location
|
|
track_id = _key(entry)
|
|
orig_bpm = entry.tempo.bpm
|
|
orig_anchor_ms = bg.grid_markers(entry)[0].start
|
|
comp_slot = (
|
|
bg.companions(entry)[0].hotcue if 0 in bg.companions(entry) else None
|
|
)
|
|
|
|
store.set_grid_marker_bpm(track_id, 0, orig_bpm / 2)
|
|
store.move_grid_marker(track_id, 0, 1.5)
|
|
store.save()
|
|
edited = work.read_bytes()
|
|
|
|
check("file actually changed", original != edited)
|
|
|
|
def entry_span(data: bytes, file_name: str):
|
|
marker = f'FILE="{file_name}"'.encode()
|
|
i = data.find(marker)
|
|
start = data.rfind(b"<ENTRY ", 0, i)
|
|
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
|
return start, end
|
|
|
|
os_, oe = entry_span(original, loc.file)
|
|
es_, ee = entry_span(edited, loc.file)
|
|
check(
|
|
"everything outside the edited track's ENTRY is byte-identical",
|
|
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
|
)
|
|
|
|
from traktor_nml_utils import TraktorCollection
|
|
|
|
reparsed = TraktorCollection(path=work)
|
|
e0 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id)
|
|
markers = bg.grid_markers(e0)
|
|
m = store._grid_marker(e0)
|
|
check("tempo BPM halved + persisted", abs(e0.tempo.bpm - orig_bpm / 2) < 1e-3)
|
|
check("grid marker BPM matches tempo", m is not None and abs(m.grid.bpm - orig_bpm / 2) < 1e-3)
|
|
check("grid anchor moved to 1.5s (1500 ms)", m is not None and abs(m.start - 1500.0) < 1)
|
|
# A move must reposition the grid, never fork it into a flexible one.
|
|
check("still exactly one grid marker", len(markers) == 1, str(len(markers)))
|
|
# _grid_marker is the first marker BY START, not by document order.
|
|
check("_grid_marker == first marker by start", m is markers[0])
|
|
if comp_slot is not None:
|
|
comp = bg.companions(e0).get(0)
|
|
check("companion dragged along with its marker",
|
|
comp is not None and abs(comp.start - 1500.0) < 1, str(comp.start if comp else None))
|
|
check("companion kept its hotcue slot", comp is not None and comp.hotcue == comp_slot)
|
|
|
|
# Reverting BPM + position round-trips to the original bytes.
|
|
store2 = TraktorStore(work)
|
|
store2.set_grid_marker_bpm(track_id, 0, orig_bpm)
|
|
store2.move_grid_marker(track_id, 0, orig_anchor_ms / 1000.0)
|
|
store2.save()
|
|
check("revert BPM + position round-trips to original bytes", work.read_bytes() == original)
|
|
|
|
# ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
|
|
print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
from traktor_nml_utils import TraktorCollection
|
|
|
|
# The store is the NATIVE layer, so its specs carry Traktor's own cue TYPE
|
|
# integer. The generic AutoHotcue (string types) is translated by the adapter
|
|
# before it gets here — test_traktor_adapter.py covers that path.
|
|
def spec(slot, start, name, type=0, length=0.0):
|
|
return SimpleNamespace(slot=slot, start=start, name=name, type=type, length=length)
|
|
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
|
|
store = TraktorStore(work)
|
|
entry = store._nml.collection.entry[0]
|
|
loc = entry.location
|
|
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
|
|
|
def entry_span(data: bytes, file_name: str):
|
|
marker = f'FILE="{file_name}"'.encode()
|
|
i = data.find(marker)
|
|
start = data.rfind(b"<ENTRY ", 0, i)
|
|
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
|
return start, end
|
|
|
|
# Establish a hand-placed hotcue as the baseline the batch must NOT overwrite.
|
|
used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
|
|
hand_slot = next(s for s in range(8) if s not in used)
|
|
store.set_hotcue(track_id, hand_slot, 12.0, 0, name="HAND-PLACED")
|
|
store.save()
|
|
original = work.read_bytes()
|
|
|
|
# Batch: one spec targets the occupied slot (must be skipped), two fill free slots.
|
|
store2 = TraktorStore(work)
|
|
e2 = store2._nml.collection.entry[0]
|
|
now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
|
|
free = [s for s in range(8) if s not in now_used][:2]
|
|
specs = [spec(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")]
|
|
specs += [spec(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)]
|
|
store2.place_hotcues(track_id, specs)
|
|
store2.save()
|
|
edited = work.read_bytes()
|
|
|
|
check("file actually changed", original != edited)
|
|
|
|
os_, oe = entry_span(original, loc.file)
|
|
es_, ee = entry_span(edited, loc.file)
|
|
check(
|
|
"everything outside the edited track's ENTRY is byte-identical",
|
|
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
|
)
|
|
n = diff_count(original[os_:oe], edited[es_:ee])
|
|
check(f"edited ENTRY diff is small (<= 6 tag-lines for {len(free)} cues)", n <= 6, f"got {n}")
|
|
|
|
reparsed = TraktorCollection(path=work)
|
|
e0 = reparsed.nml.collection.entry[0]
|
|
hand = next((c for c in (e0.cue_v2 or []) if c.hotcue == hand_slot), None)
|
|
check("hand-placed hotcue NOT overwritten (position)", hand is not None and abs(hand.start - 12000.0) < 1)
|
|
check("hand-placed hotcue NOT overwritten (name)", hand is not None and hand.name == "HAND-PLACED")
|
|
for i, s in enumerate(free):
|
|
c = next((c for c in (e0.cue_v2 or []) if c.hotcue == s), None)
|
|
check(f"auto hotcue slot {s} created", c is not None)
|
|
check(f"auto hotcue slot {s} name round-trips", c is not None and c.name == f"Auto {i}")
|
|
check(
|
|
f"auto hotcue slot {s} START in ms",
|
|
c is not None and abs(c.start - (30000.0 + i * 10000)) < 1,
|
|
)
|
|
|
|
# ---- Invariant G: moved -------------------------------------------------
|
|
# Auto Hotcues' placement logic is tested in test_auto_hotcues.py, which also
|
|
# covers its structure analysis and its route.
|
|
|
|
# ---- Invariant H: path write-back is localized + round-trips -----------
|
|
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")
|
|
from collections import Counter # noqa: E402
|
|
|
|
from konduktor.adapters.traktor.locations import resolve_path # noqa: E402
|
|
from konduktor.core.pathmap import PathMapping # noqa: E402
|
|
from konduktor.adapters.traktor.locations import os_path_to_location # noqa: E402
|
|
from traktor_nml_utils import TraktorCollection # noqa: E402
|
|
|
|
|
|
def _key(loc):
|
|
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
|
|
|
|
|
def _entry_span_by_file(data: bytes, file_name: str):
|
|
marker = f'FILE="{file_name}"'.encode()
|
|
i = data.find(marker)
|
|
start = data.rfind(b"<ENTRY ", 0, i)
|
|
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
|
return start, end
|
|
|
|
|
|
# H1: a track NOT in any playlist -> only its own <ENTRY> changes; revert round-trips.
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
|
|
store = TraktorStore(work)
|
|
pl_keys = {
|
|
k
|
|
for n in store._iter_nodes(store._root())
|
|
if n.playlist
|
|
for k in store._entry_keys_of(n.playlist)
|
|
}
|
|
file_counts = Counter(
|
|
e.location.file for e in store._nml.collection.entry if e.location and e.location.file
|
|
)
|
|
target = next(
|
|
e
|
|
for e in store._nml.collection.entry
|
|
if e.location
|
|
and _key(e.location) not in pl_keys
|
|
and file_counts[e.location.file] == 1 # unique filename → clean span masking
|
|
)
|
|
loc = target.location
|
|
old_file = loc.file
|
|
from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file))
|
|
to_prefix = "/Volumes/KONDUKTOR_TEST_H1/remapped__unique__one.mp3"
|
|
|
|
n = len(store.remap_locations(PathMapping.make(from_prefix, to_prefix)))
|
|
store.save()
|
|
edited = work.read_bytes()
|
|
|
|
check("H1: exactly one track rewritten", n == 1, f"got {n}")
|
|
check("H1: file actually changed", original != edited)
|
|
|
|
os_, oe = _entry_span_by_file(original, old_file)
|
|
es_, ee = _entry_span_by_file(edited, "remapped__unique__one.mp3")
|
|
check(
|
|
"H1: everything outside the moved ENTRY is byte-identical",
|
|
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
|
)
|
|
|
|
reparsed = TraktorCollection(path=work)
|
|
moved = next(
|
|
e
|
|
for e in reparsed.nml.collection.entry
|
|
if e.location and e.location.file == "remapped__unique__one.mp3"
|
|
)
|
|
check("H1: moved ENTRY has the new VOLUME", moved.location.volume == "KONDUKTOR_TEST_H1")
|
|
|
|
# Reverting (to -> from) round-trips to the original bytes exactly.
|
|
store2 = TraktorStore(work)
|
|
store2.remap_locations(PathMapping.make(to_prefix, from_prefix))
|
|
store2.save()
|
|
check("H1: revert round-trips to original bytes", work.read_bytes() == original)
|
|
|
|
# H2: a track that IS in a playlist -> its PRIMARYKEY is rewritten too.
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
|
|
store = TraktorStore(work)
|
|
# A collection entry whose key appears in at least one playlist.
|
|
pl_keys = {
|
|
k
|
|
for node in store._iter_nodes(store._root())
|
|
if node.playlist
|
|
for k in store._entry_keys_of(node.playlist)
|
|
}
|
|
target = next(
|
|
e for e in store._nml.collection.entry if e.location and _key(e.location) in pl_keys
|
|
)
|
|
loc = target.location
|
|
old_key = _key(loc)
|
|
from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file))
|
|
to_prefix = "/Volumes/KONDUKTOR_TEST_H2/remapped__playlist__one.mp3"
|
|
new_key = "".join(os_path_to_location(Path(to_prefix)))
|
|
|
|
n = len(store.remap_locations(PathMapping.make(from_prefix, to_prefix)))
|
|
store.save()
|
|
|
|
check("H2: at least one track rewritten", n >= 1)
|
|
|
|
reparsed = TraktorCollection(path=work)
|
|
moved = next(
|
|
(
|
|
e
|
|
for e in reparsed.nml.collection.entry
|
|
if e.location and e.location.file == "remapped__playlist__one.mp3"
|
|
),
|
|
None,
|
|
)
|
|
check("H2: collection ENTRY location rewritten", moved is not None)
|
|
|
|
store3 = TraktorStore(work)
|
|
all_pl_keys = {
|
|
k
|
|
for node in store3._iter_nodes(store3._root())
|
|
if node.playlist
|
|
for k in store3._entry_keys_of(node.playlist)
|
|
}
|
|
check("H2: old playlist PRIMARYKEY gone", old_key not in all_pl_keys)
|
|
check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys)
|
|
|
|
# H3: a remap re-keys the entry index, so the track is still reachable by its
|
|
# NEW id before any save — and a tag edit made BEFORE the remap still reaches
|
|
# the file on save (it was silently dropped when the index kept the old key).
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
|
|
store = TraktorStore(work)
|
|
target = next(e for e in store._nml.collection.entry if e.location and e.location.file)
|
|
old_key = _key(target.location)
|
|
from_prefix = str(resolve_path(target.location.volume, target.location.dir, target.location.file))
|
|
to_prefix = "/Volumes/KONDUKTOR_TEST_H3/remapped__rekey__one.mp3"
|
|
new_key = "".join(os_path_to_location(Path(to_prefix)))
|
|
|
|
store.set_track_metadata(old_key, {"genre": "H3 before remap"})
|
|
store.set_track_art(old_key, b"\xff\xd8H3", "image/jpeg")
|
|
moved = store.remap_locations(PathMapping.make(from_prefix, to_prefix))
|
|
check("H3: the remap reports the new id", moved.get(old_key) == new_key, str(moved))
|
|
check("H3: the index finds the ENTRY by its new id", store._entry_by_key.get(new_key) is target)
|
|
check("H3: …and no longer by its old one", old_key not in store._entry_by_key)
|
|
check("H3: staged cover art follows the track", new_key in store._track_art and old_key not in store._track_art)
|
|
|
|
try:
|
|
store.set_track_metadata(new_key, {"label": "H3 after remap"})
|
|
check("H3: an edit by the new id works before saving", target.info.label == "H3 after remap")
|
|
except PlaylistError as exc:
|
|
check("H3: an edit by the new id works before saving", False, str(exc))
|
|
|
|
# The tag sync must visit the moved track with BOTH edits. Stub the file
|
|
# side: this is about which tracks it reaches, not about mutagen.
|
|
import konduktor.core.audio_tags as _tags # noqa: E402
|
|
|
|
written = []
|
|
real_write_tags, real_write_cover = _tags.write_tags, _tags.write_cover
|
|
ok = SimpleNamespace(ok=True, status="ok", detail=None)
|
|
_tags.write_tags = lambda path, meta, **k: (written.append(("tags", meta)), ok)[1]
|
|
_tags.write_cover = lambda path, data, mime: (written.append(("cover", data)), ok)[1]
|
|
store._resolve = lambda loc: Path(to_prefix)
|
|
try:
|
|
results = store._sync_file_tags()
|
|
finally:
|
|
_tags.write_tags, _tags.write_cover = real_write_tags, real_write_cover
|
|
tag_meta = next((m for kind, m in written if kind == "tags"), {})
|
|
check("H3: the file-tag sync reaches the remapped track",
|
|
[r.track_id for r in results] == [new_key, new_key], str([r.track_id for r in results]))
|
|
check("H3: …with the edit made before the remap AND the one after",
|
|
tag_meta.get("genre") == "H3 before remap" and tag_meta.get("label") == "H3 after remap",
|
|
str(tag_meta))
|
|
check("H3: …and the staged cover art", ("cover", b"\xff\xd8H3") in written)
|
|
|
|
# H4: a remap that would give two ENTRYs one primary key is refused with nothing
|
|
# changed; the preview says so first. A chain (one track onto another's OLD
|
|
# path while that one moves on) is not a clash, and each track's staged art and
|
|
# edits must follow IT, not the path.
|
|
from konduktor.core.adapter import InvalidCommand # noqa: E402
|
|
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
store = TraktorStore(work)
|
|
entries = [e for e in store._nml.collection.entry if e.location and e.location.file]
|
|
e1, e2, e3 = entries[0], entries[1], entries[2]
|
|
|
|
def put(e, path):
|
|
e.location.volume, e.location.dir, e.location.file = os_path_to_location(Path(path))
|
|
|
|
def rekey(st):
|
|
st._entry_by_key = {st._key_of(e): e for e in st._nml.collection.entry if e.location}
|
|
|
|
# (a) onto a path a STAYING track already has — the realistic case: a folder
|
|
# copied to a new drive and both copies in the collection.
|
|
put(e1, "/Volumes/H4OLD/Music/same.mp3")
|
|
put(e2, "/Volumes/H4NEW/Music/same.mp3")
|
|
rekey(store)
|
|
before = store._render()
|
|
mapping = PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4NEW/Music")
|
|
preview = store.remap_preview(mapping)
|
|
check("H4: the preview reports the clash before anything is done",
|
|
preview["collisions"] == 1 and len(preview["collision_samples"]) == 1
|
|
and preview["collision_samples"][0].endswith("H4NEW/Music/same.mp3"), str(preview))
|
|
try:
|
|
store.remap_locations(mapping)
|
|
check("H4: a remap onto a staying track's path is refused", False, "it ran")
|
|
except PlaylistError as exc:
|
|
check("H4: a remap onto a staying track's path is refused", "nothing was changed" in str(exc), str(exc))
|
|
check("H4: …and nothing changed", store._render() == before and not store.dirty)
|
|
|
|
# (b) two DIFFERENTLY-keyed entries for one file — the boot disk spelt
|
|
# "Macintosh HD" and blank, both resolving to /Users/… — that the mapping
|
|
# sends to the same place.
|
|
put(e1, "/Users/h4/one.mp3")
|
|
e3.location.volume, e3.location.dir, e3.location.file = "", e1.location.dir, e1.location.file
|
|
put(e2, "/Volumes/H4OTHER/two.mp3")
|
|
rekey(store)
|
|
check("H4: (setup) two keys, one file",
|
|
store._key_of(e1) != store._key_of(e3)
|
|
and resolve_path(e1.location.volume, e1.location.dir, e1.location.file)
|
|
== resolve_path(e3.location.volume, e3.location.dir, e3.location.file))
|
|
mapping = PathMapping.make("/Users/h4", "/Volumes/H4DEST")
|
|
check("H4: two entries with different keys landing on one path clash",
|
|
store.remap_preview(mapping)["collisions"] == 1, str(store.remap_preview(mapping)))
|
|
before = store._render()
|
|
try:
|
|
store.remap_locations(mapping)
|
|
check("H4: …and that remap is refused", False, "it ran")
|
|
except PlaylistError:
|
|
check("H4: …and that remap is refused, unchanged", store._render() == before)
|
|
put(e3, "/Volumes/H4OTHER/unrelated.mp3")
|
|
|
|
# (c) a duplicate the collection ALREADY had moves as it was — refusing it
|
|
# would make a library with one duplicate impossible to move at all.
|
|
put(e1, "/Volumes/H4OLD/Music/same.mp3")
|
|
put(e2, "/Volumes/H4OLD/Music/same.mp3") # e1 and e2 now share a key
|
|
rekey(store)
|
|
mapping = PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4MOVED/Music")
|
|
check("H4: an existing duplicate is not a new clash", store.remap_preview(mapping)["collisions"] == 0)
|
|
moved = store.remap_locations(mapping)
|
|
check("H4: …and the pair moves together", len(moved) == 1 and store._key_of(e1) == store._key_of(e2))
|
|
|
|
# (d) a chain from a nested prefix: x/f -> x/sub/f while x/sub/f -> x/sub/sub/f.
|
|
put(e1, "/Volumes/H4C/x/f.mp3")
|
|
put(e2, "/Volumes/H4C/x/sub/f.mp3")
|
|
rekey(store)
|
|
k1, k2 = store._key_of(e1), store._key_of(e2)
|
|
store.set_track_metadata(k1, {"genre": "chain one"})
|
|
store.set_track_metadata(k2, {"genre": "chain two"})
|
|
store.set_track_art(k1, b"art-one", "image/jpeg")
|
|
store.set_track_art(k2, b"art-two", "image/jpeg")
|
|
mapping = PathMapping.make("/Volumes/H4C/x", "/Volumes/H4C/x/sub")
|
|
check("H4: a chain is not a clash", store.remap_preview(mapping)["collisions"] == 0)
|
|
moved = store.remap_locations(mapping)
|
|
n1, n2 = store._key_of(e1), store._key_of(e2)
|
|
check("H4: the first track takes the second's old path", n1 == k2 and moved[k1] == n1, f"{moved}")
|
|
check("H4: the index finds each track at its new id",
|
|
store._entry_by_key.get(n1) is e1 and store._entry_by_key.get(n2) is e2)
|
|
check("H4: each track's staged art follows the TRACK",
|
|
store._track_art.get(n1, (b"",))[0] == b"art-one" and store._track_art.get(n2, (b"",))[0] == b"art-two",
|
|
str({k: v[0] for k, v in store._track_art.items()}))
|
|
check("H4: …and so do its edits",
|
|
store._journal.fields_for(n1) == {"genre"} and store._journal.fields_for(n2) == {"genre"}
|
|
and store._entry_field_value(store._entry_by_key[n1], "genre") == "chain one")
|
|
j1 = [c for c in store._journal.changes if c.target == n1 and c.scope == "track"]
|
|
check("H4: …exactly one edit each, not both on one track", len(j1) == 1, str(j1))
|
|
|
|
# Through the adapter the refusal is the generic InvalidCommand (-> HTTP 400).
|
|
shutil.copy2(REAL, work)
|
|
ad = TraktorAdapter(work)
|
|
a1, a2 = [e for e in ad.store._nml.collection.entry if e.location and e.location.file][:2]
|
|
put(a1, "/Volumes/H4OLD/Music/same.mp3")
|
|
put(a2, "/Volumes/H4NEW/Music/same.mp3")
|
|
rekey(ad.store)
|
|
try:
|
|
ad.remap_locations(PathMapping.make("/Volumes/H4OLD/Music", "/Volumes/H4NEW/Music"))
|
|
check("H4: the adapter refuses with InvalidCommand", False, "it ran")
|
|
except InvalidCommand:
|
|
check("H4: the adapter refuses with InvalidCommand", True)
|
|
|
|
|
|
# ---- Invariant I: flexible (multi-marker) beatgrids round-trip ---------
|
|
print("== I. flexible beatgrid: add/move/delete markers, localized + reversible ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
|
|
def _key(e):
|
|
loc = e.location
|
|
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else ""
|
|
|
|
def entry_span(data: bytes, file_name: str):
|
|
marker = f'FILE="{file_name}"'.encode()
|
|
i = data.find(marker)
|
|
st = data.rfind(b"<ENTRY ", 0, i)
|
|
en = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
|
return st, en
|
|
|
|
# Synthesize the flexible grid rather than relying on the handful of real
|
|
# ones: those are the user's own data and could change at any time.
|
|
store = TraktorStore(work)
|
|
entry = next(
|
|
e for e in store._nml.collection.entry
|
|
if e.tempo and len(bg.grid_markers(e)) == 1
|
|
and (bg.companions(e).get(0) is None or bg.companions(e)[0].start == bg.grid_markers(e)[0].start)
|
|
)
|
|
loc = entry.location
|
|
track_id = _key(entry)
|
|
_m0 = bg.grid_markers(entry)[0]
|
|
m0_start, m0_bpm = _m0.start, _m0.grid.bpm
|
|
orig_tempo = entry.tempo.bpm
|
|
|
|
store.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99)
|
|
store.save()
|
|
two = work.read_bytes()
|
|
|
|
reparsed = TraktorCollection(path=work)
|
|
e1 = next(e for e in reparsed.nml.collection.entry if e.location and _key(e) == track_id)
|
|
ms = bg.grid_markers(e1)
|
|
check("I: second marker added", len(ms) == 2, str(len(ms)))
|
|
check("I: markers ascending by START", ms[0].start < ms[1].start)
|
|
check("I: second marker kept its own BPM", abs(ms[1].grid.bpm - m0_bpm * 0.99) < 1e-3)
|
|
check("I: TEMPO still mirrors the FIRST marker", abs(e1.tempo.bpm - orig_tempo) < 1e-6,
|
|
f"{e1.tempo.bpm} vs {orig_tempo}")
|
|
check("I: CUE_V2 still ascending by START",
|
|
all((c.start or 0) <= (ms_ .start or 0) for c, ms_ in zip(e1.cue_v2, e1.cue_v2[1:])))
|
|
check("I: new GRID BPM rendered at 6 decimals",
|
|
f'<GRID BPM="{m0_bpm * 0.99:.6f}">'.encode() in two)
|
|
os_, oe = entry_span(original, loc.file)
|
|
es_, ee = entry_span(two, loc.file)
|
|
check("I: adding a marker is confined to that ENTRY",
|
|
original[:os_] + b"@@" + original[oe:] == two[:es_] + b"@@" + two[ee:])
|
|
|
|
# Removing it must return the file to its original bytes exactly.
|
|
store2 = TraktorStore(work)
|
|
store2.delete_grid_marker(track_id, 1)
|
|
store2.save()
|
|
check("I: deleting the added marker round-trips to original bytes",
|
|
work.read_bytes() == original)
|
|
|
|
# Moves clamp between neighbours rather than reordering the list.
|
|
store3 = TraktorStore(work)
|
|
store3.add_grid_marker(track_id, (m0_start + 60_000.0) / 1000.0, bpm=m0_bpm * 0.99)
|
|
store3.move_grid_marker(track_id, 0, (m0_start + 120_000.0) / 1000.0)
|
|
e3 = store3.model_entry(track_id)
|
|
ms3 = bg.grid_markers(e3)
|
|
check("I: move clamps below the next marker", ms3[0].start < ms3[1].start)
|
|
check("I: move never changes the marker count", len(ms3) == 2)
|
|
|
|
# delete_grid takes the companions with it and keeps TEMPO.
|
|
store3.delete_grid(track_id)
|
|
e3 = store3.model_entry(track_id)
|
|
whites = [c for c in (e3.cue_v2 or []) if c.color == "#FFFFFF" and getattr(c, "grid", None) is None]
|
|
check("I: delete_grid removes every marker", len(bg.grid_markers(e3)) == 0)
|
|
check("I: delete_grid leaves no companion debris", not whites, str(len(whites)))
|
|
check("I: delete_grid keeps TEMPO", e3.tempo is not None and e3.tempo.bpm == orig_tempo)
|
|
|
|
|
|
# ---- Invariant J: companion cues are ordinary, editable hotcues ---------
|
|
# Traktor 4 keeps a beatgrid without its white beat-1 cue, so the cue is not
|
|
# the grid's to protect: every hotcue command works on it, and none of them may
|
|
# touch the grid marker it happened to sit on.
|
|
print("== J. grid companion cues are editable, and editing one leaves the grid alone ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
|
|
def fresh():
|
|
st = TraktorStore(work)
|
|
e = next(e for e in st._nml.collection.entry if bg.companions(e).get(0) is not None)
|
|
tid = f"{e.location.volume or ''}{e.location.dir or ''}{e.location.file or ''}"
|
|
return st, tid, bg.companions(e)[0].hotcue, [(m.start, m.grid.bpm) for m in bg.grid_markers(e)]
|
|
|
|
for label, fn in [
|
|
("set_hotcue moves it", lambda st, tid, slot: st.set_hotcue(tid, slot, 5.0, 0)),
|
|
("set_hotcue_type retypes it", lambda st, tid, slot: st.set_hotcue_type(tid, slot, 1)),
|
|
("delete_hotcue deletes it", lambda st, tid, slot: st.delete_hotcue(tid, slot)),
|
|
]:
|
|
store, track_id, slot, grid_before = fresh()
|
|
try:
|
|
fn(store, track_id, slot)
|
|
ok = True
|
|
except PlaylistError as ex:
|
|
ok = False
|
|
check(f"J: {label}", False, str(ex))
|
|
if ok:
|
|
e = store.model_entry(track_id)
|
|
check(f"J: {label}", store.dirty is True)
|
|
check(f"J: …and the grid is unchanged ({label.split()[0]})",
|
|
[(m.start, m.grid.bpm) for m in bg.grid_markers(e)] == grid_before)
|
|
check(f"J: …and it is no longer the marker's companion ({label.split()[0]})",
|
|
0 not in bg.companions(e))
|
|
|
|
store, track_id, slot, _ = fresh()
|
|
from konduktor.adapters.traktor.projection import to_track_cues
|
|
proj = to_track_cues(store.model_entry(track_id))
|
|
comp_cue = next(c for c in proj.cues if c.slot == slot)
|
|
check("J: the projection offers it as editable",
|
|
comp_cue.editable is True and comp_cue.readonly_reason is None)
|
|
|
|
# Auto Hotcues treats it like any other occupied slot.
|
|
spec = type("S", (), {"slot": slot, "start": 42.0, "name": "X", "type": 0, "length": 0.0})()
|
|
store.place_hotcues(track_id, [spec])
|
|
e = store.model_entry(track_id)
|
|
check("J: place_hotcues leaves it alone without overwrite",
|
|
bg.companions(e).get(0) is not None)
|
|
store.place_hotcues(track_id, [spec], overwrite=True)
|
|
e = store.model_entry(track_id)
|
|
check("J: place_hotcues(overwrite) replaces it",
|
|
any(c.hotcue == slot and abs(c.start - 42_000.0) < 1 for c in (e.cue_v2 or [])))
|
|
|
|
# Deleting the grid still removes a companion that is still on its marker.
|
|
store, track_id, slot, _ = fresh()
|
|
store.delete_grid(track_id)
|
|
e = store.model_entry(track_id)
|
|
check("J: delete_grid frees the companion's hotcue slot",
|
|
not any(c.hotcue == slot for c in (e.cue_v2 or [])))
|
|
|
|
|
|
# ---- Invariant K: real flexible grids project correctly (read-only) ----
|
|
print("== K. genuine Traktor flexible grids read correctly ==")
|
|
_real = TraktorCollection(path=REAL).nml.collection.entry
|
|
_flex = [e for e in _real if len(bg.grid_markers(e)) > 1]
|
|
if not _flex:
|
|
print(" [SKIP] no flexible-grid entries in the reference collection")
|
|
else:
|
|
from konduktor.adapters.traktor import projection as _proj
|
|
|
|
ok_order = ok_tempo = ok_proj = ok_comp = True
|
|
for e in _flex:
|
|
ms = bg.grid_markers(e)
|
|
ok_order &= all(ms[i].start < ms[i + 1].start for i in range(len(ms) - 1))
|
|
if e.tempo and e.tempo.bpm:
|
|
ok_tempo &= abs(e.tempo.bpm - ms[0].grid.bpm) < 1e-6
|
|
tc = _proj.to_track_cues(e)
|
|
ok_proj &= len(tc.grid_markers) == len(ms) and all(
|
|
abs(g.bpm - m.grid.bpm) < 1e-9 and abs(g.start - (m.start or 0) / 1000.0) < 1e-9
|
|
for g, m in zip(tc.grid_markers, ms)
|
|
)
|
|
# A marker with no companion must project None, not raise.
|
|
comps = bg.companions(e)
|
|
ok_comp &= all(
|
|
(tc.grid_markers[i].companion is None) == (i not in comps) for i in range(len(ms))
|
|
)
|
|
print(f" ({len(_flex)} flexible entr{'y' if len(_flex) == 1 else 'ies'} checked)")
|
|
check("K: markers strictly ascending by START", ok_order)
|
|
check("K: TEMPO mirrors the first marker", ok_tempo)
|
|
check("K: every marker projects with its own BPM + position", ok_proj)
|
|
check("K: a marker without a companion projects None", ok_comp)
|
|
|
|
|
|
# ---- Invariant L: removing a track from the collection is localized ---------
|
|
print("== L. remove_entries drops the ENTRY and its playlist references, nothing else ==")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
store = TraktorStore(work)
|
|
original = store._render()
|
|
|
|
def pl_nodes(st):
|
|
return [n for n in st._iter_nodes(st._root()) if n.playlist is not None]
|
|
|
|
in_pl = {k for n in pl_nodes(store) for k in store._entry_keys_of(n.playlist)}
|
|
target = next(e for e in store._nml.collection.entry
|
|
if e.location and store._key_of(e) in in_pl)
|
|
key = store._key_of(target)
|
|
touched = {n.playlist.uuid for n in pl_nodes(store) if key in store._entry_keys_of(n.playlist)}
|
|
untouched = [n.playlist.uuid for n in pl_nodes(store) if n.playlist.uuid not in touched]
|
|
n_before = len(store._nml.collection.entry)
|
|
|
|
removed = store.remove_entries([key, "no/such/track.mp3"])
|
|
after = store._render()
|
|
check("L: exactly one ENTRY removed (an unknown id is ignored)", removed == 1, str(removed))
|
|
|
|
import difflib
|
|
plus = [d for d in difflib.unified_diff(tag_lines(original), tag_lines(after), n=0)
|
|
if d.startswith("+") and not d.startswith("+++")]
|
|
# Every ADDED line is a recount — the collection's or a touched playlist's.
|
|
# Nothing is rewritten, only removed.
|
|
check("L: the only added lines are ENTRIES recounts",
|
|
all("ENTRIES=" in d for d in plus) and len(plus) == 1 + len(touched), "\n".join(plus[:6]))
|
|
check("L: every other playlist is byte-identical",
|
|
all(original[slice(*playlist_block_span(original, u))] == after[slice(*playlist_block_span(after, u))]
|
|
for u in untouched))
|
|
|
|
check("L: the edit journal records a removal, not an edit",
|
|
store._journal.removed_tracks() == {key} and not store._journal.edited_tracks())
|
|
summary = store._journal.summary()
|
|
check("L: …and the history message says so", "removed 1 track from the collection" in summary.lower(), summary)
|
|
|
|
store.save()
|
|
re = TraktorStore(work)
|
|
keys = [re._key_of(e) for e in re._nml.collection.entry]
|
|
check("L: the track is gone from the collection", key not in keys)
|
|
check("L: <COLLECTION ENTRIES> matches the entries", re._nml.collection.entries == len(keys) == n_before - 1)
|
|
check("L: …and from every playlist", all(key not in re._entry_keys_of(n.playlist) for n in pl_nodes(re)))
|
|
check("L: every playlist's ENTRIES count matches",
|
|
all((n.playlist.entries or 0) == len(n.playlist.entry or []) for n in pl_nodes(re)))
|
|
|
|
|
|
# ---- Invariant M: dates cross in Traktor's own form -----------------------
|
|
# The projection turns Traktor's "YYYY/M/D" into ISO; everything that writes a
|
|
# date back must turn it round again, or the NML ends up holding a notation
|
|
# Traktor never writes.
|
|
print("== M. dates are written as Traktor's YYYY/M/D, tags get ISO ==")
|
|
from konduktor.adapters.traktor.projection import iso_date, traktor_date # noqa: E402
|
|
|
|
for given, want in [
|
|
("2021-03-04", "2021/3/4"), ("2021-12-25", "2021/12/25"), ("2021", "2021/1/1"),
|
|
("2021-07", "2021/7/1"), ("2021-03-04T10:20:30", "2021/3/4"), ("2021/03/04", "2021/3/4"),
|
|
("2021/3/4", "2021/3/4"), ("sometime", "sometime"), ("", None), (None, None),
|
|
]:
|
|
check(f"M: traktor_date({given!r}) == {want!r}", traktor_date(given) == want, repr(traktor_date(given)))
|
|
check("M: every date in the collection round-trips through ISO",
|
|
all(traktor_date(iso_date(v)) == v
|
|
for e in TraktorCollection(path=REAL).nml.collection.entry if e.info
|
|
for v in (e.info.release_date, e.info.import_date, e.info.last_played) if v))
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
store = TraktorStore(work)
|
|
target = next(e for e in store._nml.collection.entry
|
|
if e.location and e.info and e.info.release_date)
|
|
key = store._key_of(target)
|
|
original = store._render()
|
|
store.set_track_metadata(key, {"release_date": "2019-06-07"})
|
|
check("M: an ISO edit is stored as Traktor's form", target.info.release_date == "2019/6/7",
|
|
target.info.release_date)
|
|
check("M: …and the file tag is given ISO",
|
|
store._entry_field_value(target, "release_date") == "2019-06-07")
|
|
changed = [dl for dl in difflib.unified_diff(tag_lines(original), tag_lines(store._render()), n=0)
|
|
if dl[:1] in "+-" and dl[:3] not in ("+++", "---")]
|
|
check("M: only that ENTRY's INFO line changes", len(changed) == 2 and "RELEASE_DATE=\"2019/6/7\"" in changed[1],
|
|
"\n".join(changed[:4]))
|
|
|
|
new_id = store.add_entry(
|
|
SimpleNamespace(title="M dates", release_date="2020", import_date="2026-09-30"),
|
|
Path("/Volumes/KONDUKTOR_TEST_M/dates.mp3"),
|
|
)
|
|
info = store._entry_by_key[new_id].info
|
|
check("M: an added track's dates are Traktor's form",
|
|
(info.release_date, info.import_date) == ("2020/1/1", "2026/9/30"),
|
|
f"{info.release_date!r} {info.import_date!r}")
|
|
|
|
|
|
# ---- Invariant N: setting a key is localized, in Traktor's two fields -------
|
|
# Traktor keeps the analysed key in <MUSICAL_KEY VALUE> (pitch class, +12 for
|
|
# minor) and the text it shows / tags files with in INFO@KEY. `set_key` writes
|
|
# both, as Traktor's analysis does, in the collection's own notation.
|
|
print("== N. set_key writes INFO@KEY + MUSICAL_KEY, localized, in the collection's notation ==")
|
|
import re # noqa: E402
|
|
|
|
from konduktor.adapters.traktor.projection import entry_key, musical_key_value, parse_key # noqa: E402
|
|
from konduktor.core.adapter import InvalidCommand # noqa: E402
|
|
|
|
real = TraktorCollection(path=REAL).nml.collection.entry
|
|
both = [e for e in real if e.info and e.info.key and e.musical_key is not None
|
|
and parse_key(e.info.key)[0] is not None]
|
|
agree = sum(musical_key_value(*parse_key(e.info.key)) == e.musical_key.value_attribute for e in both)
|
|
check(f"N: MUSICAL_KEY encoding matches INFO@KEY on the real collection ({agree}/{len(both)})",
|
|
agree >= 0.995 * len(both), f"{len(both) - agree} disagree")
|
|
mk_only = [e for e in real if e.musical_key is not None and not (e.info and e.info.key)]
|
|
check(f"N: the {len(mk_only)} MUSICAL_KEY-only entries project a key",
|
|
mk_only and all(entry_key(e)[1] is not None for e in mk_only))
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
store = TraktorStore(work)
|
|
check("N: the real collection's notation is Open Key", store.key_notation() == "open_key",
|
|
store.key_notation())
|
|
|
|
def changed_lines(before: bytes, after: bytes) -> list[str]:
|
|
return [dl for dl in difflib.unified_diff(tag_lines(before), tag_lines(after), n=0)
|
|
if dl[:1] in "+-" and dl[:3] not in ("+++", "---")]
|
|
|
|
# A track that has both: the two existing lines change, nothing else.
|
|
keyed = next(e for e in store._nml.collection.entry
|
|
if e.location and e.info and e.info.key == "10m" and e.musical_key is not None)
|
|
original = store._render()
|
|
store.set_key(store._key_of(keyed), 1, "minor") # Camelot 1A = Ab minor = Open Key 6m
|
|
changed = changed_lines(original, store._render())
|
|
check("N: a keyed track: only its INFO and MUSICAL_KEY lines change",
|
|
len(changed) == 4 and 'KEY="6m"' in changed[1] and changed[3] == '+<MUSICAL_KEY VALUE="20">',
|
|
"\n".join(changed))
|
|
|
|
# A track that has neither: MUSICAL_KEY appears where Traktor puts it.
|
|
bare = next(e for e in store._nml.collection.entry
|
|
if e.location and e.info and not e.info.key and e.musical_key is None
|
|
and e.loudness is not None and e.cue_v2)
|
|
bare_id = store._key_of(bare)
|
|
original = store._render()
|
|
store.set_key(bare_id, 8, "major") # C major
|
|
after = store._render()
|
|
changed = changed_lines(original, after)
|
|
check("N: an unkeyed track gains KEY on INFO plus one MUSICAL_KEY element",
|
|
len(changed) == 4 and 'KEY="1d"' in changed[1]
|
|
and changed[2] == '+<MUSICAL_KEY VALUE="0">' and changed[3] == "+</MUSICAL_KEY>",
|
|
"\n".join(changed))
|
|
i = after.find(f'FILE="{bare.location.file}"'.encode())
|
|
span = after[after.rfind(b"<ENTRY ", 0, i):after.find(b"</ENTRY>", i)].decode()
|
|
check("N: …between LOUDNESS and the first CUE_V2, as Traktor writes it",
|
|
span.index("<LOUDNESS") < span.index("<MUSICAL_KEY") < span.index("<CUE_V2"))
|
|
check("N: …in Traktor's exact layout",
|
|
re.search(r'</LOUDNESS>\n<MUSICAL_KEY VALUE="0"></MUSICAL_KEY>\n', span) is not None)
|
|
|
|
check("N: the file tag is given the INFO text", store._entry_field_value(bare, "key") == "1d")
|
|
try:
|
|
store.set_key(bare_id, 13, "minor")
|
|
check("N: an impossible key is refused", False)
|
|
except InvalidCommand:
|
|
check("N: an impossible key is refused", True)
|
|
|
|
store.save()
|
|
e = TraktorCollection(path=work).nml.collection.entry
|
|
saved = next(x for x in e if x.location and x.location.file == bare.location.file
|
|
and x.location.dir == bare.location.dir)
|
|
check("N: survives a save + re-parse",
|
|
saved.info.key == "1d" and saved.musical_key.value_attribute == 0
|
|
and entry_key(saved)[1:] == (8, "major"))
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
# An ADDED entry's key is rendered too: a Pioneer source's "Abm" is not
|
|
# copied into an Open Key collection, and MUSICAL_KEY is written.
|
|
from konduktor.adapters.traktor.export import SKELETON # noqa: E402
|
|
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
store = TraktorStore(work)
|
|
pioneer = SimpleNamespace(title="N add", key="Abm", key_wheel=1, key_mode="minor")
|
|
added = store._entry_by_key[store.add_entry(pioneer, Path("/Volumes/KONDUKTOR_TEST_N/a.mp3"))]
|
|
check("N: an added Pioneer key is rendered in the collection's notation, with MUSICAL_KEY",
|
|
added.info.key == "6m" and added.musical_key.value_attribute == 20,
|
|
f"{added.info.key} {added.musical_key}")
|
|
odd = SimpleNamespace(title="N odd", key="DANCEDJ.CLUB", key_wheel=None, key_mode=None)
|
|
kept = store._entry_by_key[store.add_entry(odd, Path("/Volumes/KONDUKTOR_TEST_N/b.mp3"))]
|
|
check("N: text that names no key is kept, with no MUSICAL_KEY",
|
|
kept.info.key == "DANCEDJ.CLUB" and kept.musical_key is None)
|
|
|
|
empty = Path(d) / "export.nml"
|
|
empty.write_text(SKELETON, encoding="utf-8")
|
|
fresh = TraktorStore(empty)
|
|
camelot = SimpleNamespace(title="N cam", key="8A", key_wheel=8, key_mode="minor")
|
|
first = fresh._entry_by_key[fresh.add_entry(camelot, Path("/Volumes/KONDUKTOR_TEST_N/c.mp3"))]
|
|
check("N: an empty collection (an export) keeps a Traktor-native source's notation",
|
|
first.info.key == "8A", first.info.key)
|
|
nxt = fresh._entry_by_key[fresh.add_entry(pioneer, Path("/Volumes/KONDUKTOR_TEST_N/d.mp3"))]
|
|
check("N: …and follows it from then on", nxt.info.key == "1A", nxt.info.key)
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
# The key reaches the frame DJ software reads, in every container written.
|
|
import av # noqa: E402
|
|
import mutagen # noqa: E402
|
|
import numpy as np # noqa: E402
|
|
import soundfile # noqa: E402
|
|
|
|
from konduktor.core import audio_tags # noqa: E402
|
|
from stem_test_support import make_mp3 # noqa: E402
|
|
|
|
mp3 = make_mp3(Path(d) / "k.mp3", seconds=1)
|
|
flac = Path(d) / "k.flac"
|
|
soundfile.write(flac, np.zeros((44100, 2), np.float32), 44100)
|
|
m4a = Path(d) / "k.m4a"
|
|
with av.open(str(m4a), "w", format="ipod") as c:
|
|
st = c.add_stream("aac", rate=44100, layout="stereo")
|
|
fr = av.AudioFrame.from_ndarray(np.zeros((2, 1024), np.float32), format="fltp", layout="stereo")
|
|
fr.sample_rate = 44100
|
|
for pkt in list(st.encode(fr)) + list(st.encode(None)):
|
|
c.mux(pkt)
|
|
for path, frame in ((mp3, "TKEY"), (flac, "initialkey"), (m4a, "----:com.apple.iTunes:initialkey")):
|
|
r = audio_tags.write_tags(path, {"key": "9m"})
|
|
tags = mutagen.File(str(path)).tags
|
|
v = tags.get(frame)
|
|
v = v.text[0] if hasattr(v, "text") else (v[0] if v else None)
|
|
v = v.decode() if isinstance(v, bytes) else v
|
|
check(f"N: {path.suffix} key tag lands in {frame}", r.ok and v == "9m", f"{r} {v!r}")
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
# A collection keyed in Camelot gets Camelot.
|
|
work = Path(d) / "collection.nml"
|
|
data = REAL.read_text(encoding="utf-8")
|
|
data = re.sub(r'KEY="(\d{1,2})([md])"',
|
|
lambda m: f'KEY="{((int(m.group(1)) + 6) % 12) + 1}{"A" if m.group(2) == "m" else "B"}"', data)
|
|
work.write_text(data, encoding="utf-8")
|
|
store = TraktorStore(work)
|
|
check("N: a Camelot collection is detected as one", store.key_notation() == "camelot", store.key_notation())
|
|
target = next(e for e in store._nml.collection.entry if e.location and e.info)
|
|
store.set_key(store._key_of(target), 1, "minor")
|
|
check("N: …and written in Camelot", target.info.key == "1A", target.info.key)
|
|
|
|
|
|
# ---- O: moving playlists in the tree ----------------------------------
|
|
# Drag and drop in the sidebar. Moving a node relocates its whole block, so
|
|
# the guarantee is: the COLLECTION is untouched, the tree reads back as moved,
|
|
# and moving it back reproduces the original bytes exactly.
|
|
print("\n== O. move_playlist ==")
|
|
|
|
|
|
def _collection_span(data: bytes) -> bytes:
|
|
return data[data.find(b"<COLLECTION"):data.find(b"</COLLECTION>")]
|
|
|
|
|
|
def _find(nodes, name):
|
|
for n in nodes:
|
|
if n.name == name:
|
|
return n
|
|
hit = _find(n.children, name)
|
|
if hit is not None:
|
|
return hit
|
|
return None
|
|
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
before = work.read_bytes()
|
|
store = TraktorStore(work)
|
|
roots = store.tree()
|
|
folders = [n for n in roots if n.kind == "folder" and n.children]
|
|
loose = [n for n in roots if n.kind == "playlist"]
|
|
if len(folders) < 2 or len(loose) < 2:
|
|
print(" [SKIP] the reference collection has too few top-level nodes")
|
|
else:
|
|
src, dst = folders[0], folders[1]
|
|
pl = next((c for c in src.children if c.kind == "playlist"), None) or loose[0]
|
|
home = _find(roots, pl.name)
|
|
home_parent = next((f.id for f in roots if any(c.id == pl.id for c in f.children)), None)
|
|
home_index = ([c.id for c in (src.children if home_parent else roots)].index(pl.id))
|
|
check("O: every node offers can_move", all(n.can_move for n in roots))
|
|
|
|
# A playlist into another folder, at a position.
|
|
new_id = store.move_playlist(pl.id, dst.id, 1)
|
|
tree = store.tree()
|
|
moved_into = next(n for n in tree if n.id == dst.id)
|
|
check("O: a playlist keeps its id when moved", new_id == pl.id, new_id)
|
|
check("O: …and lands at the index asked for",
|
|
len(moved_into.children) > 1 and moved_into.children[1].id == pl.id,
|
|
[c.name for c in moved_into.children[:3]])
|
|
store.save()
|
|
moved = work.read_bytes()
|
|
check("O: the COLLECTION is untouched by a move",
|
|
_collection_span(moved) == _collection_span(before))
|
|
reread = TraktorStore(work).tree()
|
|
check("O: the move round-trips through a save",
|
|
any(c.id == pl.id for c in next(n for n in reread if n.id == dst.id).children))
|
|
|
|
# …and back again: byte-identical to the original.
|
|
store.move_playlist(pl.id, home_parent, home_index)
|
|
store.save()
|
|
check("O: moving it back restores the original bytes", work.read_bytes() == before,
|
|
f"{diff_count(before, work.read_bytes())} lines differ")
|
|
|
|
# A folder moves with its subtree, and its id (a path) changes with it.
|
|
new_folder = store.move_playlist(src.id, dst.id, 0)
|
|
check("O: a moved folder answers its new path id",
|
|
new_folder == f"{dst.id}/{src.name}", new_folder)
|
|
inner = next(n for n in store.tree() if n.id == dst.id).children[0]
|
|
check("O: …and its subtree moved with it",
|
|
inner.id == new_folder and len(inner.children) == len(src.children))
|
|
child_ids = [c.id for c in inner.children]
|
|
check("O: …children keep addressable ids",
|
|
all(c.startswith((new_folder.replace("fld:", "sl:") + "/", new_folder + "/"))
|
|
or not c.startswith(("fld:", "sl:")) for c in child_ids), child_ids[:3])
|
|
|
|
# Into itself: refused, nothing changed.
|
|
snapshot = store._render()
|
|
try:
|
|
store.move_playlist(dst.id, new_folder, 0)
|
|
check("O: a folder cannot be moved into its own descendant", False)
|
|
except PlaylistError:
|
|
check("O: a folder cannot be moved into its own descendant",
|
|
store._render() == snapshot)
|
|
|
|
# A namesake folder in the target: refused (two paths would be one).
|
|
store.create_folder(src.name, None)
|
|
snapshot = store._render()
|
|
try:
|
|
store.move_playlist(new_folder, None, 0)
|
|
check("O: a folder cannot land beside a namesake", False)
|
|
except PlaylistError:
|
|
check("O: a folder cannot land beside a namesake", store._render() == snapshot)
|
|
|
|
# A smart playlist moves too, by its path id.
|
|
smart = next((c for c in inner.children if c.kind == "smart"), None)
|
|
if smart is not None:
|
|
sid = store.move_playlist(smart.id, None, 0)
|
|
check("O: a smart playlist moves and answers its new id",
|
|
sid == f"sl:{smart.name}" and store.tree()[0].id == sid, sid)
|
|
|
|
# A no-op move leaves the store clean.
|
|
fresh = TraktorStore(work)
|
|
first = fresh.tree()[0]
|
|
fresh.move_playlist(first.id, None, 0)
|
|
check("O: moving a node onto its own place is not an edit", not fresh.dirty)
|
|
|
|
|
|
# ---- P: memory cues (CUE_V2 on no pad) are localized + reversible ------------
|
|
# Measured in Traktor 4.5 (2026-10-16): a memory cue is set_hotcue's element with
|
|
# HOTCUE="-1", and Traktor keeps a Konduktor-written one byte for byte. Cues are
|
|
# inserted in START order, as Traktor itself writes them.
|
|
print("\n== P. memory cues: add / rename / delete, localized, in START order ==")
|
|
from konduktor.adapters.traktor import projection as _proj # noqa: E402
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
store = TraktorStore(work)
|
|
entry = store._nml.collection.entry[0]
|
|
loc = entry.location
|
|
tid = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
|
off = store.time_offset_ms(entry)
|
|
|
|
store.add_memory_cue(tid, 42.5, 0)
|
|
store.add_memory_cue(tid, 30.0, 5, 2.0, "Intro loop")
|
|
store.save()
|
|
edited = work.read_bytes()
|
|
os_, oe = _entry_span_by_file(original, loc.file)
|
|
es_, ee = _entry_span_by_file(edited, loc.file)
|
|
check("everything outside the ENTRY is byte-identical",
|
|
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:])
|
|
added = [l for l in tag_lines(edited[es_:ee]) if l not in tag_lines(original[os_:oe])]
|
|
check("the ENTRY gains exactly the two memory cue lines",
|
|
len(added) == 2 and all('HOTCUE="-1"' in l and "<GRID" not in l for l in added),
|
|
str(added))
|
|
check("in Traktor's own shape (n.n., DISPL_ORDER 0, REPEATS -1, no COLOR)",
|
|
any('NAME="n.n." DISPL_ORDER="0" TYPE="0" START="' in l and 'REPEATS="-1"' in l
|
|
and "COLOR" not in l for l in added), str(added))
|
|
check("a memory loop carries its LEN and name",
|
|
any('NAME="Intro loop"' in l and 'TYPE="5"' in l and 'LEN="2000.000000"' in l
|
|
for l in added), str(added))
|
|
|
|
store = TraktorStore(work)
|
|
entry = store._nml.collection.entry[0]
|
|
starts = [c.start or 0.0 for c in entry.cue_v2]
|
|
check("cues stay sorted by START (inserted in place, not appended)",
|
|
starts == sorted(starts), str(starts))
|
|
tc = _proj.to_track_cues(entry, off)
|
|
memory = [c for c in tc.cues if c.role == "memory"]
|
|
check("both project as memory cues with ids, no slot",
|
|
len(memory) == 2 and all(c.slot is None and c.id for c in memory), str(memory))
|
|
check("the grid marker is still a grid marker, not a memory cue",
|
|
len(tc.grid_markers) == len([c for c in entry.cue_v2 if c.grid is not None]))
|
|
|
|
loop = next(c for c in memory if c.type == "loop")
|
|
store.rename_memory_cue(tid, loop.id, "Outro loop")
|
|
store.save()
|
|
renamed = work.read_bytes()
|
|
check("a rename changes one line", diff_count(edited, renamed) == 2,
|
|
str(diff_count(edited, renamed)))
|
|
|
|
store = TraktorStore(work)
|
|
entry = store._nml.collection.entry[0]
|
|
point = next(c for c in _proj.to_track_cues(entry, off).cues
|
|
if c.role == "memory" and c.type == "cue")
|
|
store.set_memory_cue_type(tid, point.id, 1)
|
|
store.save()
|
|
retyped = work.read_bytes()
|
|
check("a type change changes one line (TYPE 0 -> 1)",
|
|
diff_count(renamed, retyped) == 2 and b'TYPE="1" START=' in retyped,
|
|
str(diff_count(renamed, retyped)))
|
|
|
|
store = TraktorStore(work)
|
|
entry = store._nml.collection.entry[0]
|
|
for c in [c for c in _proj.to_track_cues(entry, off).cues if c.role == "memory"]:
|
|
store.delete_memory_cue(tid, c.id)
|
|
store.save()
|
|
check("add + delete round-trips to the original bytes", work.read_bytes() == original)
|
|
|
|
store = TraktorStore(work)
|
|
check("an unknown memory cue id is refused",
|
|
_raises_playlist(lambda: store.delete_memory_cue(tid, "m:1.000000:0:0.000000:0")))
|
|
|
|
# A new HOT cue is inserted in START order too (it used to be appended).
|
|
entry = store._nml.collection.entry[0]
|
|
store.set_hotcue(tid, next(s for s in range(8)
|
|
if s not in {c.hotcue for c in entry.cue_v2}), 0.001, 0)
|
|
starts = [c.start or 0.0 for c in entry.cue_v2]
|
|
check("a new hot cue is inserted by START too", starts == sorted(starts), str(starts))
|
|
|
|
# A pad MAPPED onto a memory cue: Traktor keeps both cues at one START and draws
|
|
# one marker; Konduktor shows it once, as the pad.
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
store = TraktorStore(work)
|
|
entry = store._nml.collection.entry[0]
|
|
loc = entry.location
|
|
tid = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
|
off = store.time_offset_ms(entry)
|
|
store.add_memory_cue(tid, 77.0, 0)
|
|
store.add_memory_cue(tid, 88.0, 0)
|
|
free = next(s for s in range(8) if s not in {c.hotcue for c in entry.cue_v2})
|
|
store.set_hotcue(tid, free, 77.0, 0)
|
|
tc = _proj.to_track_cues(entry, off)
|
|
check("a pad and a memory cue at one START show once, as the pad",
|
|
[round(c.start, 3) for c in tc.cues if c.role == "memory"] == [88.0]
|
|
and any(c.slot == free and round(c.start, 3) == 77.0 for c in tc.cues),
|
|
str([(c.role, c.slot, c.start) for c in tc.cues]))
|
|
check("both cues stay in the file",
|
|
sum(1 for c in entry.cue_v2 if c.grid is None and c.hotcue == -1) == 2)
|
|
|
|
print("== Q. '>' and quotes in attribute values round-trip (Traktor leaves '>' raw) ==")
|
|
# The real collection's queries hold no '>', so Traktor-written values with one
|
|
# are injected into a copy: Traktor 4.5's default "Recently added" smartlist,
|
|
# a '<' query (Traktor escapes it), and '>' / name='x' in a comment and a file
|
|
# name. All four once came back self-closed ("<X .../>"), which Traktor never
|
|
# writes, and a quoting step rewrote name='x' into a bare '"' (malformed XML).
|
|
import re as _re # noqa: E402
|
|
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
data = REAL.read_bytes()
|
|
queries = list(_re.finditer(rb'QUERY="[^"]*"', data))
|
|
swaps = [
|
|
(queries[0].group(0), b'QUERY="$IMPORTDATE >= MONTHS_AGO(1)"'),
|
|
(queries[1].group(0), b'QUERY="$RATING < 3"'),
|
|
(_re.search(rb' COMMENT="[^"]*"', data).group(0), b" COMMENT=\"Classic > Move key='8A'\""),
|
|
(_re.search(rb' FILE="[^"]*"', data).group(0), b' FILE="Break Down > Build Up.wav"'),
|
|
]
|
|
for old, new in swaps:
|
|
data = data.replace(old, new, 1)
|
|
work.write_bytes(data)
|
|
store = TraktorStore(work)
|
|
out = store._render()
|
|
check("no-op render is byte-identical", out == data, f"{diff_count(data, out)} lines differ")
|
|
check("nothing is self-closed ('/>' — Traktor never writes it)", b"/>" not in out)
|
|
|
|
entry = store._nml.collection.entry[0]
|
|
tid = f"{entry.location.volume}{entry.location.dir}{entry.location.file}"
|
|
store.set_track_metadata(tid, {"comment": "x > y key='8A' \"z\""})
|
|
store.save()
|
|
saved = work.read_bytes()
|
|
check("an edited comment with '>' keeps </INFO>",
|
|
b"COMMENT=\"x > y key='8A' "z"\"" in saved and b"/>" not in saved)
|
|
reread = TraktorStore(work)._nml.collection.entry[0].info.comment
|
|
check("…and reads back unchanged", reread == "x > y key='8A' \"z\"", repr(reread))
|
|
|
|
print("== R. track colour (INFO@COLOR) is localized, Traktor's shape, reversible ==")
|
|
# Measured in Traktor 4.5 (kit T1): COLOR="1".."7" (Red..Magenta), the LAST
|
|
# attribute of <INFO>; no file tag. Cleared = no attribute (unmeasured what
|
|
# Traktor itself leaves after "None"; absent is what an uncoloured entry has).
|
|
with tempfile.TemporaryDirectory() as d:
|
|
work = Path(d) / "collection.nml"
|
|
shutil.copy2(REAL, work)
|
|
original = work.read_bytes()
|
|
store = TraktorStore(work)
|
|
entry = next(e for e in store._nml.collection.entry if e.info is not None and e.info.color is None)
|
|
loc = entry.location
|
|
tid = f"{loc.volume}{loc.dir}{loc.file}"
|
|
store.set_track_color(tid, "blue")
|
|
store.save()
|
|
coloured = work.read_bytes()
|
|
o_s, o_e = _entry_span_by_file(original, loc.file)
|
|
c_s, c_e = _entry_span_by_file(coloured, loc.file)
|
|
check("only that ENTRY changes",
|
|
original[:o_s] + original[o_e:] == coloured[:c_s] + coloured[c_e:])
|
|
check("in one line: its <INFO>, with COLOR last, as Traktor writes it",
|
|
diff_count(original[o_s:o_e], coloured[c_s:c_e]) == 2 # one line: - and +
|
|
and _re.search(rb'<INFO [^>]* COLOR="5">', coloured[c_s:c_e]) is not None)
|
|
store = TraktorStore(work)
|
|
store.set_track_color(tid, "aqua")
|
|
check("aqua (rekordbox's) is stored as Traktor's Blue: a no-op", store.dirty is False)
|
|
store.set_track_color(tid, "purple")
|
|
check("purple is Traktor's Violet (6)",
|
|
store._entry_by_key[tid].info.color == 6)
|
|
store.set_track_color(tid, None)
|
|
store.save()
|
|
check("clearing restores the original bytes", work.read_bytes() == original)
|
|
check("an unknown colour is refused",
|
|
_raises_any(lambda: TraktorStore(work).set_track_color(tid, "teal")))
|
|
|
|
_KIT = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
|
|
if _KIT.exists() and b'COLOR="' in _KIT.read_bytes():
|
|
data = _KIT.read_bytes()
|
|
check("a Traktor 4.5 collection with coloured tracks renders byte-identically",
|
|
TraktorStore(_KIT)._render() == data)
|
|
else:
|
|
print(" [SKIP] no coloured Traktor 4.5 collection on this machine")
|
|
|
|
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
|
sys.exit(1 if failed else 0)
|