SPB Git

Repository Public

UnitTests.swift 12.6 KB 159 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/UnitTests.swift3// Description: Tests: queue rules, byte ranges, path guard, formatting, loudness vs reference meter, large library speed.4import XCTest5import AVFoundation6@testable import SPMusicCore78final class AudioQueueTests: XCTestCase {9    func tracks(_ n: Int) -> [Track] { (0..<n).map { Track(id: "t\($0)", title: "T\($0)") } }1011    func testOrderRepeatAndEnds() {12        var q = AudioQueue(); q.set(tracks(3), startAt: 1)13        XCTAssertEqual(q.current?.track.id, "t1"); XCTAssertEqual(q.nextIndex(auto: true), 2); XCTAssertEqual(q.previousIndex(), 0)14        q.jump(to: 2)15        XCTAssertNil(q.nextIndex(auto: true), "end of the queue")16        q.repeatMode = .all; XCTAssertEqual(q.nextIndex(auto: true), 0)17        q.repeatMode = .one; XCTAssertEqual(q.nextIndex(auto: true), 2, "repeat one replays when the track ends by itself")18        XCTAssertEqual(q.nextIndex(auto: false), 0, "but the Next button moves on")19    }20    func testShuffleKeepsTheCurrentTrackAndEveryTrackAndIsReversible() {21        var q = AudioQueue(); q.set(tracks(50), startAt: 7)22        q.setShuffle(true)23        XCTAssertEqual(q.current?.track.id, "t7"); XCTAssertEqual(q.index, 7)24        XCTAssertEqual(Set(q.items.map(\.track.id)).count, 50)25        XCTAssertNotEqual(q.items.map(\.track.id), tracks(50).map(\.id), "the upcoming tracks were reordered")26        XCTAssertEqual(q.items.prefix(8).map(\.track.id), tracks(8).map(\.id), "what was already played is untouched")27        q.jump(to: 20); let cur = q.current!.id28        q.setShuffle(false)29        XCTAssertEqual(q.items.map(\.track.id), tracks(50).map(\.id)); XCTAssertEqual(q.current?.id, cur)30    }31    func testEditingTheQueueNeverLosesThePlace() {32        var q = AudioQueue(); q.set(tracks(5), startAt: 2)33        q.playNext([Track(id: "n", title: "N")]); XCTAssertEqual(q.items.map(\.track.id), ["t0", "t1", "t2", "n", "t3", "t4"])34        q.append([Track(id: "z", title: "Z")]); XCTAssertEqual(q.items.last?.track.id, "z")35        q.remove(q.items[0].id); XCTAssertEqual(q.current?.track.id, "t2"); XCTAssertEqual(q.index, 1)36        q.remove(q.current!.id); XCTAssertEqual(q.current?.track.id, "t2", "the current item cannot be removed from under the player")37        q.move(from: 4, to: 0); XCTAssertEqual(q.items.first?.track.id, "t4"); XCTAssertEqual(q.current?.track.id, "t2")38        q.clearUpcoming(); XCTAssertEqual(q.items.last?.track.id, "t2")39    }40}4142final class SmallPartsTests: XCTestCase {43    func testByteRanges() {44        var r = ByteRangeSet()45        r.insert(0..<100); r.insert(200..<300); r.insert(100..<150)46        XCTAssertEqual(r.pairs, [[0, 150], [200, 300]]); XCTAssertEqual(r.total, 250)47        XCTAssertEqual(r.contiguous(from: 40), 110); XCTAssertEqual(r.contiguous(from: 150), 0)48        XCTAssertEqual(r.firstMissing(from: 0, limit: 400), 150); XCTAssertEqual(r.holeEnd(from: 150, limit: 400), 200)49        XCTAssertEqual(r.firstMissing(from: 210, limit: 400), 300); XCTAssertEqual(r.holeEnd(from: 300, limit: 400), 400)50        r.insert(140..<210); r.insert(300..<400)51        XCTAssertEqual(r.pairs, [[0, 400]]); XCTAssertNil(r.firstMissing(from: 0, limit: 400))52    }53    func testPathsAreConfinedToTheMarkedLibrary() throws {54        let base = FileManager.default.temporaryDirectory.appendingPathComponent("pg-\(UUID().uuidString.prefix(6))")55        let root = base.appendingPathComponent("lib"), other = base.appendingPathComponent("library-evil")56        try FileManager.default.createDirectory(at: root.appendingPathComponent(".spmusic"), withIntermediateDirectories: true)57        try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true)58        defer { try? FileManager.default.removeItem(at: base) }59        XCTAssertTrue(PathGuard.isInside(root.appendingPathComponent("A/b.flac"), root: root))60        XCTAssertFalse(PathGuard.isInside(root, root: root), "the root itself is never a deletable item")61        XCTAssertFalse(PathGuard.isInside(root.appendingPathComponent("../library-evil/x.flac"), root: root))62        XCTAssertFalse(PathGuard.isInside(base.appendingPathComponent("lib2/x"), root: root), "a sibling whose name starts the same is outside")63        try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("link"), withDestinationURL: other)64        XCTAssertFalse(PathGuard.isInside(root.appendingPathComponent("link/x.flac"), root: root), "a symbolic link out of the library is followed and refused")65        XCTAssertFalse(PathGuard.mayDelete(root.appendingPathComponent("A/b.flac"), root: root), "no marker file, no deletion")66        try Data("{}".utf8).write(to: root.appendingPathComponent(".spmusic/library.json"))67        XCTAssertTrue(PathGuard.mayDelete(root.appendingPathComponent("A/b.flac"), root: root))68        XCTAssertEqual(PathGuard.safeComponent("AC/DC: Back\\in..", fallback: "x"), "AC-DC- Back-in")69        XCTAssertEqual(PathGuard.safeComponent("  ...  ", fallback: "Inconnu"), "Inconnu")70        XCTAssertEqual(PathGuard.safeComponent("Été\u{0000}pur", fallback: "x"), "Été pur")71    }72    func testFormattingAndDates() {73        XCTAssertEqual(Format.duration(ms: 185_000), "3:05"); XCTAssertEqual(Format.duration(ms: 3_725_000), "1:02:05")74        XCTAssertEqual(Format.sampleRate(44100), "44,1 kHz"); XCTAssertEqual(Format.sampleRate(96000), "96 kHz")75        XCTAssertEqual(Format.quality(of: Track(id: "a", title: "", codec: "mp3", container: "mp3", sampleRate: 44100, bitrate: 320_000)), "MP3 · 320 kb/s")76        XCTAssertEqual(Format.quality(of: Track(id: "a", title: "", codec: "alac", container: "mov", sampleRate: 48000, bitDepth: 24)), "ALAC · 24 bits / 48 kHz")77        for s in ["2026-11-17T22:40:47.229Z", "2026-01-01T00:00:00.000Z", "2026-06-30T23:59:59.999Z", "2026-03-08T07:00:00.001Z"] {78            XCTAssertEqual(APIClient.iso(APIClient.parseISO(s)!), s, "dates survive a round trip to the millisecond")79        }80        XCTAssertEqual(TextNorm.norm("  Éric Lapointe "), "eric lapointe")81        XCTAssertEqual(Data(base64URL: "SGk_LQ")?.base64URL, "SGk_LQ")82    }83    func testLoudnessMatchesTheReferenceMeter() throws {84        guard let ffmpeg = Fixtures.ffmpeg else { throw XCTSkip("ffmpeg is not installed") }85        // Compared with ffmpeg's EBU R128 meter on the same files.86        for (name, input) in [("loud-pink.flac", "anoisesrc=d=20:c=pink:r=44100:a=0.5"), ("loud-sine.flac", "sine=frequency=1000:duration=20:sample_rate=48000")] {87            let url = Fixtures.dir.appendingPathComponent(name)88            try Fixtures.run(ffmpeg, ["-v", "error", "-nostdin", "-y", "-f", "lavfi", "-i", input, "-ac", "2", "-c:a", "flac", url.path])89            let p = Process(); p.executableURL = URL(fileURLWithPath: ffmpeg); p.arguments = ["-nostdin", "-i", url.path, "-af", "ebur128", "-f", "null", "-"]90            let pipe = Pipe(); p.standardError = pipe; p.standardOutput = FileHandle.nullDevice91            try p.run(); let text = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""; p.waitUntilExit()92            let summary = text.components(separatedBy: "Integrated loudness:").last ?? ""93            let reference = try XCTUnwrap(summary.components(separatedBy: "I:").dropFirst().first.flatMap { Double($0.trimmingCharacters(in: .whitespaces).split(separator: " ").first ?? "") }, name)94            let mine = try LoudnessAnalyzer.analyze(LocalFileSource(url: url))95            XCTAssertEqual(mine.lufs, reference, accuracy: 0.3, "\(name): reference \(reference) LUFS")96            XCTAssertGreaterThan(mine.peak, 0.05); XCTAssertLessThanOrEqual(mine.peak, 1.0)97        }98        XCTAssertEqual(LoudnessAnalyzer.gainDB(lufs: -9, peak: 1), -5, accuracy: 0.01, "a loud master is turned down")99        XCTAssertEqual(LoudnessAnalyzer.gainDB(lufs: -24, peak: 0.9), Float(-20 * log10(0.9) - 0.3), accuracy: 0.01, "a quiet one is raised only as far as its peak allows")100    }101}102103final class LargeLibraryTests: XCTestCase {104    /// 6 000 albums and 72 000 tracks: what the interface asks of the database must stay instant.105    func testAVeryLargeLibraryStaysFast() async throws {106        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("big-\(UUID().uuidString.prefix(6))")107        defer { try? FileManager.default.removeItem(at: dir) }108        let store = try LibraryStore(path: dir.appendingPathComponent("library.sqlite").path)109        let words = ["Nuit", "Rivière", "Blues", "Été", "Lumière", "Montréal", "Hiver", "Soleil", "Route", "Cœur", "Vent", "Ombre", "Danse", "Feu", "Silence", "Étoile"]110        let now = Date()111        var rev: Int64 = 0112        let artists = (0..<1500).map { i -> WireArtist in rev += 1; return WireArtist(id: "ar\(i)", name: "\(words[i % 16]) \(words[(i / 16) % 16]) \(i)", rev: rev) }113        let insertStart = Date()114        for chunk in 0..<6 {115            var albums: [WireAlbum] = [], tracks: [WireTrack] = []116            for a in (chunk * 1000)..<((chunk + 1) * 1000) {117                rev += 1118                albums.append(WireAlbum(id: "al\(a)", title: "\(words[a % 16]) de \(words[(a / 7) % 16]) vol. \(a)", year: 1960 + a % 65, artworkId: "art\(a % 900)", artistId: "ar\(a % 1500)", genre: "Genre \(a % 12)", createdAt: now.addingTimeInterval(Double(-a)), rev: rev))119                for n in 1...12 {120                    rev += 1121                    tracks.append(WireTrack(id: "t\(a)-\(n)", title: "\(words[(a + n) % 16]) \(words[(a * n) % 16]) \(n)", trackNo: n, discNo: 1, durationMs: 200_000, year: 1960 + a % 65, codec: "flac", container: "flac",122                                            sampleRate: 44100, bitDepth: 16, channels: 2, bitrate: 900_000, webPlayable: "yes", compatState: "none", artistId: "ar\(a % 1500)", albumId: "al\(a)", genre: "Genre \(a % 12)",123                                            lyricsState: nil, createdAt: now, file: WireFile(assetId: "as\(a)-\(n)", sha256: nil, sizeBytes: 30_000_000, mime: "audio/flac"), compat: nil, rev: rev))124                }125            }126            try await store.apply(WireLibraryDelta(since: 0, rev: rev, more: chunk < 5, artists: chunk == 0 ? artists : [], albums: albums, tracks: tracks, deleted: [], counts: WireCounts(artists: 1500, albums: 6000, tracks: 72000)))127        }128        let insertTime = Date().timeIntervalSince(insertStart)129        func time<T>(_ label: String, limit: Double, _ work: () async -> T) async -> T {130            let t = Date(); let r = await work(); let dt = Date().timeIntervalSince(t)131            print(String(format: "PERF %-34@ %7.1f ms", label as NSString, dt * 1000))132            XCTAssertLessThan(dt, limit, label); return r133        }134        print(String(format: "PERF %-34@ %7.1f ms", "first sync of 72 000 tracks" as NSString, insertTime * 1000))135        let albums = await time("all 6 000 albums, by artist", limit: 0.5) { await store.albums() }136        XCTAssertEqual(albums.count, 6000); XCTAssertEqual(albums[0].trackCount, 12)137        _ = await time("recent albums (home)", limit: 0.05) { await store.albums(sort: .recent, limit: 24) }138        let artistList = await time("all 1 500 artists", limit: 0.5) { await store.artists() }139        XCTAssertEqual(artistList.count, 1500)140        let one = await time("one album's tracks", limit: 0.02) { await store.albumTracks("al4242") }141        XCTAssertEqual(one.count, 12)142        let page = await time("a page of 200 tracks", limit: 0.25) { await store.tracks(sort: .title, limit: 200, offset: 30000) }143        XCTAssertEqual(page.count, 200)144        let hits = await time("search, 2 words, prefix", limit: 0.08) { await store.search("rivi blu") }145        XCTAssertFalse(hits.tracks.isEmpty)146        _ = await time("search, 1 letter (worst case)", limit: 0.25) { await store.search("s") }147        let stats = await time("library statistics", limit: 0.25) { await store.stats() }148        XCTAssertEqual(stats.tracks, 72000)149        // One changed track among 72 000 costs one row, not a rebuild.150        var t = WireTrack(id: "t4242-3", title: "Renommée unique", trackNo: 3, discNo: 1, durationMs: 1, year: nil, codec: "flac", container: "flac", sampleRate: nil, bitDepth: nil, channels: nil, bitrate: nil, webPlayable: "yes",151                          compatState: "none", artistId: "ar0", albumId: "al4242", genre: nil, lyricsState: nil, createdAt: now, file: nil, compat: nil, rev: rev + 1)152        t.title = "Renommée unique"153        let delta = WireLibraryDelta(since: rev, rev: rev + 1, more: false, artists: [], albums: [], tracks: [t], deleted: [], counts: WireCounts(artists: 1500, albums: 6000, tracks: 72000))154        _ = await time("incremental change of one track", limit: 0.05) { try? await store.apply(delta) }155        let found = await store.search("renommee unique")156        XCTAssertEqual(found.tracks.map(\.id), ["t4242-3"])157    }158}159
Files main
Menu

Theme