Repository Public
1// ORIX Sonata2// File: Packages/SonataProject/Tests/SonataProjectTests/SonataProjectTests.swift3// Description: Round trip, migration, path safety, missing files, backups and recovery of the project format.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9@testable import SonataProject1011func scratch() throws -> URL {12 let url = FileManager.default.temporaryDirectory.appendingPathComponent("sonata-project-tests-" + UUID().uuidString)13 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)14 return url15}1617@Test func roundTripPreservesEverything() throws {18 let dir = try scratch()19 defer { try? FileManager.default.removeItem(at: dir) }20 var b = SonataProjectBundle(name: "Aurora", mainSource: "composition \"Aurora\" { tempo 120bpm }\n", writtenBy: "test")21 b.sources["src/motifs.sonata"] = "const x = 1\n"22 b.instruments["instruments/CrystalHarp.sonatainstrument"] = "instrument CrystalHarp { model plucked_string }\n"23 b.studio.overrides.strips = [StripOverride(strip: "piano", gainDb: -6, mute: true)]24 b.studio.overrides.notes = [NoteOverride(track: "piano", index: 3, originalStart: RationalValue(1, 4), originalPitch: 62, start: RationalValue(1, 2), velocity: 0.5)]25 b.studio.loopStart = 1.526 b.studio.loopEnd = 427 b.studio.loopEnabled = true28 let url = dir.appendingPathComponent("Aurora.sonataproject")29 try b.write(to: url)30 var read = try SonataProjectBundle.read(from: url)31 #expect(read.readWarnings.isEmpty)32 #expect(read.migratedFromFormat == nil)33 #expect(read.sources == b.sources)34 #expect(read.instruments == b.instruments)35 #expect(read.studio == b.studio)36 #expect(read.manifest.id == b.manifest.id)37 #expect(read.manifest.format == ProjectManifest.currentFormat)3839 // The overrides JSON is exactly what the Rust side expects (snake_case keys).40 let json = String(decoding: try JSONEncoder.sorted.encode(read.studio.overrides), as: UTF8.self)41 #expect(json.contains("\"gain_db\":-6"))42 #expect(json.contains("\"original_start\":{\"den\":4,\"num\":1}"))4344 // Update in place: a removed source disappears, an unknown file of the user survives.45 try Data("keep".utf8).write(to: url.appendingPathComponent("notes.txt"))46 try Data([1, 2, 3]).write(to: url.appendingPathComponent("assets/sample.bin"))47 read.sources.removeValue(forKey: "src/motifs.sonata")48 read.mainSource = "composition \"Aurora\" { tempo 90bpm }\n"49 try read.write(to: url)50 let again = try SonataProjectBundle.read(from: url)51 #expect(again.sources.count == 1)52 #expect(again.mainSource.contains("90bpm"))53 #expect(FileManager.default.fileExists(atPath: url.appendingPathComponent("notes.txt").path))54 #expect(FileManager.default.fileExists(atPath: url.appendingPathComponent("assets/sample.bin").path))55 #expect(again.manifest.created == b.manifest.created || abs(again.manifest.created.timeIntervalSince(b.manifest.created)) < 1)56}5758@Test func migratesFormatOne() throws {59 let v1 = #"{"format":1,"id":"6F9619FF-8B86-D011-B42D-00C04FC964FF","name":"Old","entry":"src/main.sonata","created":1700000000,"modified":1700000100}"#60 let (m, from) = try ManifestMigration.decode(Data(v1.utf8))61 #expect(from == 1)62 #expect(m.format == 2)63 #expect(m.main == "src/main.sonata")64 #expect(m.assets.isEmpty)65 #expect(m.created == Date(timeIntervalSince1970: 1_700_000_000))66 let again = try ManifestMigration.decode(try ManifestMigration.encode(m))67 #expect(again.manifest == m)68 #expect(again.migratedFrom == nil)69}7071@Test func refusesNewerAndBrokenManifests() throws {72 #expect(throws: ProjectError.newerFormat(found: 99, supported: 2)) { try ManifestMigration.decode(Data(#"{"format":99}"#.utf8)) }73 #expect(throws: ProjectError.self) { try ManifestMigration.decode(Data("[]".utf8)) }74 #expect(throws: ProjectError.self) { try ManifestMigration.decode(Data(#"{"format":2,"name":"x"}"#.utf8)) }75 #expect(throws: ProjectError.self) { try ManifestMigration.decode(Data(#"{"format":0}"#.utf8)) }76}7778@Test func pathSafety() throws {79 for bad in ["", "/etc/passwd", "../x.sonata", "src/../../x.sonata", "src//x.sonata", "src/./x.sonata", "~/x", "other/x.sonata", "src\\x.sonata", "src/x\u{0}.sonata", "src"] {80 #expect(!SonataProjectBundle.isSafeRelativePath(bad), "\(bad)")81 }82 #expect(SonataProjectBundle.isSafeRelativePath("src/main.sonata"))83 #expect(SonataProjectBundle.isSafeRelativePath("src/motifs/arp.sonata"))8485 let dir = try scratch()86 defer { try? FileManager.default.removeItem(at: dir) }87 var b = SonataProjectBundle(name: "P", mainSource: "x")88 b.sources["src/../escape.sonata"] = "boom"89 #expect(throws: ProjectError.unsafePath("src/../escape.sonata")) { try b.write(to: dir.appendingPathComponent("P.sonataproject")) }9091 // A manifest whose main escapes the bundle is refused; a symlinked source is skipped with a warning.92 let url = dir.appendingPathComponent("Q.sonataproject")93 try SonataProjectBundle(name: "Q", mainSource: "ok").write(to: url)94 let secret = dir.appendingPathComponent("secret.sonata")95 try Data("secret".utf8).write(to: secret)96 try FileManager.default.createSymbolicLink(at: url.appendingPathComponent("src/link.sonata"), withDestinationURL: secret)97 let read = try SonataProjectBundle.read(from: url)98 #expect(read.sources["src/link.sonata"] == nil)99 #expect(read.readWarnings.contains { $0.contains("outside the project") })100 var manifest = read.manifest101 manifest.main = "src/../../secret.sonata"102 try ManifestMigration.encode(manifest).write(to: url.appendingPathComponent("project.json"))103 #expect(throws: ProjectError.unsafePath("src/../../secret.sonata")) { try SonataProjectBundle.read(from: url) }104}105106@Test func missingFilesAreReported() throws {107 let dir = try scratch()108 defer { try? FileManager.default.removeItem(at: dir) }109 let url = dir.appendingPathComponent("M.sonataproject")110 var b = SonataProjectBundle(name: "M", mainSource: "x")111 b.manifest.assets = [.init(file: "gone.wav", originalName: "Take 1.wav", sha256: "00", bytes: 1)]112 try b.write(to: url)113 try Data("{broken".utf8).write(to: url.appendingPathComponent("studio.json"))114 let read = try SonataProjectBundle.read(from: url)115 #expect(read.readWarnings.contains { $0.contains("Take 1.wav") && $0.contains("missing") })116 #expect(read.readWarnings.contains { $0.contains("studio.json") })117 #expect(read.studio == StudioState())118 try FileManager.default.removeItem(at: url.appendingPathComponent("src/main.sonata"))119 #expect(throws: ProjectError.mainSourceMissing("src/main.sonata")) { try SonataProjectBundle.read(from: url) }120 #expect(throws: ProjectError.notABundle("nothing.sonataproject")) { try SonataProjectBundle.read(from: dir.appendingPathComponent("nothing.sonataproject")) }121}122123@Test func assetImportIsContentAddressed() throws {124 let dir = try scratch()125 defer { try? FileManager.default.removeItem(at: dir) }126 let url = dir.appendingPathComponent("A.sonataproject")127 try SonataProjectBundle(name: "A", mainSource: "x").write(to: url)128 let file = dir.appendingPathComponent("Take 1.WAV")129 try Data(repeating: 7, count: 3000).write(to: file)130 let a = try SonataProjectBundle.importAsset(file, intoBundleAt: url)131 let b = try SonataProjectBundle.importAsset(file, intoBundleAt: url)132 #expect(a == b)133 #expect(a.file.hasSuffix(".wav") && a.bytes == 3000 && a.sha256.count == 64)134 #expect(try FileManager.default.contentsOfDirectory(atPath: url.appendingPathComponent("assets").path) == [a.file])135}136137@Test func backupsAreBounded() throws {138 let dir = try scratch()139 defer { try? FileManager.default.removeItem(at: dir) }140 let loc = ProjectLocations(projectID: UUID(), cachesRoot: dir.appendingPathComponent("c"), supportRoot: dir.appendingPathComponent("s"))141 let store = BackupStore(directory: loc.backups, keep: 3)142 let t0 = Date(timeIntervalSince1970: 1_800_000_000)143 for i in 0..<5 { try store.save(sources: ["src/main.sonata": "v\(i)"], now: t0.addingTimeInterval(Double(i))) }144 #expect(try store.save(sources: ["src/main.sonata": "v4"], now: t0.addingTimeInterval(9)) == nil, "identical to the latest")145 let list = store.list()146 #expect(list.count == 3)147 #expect(try store.load(list[0]) == ["src/main.sonata": "v4"])148 #expect(try store.load(list[2]) == ["src/main.sonata": "v2"])149150}151152@Test func fileWrapperRoundTripKeepsAssetsAndUnknownFiles() throws {153 let dir = try scratch()154 defer { try? FileManager.default.removeItem(at: dir) }155 var b = SonataProjectBundle(name: "W", mainSource: "one\n")156 b.sources["src/motifs/arp.sonata"] = "const a = 1\n"157 b.studio.metronome = true158 let url = dir.appendingPathComponent("W.sonataproject")159 try b.fileWrapper().write(to: url, options: .atomic, originalContentsURL: nil)160 try Data([9, 9]).write(to: url.appendingPathComponent("assets/take.wav"))161 try Data("mine".utf8).write(to: url.appendingPathComponent("README.txt"))162163 let original = try FileWrapper(url: url)164 var read = try SonataProjectBundle.read(fileWrapper: original)165 #expect(read.sources == b.sources)166 #expect(read.studio.metronome)167 #expect(try SonataProjectBundle.read(from: url).sources == b.sources, "both readers agree")168169 read.mainSource = "two\n"170 read.sources.removeValue(forKey: "src/motifs/arp.sonata")171 try read.fileWrapper(preserving: original).write(to: url, options: .atomic, originalContentsURL: url)172 let again = try SonataProjectBundle.read(from: url)173 #expect(again.sources == ["src/main.sonata": "two\n"])174 #expect(try Data(contentsOf: url.appendingPathComponent("assets/take.wav")) == Data([9, 9]))175 #expect(try String(contentsOf: url.appendingPathComponent("README.txt"), encoding: .utf8) == "mine")176 #expect(throws: ProjectError.self) { try SonataProjectBundle.read(fileWrapper: FileWrapper(regularFileWithContents: Data())) }177}178