"""End-to-end write test for Phase 3. Runs against a COPY of the collection (never the original). Verifies: * create / add-tracks / reorder / rename / delete all work * save records a version-history commit and produces a Traktor-parseable file * the COLLECTION section is byte-identical after save (truly surgical) * changes survive a reload """ import os import re import shutil import sys import tempfile import warnings from pathlib import Path warnings.filterwarnings("ignore") REAL = Path(__file__).resolve().parents[1] / "collection.nml" work_dir = Path(tempfile.mkdtemp(prefix="konduktor-test-")) WORK = work_dir / "collection.nml" shutil.copy2(REAL, WORK) # Snapshot the real file up front; the test only ever touches the copy, so the # real file must be untouched at the end (regardless of its absolute size). REAL_STAT = (REAL.stat().st_size, REAL.stat().st_mtime) os.environ["KONDUKTOR_NML"] = str(WORK) # Isolate version history + prefs to a throwaway dir (never the real app data). os.environ["KONDUKTOR_DATA_DIR"] = str(work_dir / "appdata") from fastapi.testclient import TestClient # noqa: E402 from traktor_nml_utils import TraktorCollection # noqa: E402 import konduktor.main as m # noqa: E402 client = TestClient(m.app) def collection_span(data: bytes) -> bytes: s = re.search(rb"]", data).start() e = re.search(rb"", data).end() return data[s:e] def check(label, cond): print(f" [{'PASS' if cond else 'FAIL'}] {label}") if not cond: check.failed = True check.failed = False print("== initial read ==") pls = client.get("/api/playlists").json() flat = lambda ns: [x for n in ns for x in [n] + flat(n.get("children", []))] playlists = [n for n in flat(pls) if n["kind"] == "playlist"] print(f" {len(playlists)} playlists, e.g. {[p['name'] for p in playlists[:3]]}") donor = next(p for p in playlists if p["count"] >= 5) donor_tracks = client.get(f"/api/playlists/{donor['id']}/tracks").json() track_ids = [t["id"] for t in donor_tracks[:5]] print(f" donor '{donor['name']}' -> using {len(track_ids)} track ids") collection_before = collection_span(WORK.read_bytes()) print("== create + add + reorder + rename ==") created = client.post("/api/playlists", json={"name": "Konduktor Test"}).json() new_uuid = created["id"] check("create returns uuid", bool(new_uuid)) r = client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": track_ids}) check("add 5 entries", r.json().get("count") == 5) reordered = list(reversed(track_ids)) client.put(f"/api/playlists/{new_uuid}/entries", json={"track_ids": reordered}) client.patch(f"/api/playlists/{new_uuid}", json={"name": "Konduktor Test 2"}) st = client.get("/api/state").json() check("state is dirty before save", st["dirty"] is True) print("== save ==") res = client.post("/api/save").json() check("saved", res["saved"] is True) check("commit recorded", bool(res["commit"])) hist = client.get("/api/history").json() check("history has baseline + this save", len(hist) >= 2) check("newest history summary non-empty", bool(hist[0]["summary"])) check("no .bak litter next to collection", not list(work_dir.glob("*.bak"))) st = client.get("/api/state").json() check("state clean after save", st["dirty"] is False) print("== verify saved file ==") data_after = WORK.read_bytes() check( "COLLECTION section byte-identical (surgical write)", collection_span(data_after) == collection_before, ) # Re-parse with the real Traktor library (proves it stays v4-valid). coll = TraktorCollection(path=WORK) check("file re-parses with traktor-nml-utils", len(coll.nml.collection.entry) == 8485) def walk(n): yield n if n.subnodes: for s in n.subnodes.node: yield from walk(s) found = [ n for n in walk(coll.nml.playlists.node) if n.type == "PLAYLIST" and n.playlist and n.playlist.uuid == new_uuid ] check("new playlist present in saved file", len(found) == 1) if found: node = found[0] check("renamed correctly", node.name == "Konduktor Test 2") check("ENTRIES attr synced to 5", node.playlist.entries == 5) saved_keys = [e.primarykey.key for e in node.playlist.entry] check("entries reordered correctly", saved_keys == reordered) print("== reload + delete ==") client.post("/api/reload") pls2 = flat(client.get("/api/playlists").json()) check("new playlist visible after reload", any(n["id"] == new_uuid for n in pls2)) client.delete(f"/api/playlists/{new_uuid}") res2 = client.post("/api/save").json() coll2 = TraktorCollection(path=WORK) still = [ n for n in walk(coll2.nml.playlists.node) if n.type == "PLAYLIST" and n.playlist and n.playlist.uuid == new_uuid ] check("playlist gone after delete+save", len(still) == 0) check("COLLECTION still byte-identical", collection_span(WORK.read_bytes()) == collection_before) print("== folders: create, rename, delete (nested ids contain a slash) ==") outer = client.post("/api/playlists/folders", json={"name": "Konduktor Test Folder"}).json()["id"] inner = client.post( "/api/playlists/folders", json={"name": "Inner Draft", "parent_id": outer} ).json()["id"] check("nested folder id is its path", inner == "fld:Konduktor Test Folder/Inner Draft") r = client.patch(f"/api/playlists/{inner.replace('/', '%2F')}", json={"name": "Inner"}) check("nested folder rename accepted", r.status_code == 200) inner = "fld:Konduktor Test Folder/Inner" nodes = flat(client.get("/api/playlists").json()) check("renamed folder found by its new path", any(n["id"] == inner for n in nodes)) check("folder name with a slash refused", client.post("/api/playlists/folders", json={"name": "a/b"}).status_code == 400) client.post("/api/playlists/folders", json={"name": "Sibling", "parent_id": outer}) check("rename onto a sibling folder's name refused", client.patch(f"/api/playlists/{outer}%2FSibling", json={"name": "Inner"}).status_code == 400) nested_uuid = client.post( "/api/playlists", json={"name": "Nested", "parent_id": inner} ).json()["id"] nodes = flat(client.get("/api/playlists").json()) check("nested folder offered as deletable", any(n["id"] == inner and n["can_delete"] for n in nodes)) r = client.delete(f"/api/playlists/{inner.replace('/', '%2F')}") check("nested folder delete accepted", r.status_code == 200) nodes = flat(client.get("/api/playlists").json()) check("folder and its playlist gone", not any(n["id"] in (inner, nested_uuid) for n in nodes)) check("parent folder kept", any(n["id"] == outer for n in nodes)) client.delete(f"/api/playlists/{outer}") client.post("/api/save") coll3 = TraktorCollection(path=WORK) check("no test folder in saved file", not any(n.name == "Konduktor Test Folder" for n in walk(coll3.nml.playlists.node))) check("COLLECTION still byte-identical after folder delete", collection_span(WORK.read_bytes()) == collection_before) check("unknown folder is 404", client.delete("/api/playlists/fld:No Such Folder").status_code == 404) print("== drag and drop: add with duplicates, move ==") target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"] first, rest = track_ids[:2], track_ids[2:4] r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json() check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0) r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json() check("'ask' with a duplicate changes nothing and counts it", r["status"] == "duplicates" and r["duplicates"] == 1 and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2) r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json() check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4) r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first[:1], "duplicates": "add"}).json() check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5) r = client.post(f"/api/playlists/{target}/add", json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json() check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1) more = [t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"] if t["id"] not in track_ids][:2] before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] r = client.post(f"/api/playlists/{target}/add", json={"track_ids": more[:1], "index": 1}).json() after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] check("an index inserts there (a drop between rows)", r["added"] == 1 and after == before[:1] + more[:1] + before[1:]) client.post(f"/api/playlists/{target}/add", json={"track_ids": more[1:2], "index": 999}) after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] check("an index past the end appends", after[-1] == more[1]) check("capabilities say Traktor holds duplicates", client.get("/api/capabilities").json()["playlists"]["duplicates"] is True) box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"] r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0}) check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target) r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0}) check("moving a folder answers its (path) id", r.json()["id"] == box) check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box) r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0}) check("a folder into itself is a 400", r.status_code == 400) r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0}) check("an unknown node is a 404", r.status_code == 404) client.delete(f"/api/playlists/{box}") client.post("/api/save") check("COLLECTION still byte-identical after drops and moves", collection_span(WORK.read_bytes()) == collection_before) print("== original untouched ==") check( "original collection.nml never modified", (REAL.stat().st_size, REAL.stat().st_mtime) == REAL_STAT, ) shutil.rmtree(work_dir, ignore_errors=True) print("\nRESULT:", "FAILED" if check.failed else "ALL PASSED") sys.exit(1 if check.failed else 0)