Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Tests/ORIXLibraryTests/ScriptStoreTests.swift3// Description: Tests of script persistence: versioning, optimistic conflicts, unique names, search, import/export and backups.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation9import Testing10@testable import ORIXLibrary1112@Suite struct ScriptStoreTests {13 @Test func everySourceChangeAppendsAVersion() throws {14 let store = try LibraryStore(inMemory: true)15 let created = try store.createScript(name: "Build-up", source: "v1", tags: ["fx"], origin: .preset)16 #expect(try store.scriptVersions(scriptID: created.id).map(\.source) == ["v1"])1718 let second = try store.saveScript(id: created.id, source: "v2", expectedUpdatedAt: created.updatedAt)19 #expect(second.updatedAt > created.updatedAt)20 let same = try store.saveScript(id: created.id, source: "v2", expectedUpdatedAt: second.updatedAt)21 #expect(same == second) // identical source: nothing stored, no new version22 let third = try store.saveScript(id: created.id, source: "v3", expectedUpdatedAt: second.updatedAt)2324 let versions = try store.scriptVersions(scriptID: created.id)25 #expect(versions.map(\.version) == [3, 2, 1])26 #expect(versions.map(\.source) == ["v3", "v2", "v1"])2728 // Restoring appends: history is never rewritten.29 let restored = try store.restoreScriptVersion(scriptID: created.id, versionID: versions[2].id)30 #expect(restored.source == "v1")31 #expect(restored.updatedAt > third.updatedAt)32 #expect(try store.scriptVersions(scriptID: created.id).map(\.source) == ["v1", "v3", "v2", "v1"])33 #expect(try store.script(id: created.id) == restored)34 #expect(restored.origin == .preset)35 #expect(restored.createdAt == created.createdAt)3637 #expect(expectLibraryError({ if case .notFound = $0 { return true } else { return false } }) {38 _ = try store.restoreScriptVersion(scriptID: created.id, versionID: 99_999)39 })40 try store.deleteScript(id: created.id)41 #expect(try store.scriptVersions(scriptID: created.id).isEmpty)42 #expect(try store.script(id: created.id) == nil)43 }4445 @Test func staleSaveThrowsConflictAndOverwritesNothing() throws {46 let store = try LibraryStore(inMemory: true)47 let original = try store.createScript(name: "Shared", source: "base")48 // Two editors read the same record.49 let editorA = original, editorB = original50 let savedA = try store.saveScript(id: original.id, source: "from A", expectedUpdatedAt: editorA.updatedAt)5152 #expect(expectLibraryError({ if case .conflict = $0 { return true } else { return false } }) {53 _ = try store.saveScript(id: original.id, source: "from B", expectedUpdatedAt: editorB.updatedAt)54 })55 #expect(try store.script(id: original.id) == savedA)56 #expect(try store.scriptVersions(scriptID: original.id).map(\.source) == ["from A", "base"])5758 // A stale save conflicts even when it would write the text that is already stored.59 #expect(expectLibraryError({ if case .conflict = $0 { return true } else { return false } }) {60 _ = try store.saveScript(id: original.id, source: "from A", expectedUpdatedAt: editorB.updatedAt)61 })62 // Renaming or re-tagging elsewhere also invalidates what an editor holds.63 let renamed = try store.renameScript(id: original.id, to: "Renamed")64 #expect(expectLibraryError({ if case .conflict = $0 { return true } else { return false } }) {65 _ = try store.saveScript(id: original.id, source: "late", expectedUpdatedAt: savedA.updatedAt)66 })67 // After reloading, B can save.68 let merged = try store.saveScript(id: original.id, source: "from A + B", expectedUpdatedAt: renamed.updatedAt)69 #expect(merged.source == "from A + B")70 #expect(merged.name == "Renamed")7172 // The timestamp survives a JSON round trip exactly, so clients may carry records through Codable.73 let decoded = try JSONDecoder().decode(ScriptRecord.self, from: JSONEncoder().encode(merged))74 #expect(try store.saveScript(id: original.id, source: "after JSON", expectedUpdatedAt: decoded.updatedAt).source == "after JSON")75 }7677 @Test func namesStayUniqueOnCreateRenameDuplicateAndImport() throws {78 let store = try LibraryStore(inMemory: true)79 let first = try store.createScript(name: "Drop", source: "a")80 let second = try store.createScript(name: "Drop", source: "b")81 let third = try store.createScript(name: "drop", source: "c") // case-insensitive82 #expect([first.name, second.name, third.name] == ["Drop", "Drop 2", "drop 3"])8384 let other = try store.createScript(name: "Other", source: "d")85 #expect(try store.renameScript(id: other.id, to: "Drop").name == "Drop 4")86 #expect(try store.renameScript(id: first.id, to: "Drop") == first) // renaming to its own name is a no-op87 #expect(try store.renameScript(id: first.id, to: "DROP").name == "DROP") // case change of its own name is allowed88 #expect(try store.renameScript(id: other.id, to: " ").name == "Untitled")8990 let copy = try store.duplicateScript(id: second.id)91 #expect(copy.name == "Drop 2 2")92 #expect(copy.source == "b")93 #expect(copy.id != second.id)94 #expect(try store.scriptVersions(scriptID: copy.id).count == 1)9596 let names = try store.scripts().map { $0.name.lowercased() }97 #expect(Set(names).count == names.count)98 }99100 @Test func searchFiltersAndMetadata() throws {101 let store = try LibraryStore(inMemory: true)102 let echo = try store.createScript(name: "Écho long", source: "deck.a.echo(0.5)", tags: ["fx", "transition"])103 let filter = try store.createScript(name: "Filter sweep", source: "deck.b.filter.sweep()", tags: ["fx"], origin: .preset)104 let ai = try store.createScript(name: "Generated", source: "// made by the assistant", origin: .ai)105 #expect(try store.scripts().map(\.name) == ["Écho long", "Filter sweep", "Generated"])106 #expect(try store.scripts(search: "echo").map(\.id) == [echo.id]) // name, diacritic-insensitive107 #expect(try store.scripts(search: "SWEEP").map(\.id) == [filter.id])108 #expect(try store.scripts(search: "fx").count == 2) // tags109 #expect(try store.scripts(search: "assistant").map(\.id) == [ai.id]) // source110 #expect(try store.scripts(search: "fx transition").map(\.id) == [echo.id])111 #expect(try store.scripts(search: "'; DROP TABLE scripts;--").isEmpty)112 #expect(try store.scripts(origin: .preset).map(\.id) == [filter.id])113 #expect(try store.scripts(origin: .ai).map(\.id) == [ai.id])114115 let updated = try store.updateScript(id: ai.id, tags: ["review"], favorite: true)116 #expect(updated.tags == ["review"])117 #expect(updated.updatedAt > ai.updatedAt)118 #expect(try store.scripts(favoritesOnly: true).map(\.id) == [ai.id])119 #expect(try store.scripts(search: "review").map(\.id) == [ai.id])120 #expect(try store.script(named: "filter SWEEP")?.id == filter.id)121 }122123 @Test func exportImportRoundTrip() throws {124 let temp = TempDirectory()125 let store = try LibraryStore(inMemory: true)126 let source = "// ---\non beat(16) {\n\tdeck.a.loop(4)\n}\n// trailing comment, \"quotes\", émojis-free ünïcode\n\n"127 let original = try store.createScript(name: "Loop: roll/4", source: source, tags: ["loop", "roll"], favorite: true, origin: .ai)128 let file = temp.file("export.orixdj")129 try store.exportScript(id: original.id, to: file)130 let text = try String(contentsOf: file, encoding: .utf8)131 #expect(text.hasPrefix("// ORIX DJ Script v1\n// name: Loop: roll/4\n"))132 #expect(text.hasSuffix(source))133134 // Same library: imported as a new script with a unique name.135 let twin = try store.importScript(from: file)136 #expect(twin.id != original.id)137 #expect(twin.name == "Loop: roll/4 2")138 #expect(twin.source == source)139140 // Fresh library: identical name, source, tags, origin, favorite.141 let fresh = try LibraryStore(inMemory: true)142 let imported = try fresh.importScript(from: file)143 #expect(imported.name == original.name)144 #expect(imported.source == original.source)145 #expect(imported.tags == original.tags)146 #expect(imported.origin == .ai)147 #expect(imported.favorite)148 #expect(try fresh.scriptVersions(scriptID: imported.id).count == 1)149150 // A plain text file without header is taken whole, named after the file.151 let plain = temp.file("My Transition.orixdj")152 try "deck.a.play()\n".write(to: plain, atomically: true, encoding: .utf8)153 let fromPlain = try fresh.importScript(from: plain)154 #expect(fromPlain.name == "My Transition")155 #expect(fromPlain.source == "deck.a.play()\n")156 #expect(fromPlain.origin == .user)157158 // Empty source survives too.159 let empty = try store.createScript(name: "Empty", source: "")160 let emptyFile = temp.file("empty.orixdj")161 try store.exportScript(id: empty.id, to: emptyFile)162 #expect(try fresh.importScript(from: emptyFile).source == "")163164 #expect(expectLibraryError({ if case .io = $0 { return true } else { return false } }) {165 _ = try fresh.importScript(from: temp.file("absent.orixdj"))166 })167 }168169 @Test func backupWritesEveryScriptAndRestoresElsewhere() throws {170 let temp = TempDirectory()171 let store = try LibraryStore(inMemory: true)172 try store.createScript(name: "One", source: "1")173 try store.createScript(name: "a/b", source: "2")174 try store.createScript(name: "a-b", source: "3") // collides with the sanitised "a/b"175 try store.createScript(name: "Été", source: "4", tags: ["saison"])176 let directory = temp.url.appendingPathComponent("backups/2026-11-21", isDirectory: true)177 let files = try store.backupScripts(to: directory)178 #expect(files.count == 4)179 #expect(Set(files.map(\.lastPathComponent)).count == 4)180 #expect(files.allSatisfy { $0.pathExtension == "orixdj" && FileManager.default.fileExists(atPath: $0.path) })181182 let restored = try LibraryStore(inMemory: true)183 for file in files { try restored.importScript(from: file) }184 let before = try store.scripts().map { [$0.name, $0.source] + $0.tags }185 let after = try restored.scripts().map { [$0.name, $0.source] + $0.tags }186 #expect(before == after)187 }188}189