Repository Public
1// SP Music iOS2// File: Core/Tests/SPMusicCoreTests/CoreTests.swift3// Description: Unit tests of the core: queue, policy, security, API client, sync, downloads.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation9import Synchronization10import Testing11@testable import SPMusicCore1213func makeTrack(_ n: Int, album: String = "al", artist: String = "ar") -> Track {14 Track(id: FakeServer.uuid(n), title: "T\(n)", trackNo: n, discNo: 1, durationMs: 200_000, year: nil, codec: "flac", container: "flac", sampleRate: 44100, bitDepth: 16, channels: 2, bitrate: nil,15 compatState: "none", artistId: artist, artistName: "A", albumId: album, albumTitle: "Al", albumArtistName: "A", artworkId: nil, genre: nil, lyricsState: nil, file: nil, compat: nil,16 favorite: false, removedRemotely: false, entryId: nil)17}1819/// Deterministic generator so shuffle tests do not depend on luck.20struct LCG: RandomNumberGenerator { var s: UInt64 = 42; mutating func next() -> UInt64 { s = s &* 6364136223846793005 &+ 1442695040888963407; return s } }2122@Suite struct PlaybackQueueTests {23 let five = (1...5).map { makeTrack($0) }2425 @Test func advancesAndStopsAtTheEnd() {26 var q = PlaybackQueue(); q.replace(five, startAt: 3)27 #expect(q.current?.id == five[3].id)28 #expect(q.advance(auto: true) == .moved)29 #expect(q.indexAfterCurrent == nil)30 #expect(q.advance(auto: true) == .ended) // played to the end: playback stops31 #expect(q.advance(auto: false) == .none) // "next" on the last track does nothing32 #expect(q.index == 4)33 }34 @Test func repeatModes() {35 var q = PlaybackQueue(); q.replace(five, startAt: 4)36 q.repeatMode = .all37 #expect(q.indexAfterCurrent == 0)38 #expect(q.advance(auto: true) == .moved); #expect(q.index == 0)39 q.repeatMode = .one40 #expect(q.indexAfterCurrent == nil)41 #expect(q.advance(auto: true) == .restartCurrent); #expect(q.index == 0)42 #expect(q.advance(auto: false) == .moved) // the listener can still skip out of repeat-one43 q.cycleRepeat(); #expect(q.repeatMode == .off)44 }45 @Test func previousRestartsAfterThreeSeconds() {46 var q = PlaybackQueue(); q.replace(five, startAt: 2)47 #expect(q.previous(position: 10) == .restartCurrent); #expect(q.index == 2)48 #expect(q.previous(position: 1) == .moved); #expect(q.index == 1)49 _ = q.previous(position: 0)50 #expect(q.previous(position: 0) == .restartCurrent); #expect(q.index == 0)51 }52 @Test func shuffleKeepsTheCurrentTrackAndEveryTrackOnce() {53 var g = LCG()54 var q = PlaybackQueue(); q.replace(five, startAt: 2, shuffle: true, using: &g)55 #expect(q.current?.id == five[2].id); #expect(q.index == 0)56 #expect(Set(q.tracks.map(\.id)) == Set(five.map(\.id))); #expect(q.tracks.count == 5)57 q.setShuffle(false, using: &g)58 #expect(q.tracks.map(\.id) == five.map(\.id)); #expect(q.current?.id == five[2].id)59 q.setShuffle(true, using: &g)60 #expect(Array(q.tracks[...q.index]).map(\.id) == Array(five[...2]).map(\.id)) // what was played stays in place61 }62 @Test func editsKeepTheCurrentTrack() {63 var q = PlaybackQueue(); q.replace(five, startAt: 2)64 q.playNext([makeTrack(9)]); #expect(q.tracks[3].id == FakeServer.uuid(9)); #expect(q.index == 2)65 q.move(from: 0, to: 4); #expect(q.current?.id == five[2].id)66 q.move(from: q.index, to: 0); #expect(q.index == 0); #expect(q.current?.id == five[2].id)67 #expect(q.remove(at: 3) == false); #expect(q.current?.id == five[2].id)68 #expect(q.remove(at: 0) == true) // the current track itself69 q.clearUpcoming(); #expect(q.tracks.count == 1)70 }71}7273@Suite struct PolicyTests {74 @Test func streaming() {75 var s = TransferSettings()76 #expect(NetworkPolicy.stream(s, .offline) == .blocked(.offline))77 #expect(NetworkPolicy.stream(s, .wifi) == .allowed(.original))78 let cell = NetworkStatus(online: true, interface: .cellular, expensive: true)79 s.streamQualityCellular = .compact80 #expect(NetworkPolicy.stream(s, cell) == .allowed(.compact))81 s.streamOnCellular = false82 #expect(NetworkPolicy.stream(s, cell) == .blocked(.cellularNotAllowed))83 #expect(NetworkPolicy.stream(TransferSettings(), NetworkStatus(online: true, interface: .wifi, constrained: true)) == .allowed(.compact))84 }85 @Test func downloads() {86 var s = TransferSettings()87 let cell = NetworkStatus(online: true, interface: .cellular, expensive: true)88 #expect(NetworkPolicy.download(s, .wifi) == nil)89 #expect(NetworkPolicy.download(s, cell) == .cellularNotAllowed) // Wi-Fi only is the default90 #expect(NetworkPolicy.download(s, .offline) == .offline)91 s.downloadOnCellular = true92 #expect(NetworkPolicy.download(s, cell) == nil)93 #expect(NetworkPolicy.download(s, NetworkStatus(online: true, interface: .cellular, expensive: true, constrained: true)) == .lowDataMode)94 #expect(NetworkPolicy.needsCellularConfirmation(s, cell, bytes: 500 << 20))95 #expect(!NetworkPolicy.needsCellularConfirmation(s, cell, bytes: 10 << 20))96 #expect(!NetworkPolicy.needsCellularConfirmation(s, .wifi, bytes: 500 << 20))97 }98}99100@Suite struct SecurityTests {101 @Test func identifiersThatAreNotUUIDsNeverBecomePaths() throws {102 let files = OfflineFiles(root: FileManager.default.temporaryDirectory.appendingPathComponent("spm-\(UUID())"), caches: FileManager.default.temporaryDirectory.appendingPathComponent("spm-\(UUID())"))103 for bad in ["../../etc/passwd", "", "0000", "00000000-0000-4000-8000-00000000000/", "00000000-0000-4000-8000-0000000000001", "..%2F..%2Fx", "00000000_0000_4000_8000_000000000001"] {104 #expect(!SafeID.isValid(bad))105 #expect(throws: (any Error).self) { try files.mediaURL(trackId: bad, ext: "flac") }106 #expect(throws: (any Error).self) { try files.artworkURL(artworkId: bad) }107 }108 let u = try files.mediaURL(trackId: FakeServer.uuid(7), ext: "../../x")109 #expect(u.deletingLastPathComponent().standardizedFileURL == files.media.standardizedFileURL)110 #expect(u.pathExtension == "x")111 }112 @Test func base64URLRoundTrip() {113 let d = Data([0xfb, 0xff, 0xfe, 0x00, 0x01])114 let s = Base64URL.encode(d)115 #expect(!s.contains("+") && !s.contains("/") && !s.contains("="))116 #expect(Base64URL.decode(s) == d)117 }118 @Test func fileHashMatchesCryptoKit() throws {119 let url = FileManager.default.temporaryDirectory.appendingPathComponent("spm-hash-\(UUID())")120 var data = Data(count: 3_000_000); for i in stride(from: 0, to: data.count, by: 997) { data[i] = UInt8(i & 0xff) }121 try data.write(to: url); defer { try? FileManager.default.removeItem(at: url) }122 #expect(try FileHash.sha256(of: url) == FakeServer.sha(data))123 }124 @Test func passkeyAnswersUseTheWebAuthnJSONShape() throws {125 let c = PasskeyWire.assertion(credentialID: Data([1, 2, 3]), clientDataJSON: Data("{}".utf8), authenticatorData: Data([9]), signature: Data([8, 8]), userID: Data("u".utf8))126 let o = try JSONSerialization.jsonObject(with: JSONEncoder().encode(PasskeyWire.LoginVerify(challengeId: "c", response: c))) as! [String: Any]127 let r = o["response"] as! [String: Any], inner = r["response"] as! [String: Any]128 #expect(r["id"] as? String == "AQID"); #expect(r["rawId"] as? String == "AQID"); #expect(r["type"] as? String == "public-key")129 #expect(inner["clientDataJSON"] as? String == "e30"); #expect(inner["signature"] as? String == "CAg"); #expect(inner["userHandle"] as? String == "dQ")130 #expect(inner["attestationObject"] == nil)131 #expect(AuthService.setupToken(from: " https://music.spboucher.ai/setup#abcDEF_123 ") == "abcDEF_123")132 }133 @Test func formatLabelsDescribeTheFileOnly() {134 #expect(AudioFormat.describe(codec: "flac", container: "flac", sampleRate: 96000, bitDepth: 24, bitrate: nil) == "FLAC · 24 bits / 96 kHz")135 #expect(AudioFormat.describe(codec: "flac", container: "flac", sampleRate: 44100, bitDepth: 16, bitrate: nil) == "FLAC · 16 bits / 44,1 kHz")136 #expect(AudioFormat.describe(codec: "mp3", container: "mp3", sampleRate: 44100, bitDepth: nil, bitrate: 320_000) == "MP3 · 320 kbit/s")137 #expect(AudioFormat.describe(codec: "pcm_s16be", container: "aiff", sampleRate: 44100, bitDepth: 16, bitrate: nil).hasPrefix("AIFF"))138 #expect(AudioFormat.isHiRes(codec: "flac", sampleRate: 48000, bitDepth: 24)); #expect(!AudioFormat.isHiRes(codec: "aac", sampleRate: 96000, bitDepth: nil))139 #expect(normalized(" Hélène CÔTÉ ") == "helene cote")140 }141}142143/// These share the fake server (one at a time).144@Suite(.serialized) struct EngineTests {145 @Test func signInCapturesTheCookieAndMutationsCarryTheCSRFToken() async throws {146 let rig = try await Rig(); defer { rig.cleanup() }147 rig.server.addTrack(1, title: "Un", artist: 1, album: 1, no: 1)148 rig.tokens.write(nil)149 await #expect(throws: APIError.self) { try await rig.api.librarySync(since: 0) } // signed out: 401150 await #expect(throws: APIError.self) { try await rig.api.loginWithRecoveryCode("nope-nope-nope") }151 try await rig.api.loginWithRecoveryCode("aaaa-bbbb-cccc")152 #expect(rig.tokens.read() == "tok-2") // token taken from Set-Cookie153 try await rig.api.setFavorite(kind: "track", id: FakeServer.uuid(1), on: true) // fetches the CSRF token first154 #expect(rig.server.state.withLock { $0.favorites } == [FakeServer.uuid(1)])155 rig.server.state.withLock { $0.csrfRejectionsLeft = 1 } // token rotated server-side: one retry156 try await rig.api.setFavorite(kind: "track", id: FakeServer.uuid(1), on: false)157 #expect(rig.server.state.withLock { $0.favorites }.isEmpty)158 }159160 @Test func aRevokedSessionIsReportedOnce() async throws {161 let rig = try await Rig(); defer { rig.cleanup() }162 let hits = Mutex(0)163 rig.api.onUnauthenticated { hits.withLock { $0 += 1 } }164 rig.server.state.withLock { $0.token = "revoked-elsewhere" }165 do { _ = try await rig.api.librarySync(since: 0); Issue.record("should have failed") } catch let e as APIError { #expect(e.isUnauthenticated) }166 #expect(hits.withLock { $0 } == 1)167 rig.server.state.withLock { $0.offline = true }168 do { _ = try await rig.api.librarySync(since: 0); Issue.record("should have failed") } catch let e as APIError { #expect(e.isNetwork) }169 #expect(hits.withLock { $0 } == 1) // being offline is not being signed out170 }171172 @Test func synchronisationIsIncrementalAndAppliesDeletions() async throws {173 let rig = try await Rig(); defer { rig.cleanup() }174 for n in 1...6 { rig.server.addTrack(n, title: n == 3 ? "Éclat d'été" : "Titre \(n)", artist: n <= 3 ? 1 : 2, album: n <= 3 ? 1 : 2, no: n) }175 let first = try await rig.sync.sync()176 #expect(first.full); #expect(await rig.db.counts().tracks == 6); #expect(await rig.db.counts().albums == 2)177 #expect(await rig.db.search("eclat d'ete").tracks.map(\.id) == [FakeServer.uuid(3)]) // accents and case folded178 #expect(await rig.db.tracks(albumId: FakeServer.uuid(2001)).map(\.trackNo) == [1, 2, 3])179180 // Nothing changed: the second pass asks above the stored revision and applies nothing.181 let second = try await rig.sync.sync()182 #expect(!second.full); #expect(second.catalogRows == 0)183184 rig.server.rename(2, "Renommé"); rig.server.deleteTrack(5)185 let third = try await rig.sync.sync()186 #expect(third.catalogRows == 2) // one changed row + one tombstone, not the library187 #expect(await rig.db.track(id: FakeServer.uuid(2))?.title == "Renommé")188 #expect(await rig.db.track(id: FakeServer.uuid(5)) == nil)189 let since = rig.server.state.withLock { $0.requests.filter { $0.hasSuffix("/library/sync") }.count }190 #expect(since == 3)191 }192193 @Test func changesMadeOfflineAreSentWhenTheServerIsBack() async throws {194 let rig = try await Rig(); defer { rig.cleanup() }195 rig.server.addTrack(1, title: "Un", artist: 1, album: 1, no: 1)196 _ = try await rig.sync.sync()197 rig.server.state.withLock { $0.offline = true }198 await rig.sync.setFavorite(kind: "track", id: FakeServer.uuid(1), on: true)199 let play = PlayEvent(id: UUID().uuidString.lowercased(), trackId: FakeServer.uuid(1), playedAt: Date(), listenedMs: 61_000, completed: true, source: "local")200 await rig.sync.recordPlay(play)201 #expect(await rig.db.track(id: FakeServer.uuid(1))?.favorite == true) // visible at once on the device202 #expect(await rig.db.recentlyPlayed().map(\.id) == [FakeServer.uuid(1)])203 #expect(await rig.db.outboxCount() == 2)204 await #expect(throws: APIError.self) { _ = try await rig.sync.sync() } // still offline: nothing is lost205 #expect(await rig.db.outboxCount() == 2)206207 rig.server.state.withLock { $0.offline = false }208 _ = try await rig.sync.sync()209 #expect(await rig.db.outboxCount() == 0)210 #expect(rig.server.state.withLock { $0.favorites } == [FakeServer.uuid(1)])211 #expect(rig.server.state.withLock { $0.history.count } == 1)212 #expect(await rig.db.track(id: FakeServer.uuid(1))?.favorite == true)213 #expect(await rig.db.playCount() == 1) // the server's copy of the play is not a second play214 }215216 @Test func aDownloadIsVerifiedBeforeItCounts() async throws {217 let rig = try await Rig(); defer { rig.cleanup() }218 rig.server.addTrack(1, title: "Bon", artist: 1, album: 1, no: 1, bytes: 300_000)219 rig.server.addTrack(2, title: "Altéré", artist: 1, album: 1, no: 2, bytes: 300_000)220 rig.server.state.withLock { $0.corruptStream = [FakeServer.uuid(2)] }221 _ = try await rig.sync.sync()222 await rig.downloads.pin(.album, FakeServer.uuid(2001))223 try await rig.settle()224 let good = try #require(await rig.db.download(trackId: FakeServer.uuid(1)))225 #expect(good.state == .done)226 let local = try #require(await rig.downloads.localFile(trackId: FakeServer.uuid(1)))227 #expect(try FileHash.sha256(of: local.url) == good.sha256)228 #expect(local.url.path.hasPrefix(rig.files.media.path)) // persistent storage, not a cache229 let bad = try #require(await rig.db.download(trackId: FakeServer.uuid(2)))230 #expect(bad.state == .failed); #expect(bad.error == "checksum")231 #expect(await rig.downloads.localFile(trackId: FakeServer.uuid(2)) == nil) // a file that fails the check is not kept232 #expect(try FileManager.default.contentsOfDirectory(atPath: rig.files.staging.path).filter { $0.hasSuffix(".part") }.isEmpty)233 var status = await rig.downloads.pinStatus(.album, FakeServer.uuid(2001))234 #expect(status.pinned); #expect(status.done == 1); #expect(status.failed == 1); #expect(!status.complete)235236 rig.server.state.withLock { $0.corruptStream = [] } // retry once the server sends the right bytes237 await rig.downloads.resume(FakeServer.uuid(2))238 try await rig.settle()239 status = await rig.downloads.pinStatus(.album, FakeServer.uuid(2001))240 #expect(status.complete)241 }242243 @Test func aRefusedTransferIsNotMistakenForAudio() async throws {244 let rig = try await Rig(); defer { rig.cleanup() }245 rig.server.addTrack(1, title: "Un", artist: 1, album: 1, no: 1)246 _ = try await rig.sync.sync()247 rig.server.state.withLock { $0.streamStatus = 401 }248 await rig.downloads.pin(.track, FakeServer.uuid(1))249 try await rig.settle()250 let d = try #require(await rig.db.download(trackId: FakeServer.uuid(1)))251 #expect(d.state == .failed); #expect(d.error == "auth")252 #expect(try FileManager.default.contentsOfDirectory(atPath: rig.files.media.path).isEmpty)253 }254255 @Test func aTrackSharedByAnAlbumAndAPlaylistIsStoredOnceAndKeptWhileOneOfThemWantsIt() async throws {256 let rig = try await Rig(); defer { rig.cleanup() }257 for n in 1...3 { rig.server.addTrack(n, title: "T\(n)", artist: 1, album: 1, no: n) }258 rig.server.addTrack(4, title: "Ailleurs", artist: 2, album: 2, no: 1)259 let pl = FakeServer.uuid(5000)260 rig.server.state.withLock { $0.playlists = [(pl, "Route", [(FakeServer.uuid(6001), FakeServer.uuid(2)), (FakeServer.uuid(6002), FakeServer.uuid(4))])] }261 _ = try await rig.sync.sync()262 #expect(await rig.db.playlistTracks(id: pl).map(\.title) == ["T2", "Ailleurs"]) // order of the playlist kept263264 await rig.downloads.pin(.album, FakeServer.uuid(2001))265 await rig.downloads.pin(.playlist, pl)266 try await rig.settle()267 #expect(await rig.db.downloads(states: [.done]).count == 4) // T2 once, not twice268 let streams = rig.server.state.withLock { $0.requests.filter { $0.contains("/stream/") } }269 #expect(streams.count == 4)270 #expect(await rig.db.references(trackId: FakeServer.uuid(2)) == 2)271272 await rig.downloads.unpin(.album, FakeServer.uuid(2001))273 #expect(Set(await rig.db.downloads(states: [.done]).map(\.trackId)) == [FakeServer.uuid(2), FakeServer.uuid(4)]) // T2 survives: the playlist still wants it274 #expect(await rig.downloads.localFile(trackId: FakeServer.uuid(2)) != nil)275 #expect(await rig.downloads.localFile(trackId: FakeServer.uuid(1)) == nil)276277 await rig.downloads.unpin(.playlist, pl)278 #expect(await rig.db.downloads().isEmpty)279 #expect(try FileManager.default.contentsOfDirectory(atPath: rig.files.media.path).isEmpty)280 }281282 @Test func pinnedPlaylistsFollowTheirContentAndDownloadsSurviveAServerOutage() async throws {283 let rig = try await Rig(); defer { rig.cleanup() }284 for n in 1...3 { rig.server.addTrack(n, title: "T\(n)", artist: 1, album: 1, no: n) }285 let pl = FakeServer.uuid(5000)286 rig.server.state.withLock { $0.playlists = [(pl, "Route", [(FakeServer.uuid(6001), FakeServer.uuid(1))])] }287 _ = try await rig.sync.sync()288 await rig.downloads.pin(.playlist, pl)289 try await rig.settle()290291 rig.server.state.withLock { $0.playlists[0].entries.append((FakeServer.uuid(6002), FakeServer.uuid(3))) }292 _ = try await rig.sync.sync()293 await rig.downloads.reconcilePins() // the new entry is fetched without asking294 try await rig.settle()295 #expect(Set(await rig.db.downloads(states: [.done]).map(\.trackId)) == [FakeServer.uuid(1), FakeServer.uuid(3)])296297 // The cluster goes away: synchronisation fails, and nothing on the device is touched.298 rig.server.state.withLock { $0.offline = true }299 await #expect(throws: APIError.self) { _ = try await rig.sync.sync() }300 await rig.downloads.reconcilePins(); await rig.downloads.reconcile()301 #expect(await rig.db.downloads(states: [.done]).count == 2)302 #expect(await rig.db.allTracks(downloadedOnly: true).count == 2)303 #expect(await rig.db.search("t3", downloadedOnly: true).tracks.count == 1) // offline search over what is on the device304 #expect(await rig.db.albums(downloadedOnly: true).first?.trackCount == 2)305306 // The owner deletes a downloaded track from the server: the local copy stays, flagged.307 rig.server.state.withLock { $0.offline = false }; rig.server.deleteTrack(3)308 _ = try await rig.sync.sync()309 let kept = try #require(await rig.db.track(id: FakeServer.uuid(3)))310 #expect(kept.removedRemotely); #expect(await rig.downloads.localFile(trackId: FakeServer.uuid(3)) != nil)311312 // One track removed by hand: the playlist stays pinned for the rest, and the track does not come back by itself.313 await rig.downloads.removeTrack(FakeServer.uuid(1))314 await rig.downloads.reconcilePins(); try await rig.settle()315 #expect(await rig.db.download(trackId: FakeServer.uuid(1)) == nil)316 #expect(await rig.db.isPinned(.playlist, pl))317 }318319 @Test func aFileThatVanishedIsFetchedAgain() async throws {320 let rig = try await Rig(); defer { rig.cleanup() }321 rig.server.addTrack(1, title: "Un", artist: 1, album: 1, no: 1)322 _ = try await rig.sync.sync()323 await rig.downloads.pin(.track, FakeServer.uuid(1)); try await rig.settle()324 let url = try #require(await rig.downloads.localFile(trackId: FakeServer.uuid(1))).url325 try FileManager.default.removeItem(at: url)326 #expect(await rig.downloads.localFile(trackId: FakeServer.uuid(1)) == nil) // never claims a file that is not there327 await rig.downloads.reconcile(); try await rig.settle()328 #expect(await rig.downloads.localFile(trackId: FakeServer.uuid(1)) != nil)329 let est = await rig.downloads.estimate(trackIds: [FakeServer.uuid(1)])330 #expect(est == 0) // already here: nothing to fetch331 }332}333