SPB Git

Repository Public

IntegrationTests.swift 23.4 KB 382 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music9// File             : Tests/AppTests/IntegrationTests.swift10// Description      : Simulator integration tests against the disposable backend11//                    (real HTTP, real audio).12// Module           : AppTests13// Repository       : https://git.spboucher.ai/sp-music-ios14// Created          : 2026-11-1715// Last Modified    : 2026-11-1716//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import AVFoundation90import Foundation91import MediaPlayer92import SPMusicCore93import Synchronization94import Testing9596/// End-to-end tests on the simulator against the disposable backend (Scripts/test-server.sh): real HTTP, real audio97/// decoding by AVFoundation, real files on disk. The library is synthetic (sine waves in every supported container).98/// Skipped — and reported as such — when the backend's address and credentials are not provided.99let testURL = ProcessInfo.processInfo.environment["SPMUSIC_TEST_URL"].flatMap(URL.init(string:))100let testSession = ProcessInfo.processInfo.environment["SPMUSIC_TEST_SESSION"]101102final class SettingsBox: Sendable {103    private let m = Mutex(TransferSettings())104    var value: TransferSettings { m.withLock { $0 } }105    func withLock(_ f: (inout TransferSettings) -> Void) { m.withLock { f(&$0) } }106}107108@MainActor109final class Stack {110    let api: APIClient111    let db: Database112    let files: OfflineFiles113    let downloads: DownloadManager114    let sync: SyncEngine115    let session = AudioSessionManager()116    let player: AudioPlayer117    let settings = SettingsBox()118    let dir: URL119120    /// `sharing`: a second stack over the same database and files — used to play offline what the first downloaded.121    init(base: URL, token: String?, online: Bool, sharing other: Stack? = nil) async throws {122        dir = other?.dir ?? FileManager.default.temporaryDirectory.appendingPathComponent("spmusic-it-\(UUID().uuidString)")123        files = other?.files ?? OfflineFiles(root: dir.appendingPathComponent("support"), caches: dir.appendingPathComponent("caches"))124        db = try other?.db ?? Database(url: files.databaseURL)125        api = APIClient(baseURL: base, tokens: InMemoryTokenStore(token), userAgent: "SPMusic-iOS/tests (iPhone; simulator)")126        let box = settings127        let status: NetworkStatus = online ? .wifi : .offline128        downloads = DownloadManager(db: db, api: api, files: files, configuration: .ephemeral, settings: { box.value }, network: { status })129        sync = SyncEngine(db: db, api: api)130        player = AudioPlayer(resolver: SourceResolver(api: api, downloads: downloads, settings: { box.value }, network: { status }), session: session)131        player.player.volume = 0132        session.configure()133        await downloads.start()134    }135    func settle(_ seconds: TimeInterval = 60) async throws {136        let deadline = Date().addingTimeInterval(seconds)137        while Date() < deadline {138            if await db.downloads(states: [.queued, .running, .preparing]).isEmpty { return }139            try await Task.sleep(for: .milliseconds(50))140        }141        Issue.record("downloads did not settle in \(seconds) s")142    }143    func until(_ seconds: TimeInterval, _ what: String, _ condition: @MainActor () -> Bool) async -> Bool {144        let deadline = Date().addingTimeInterval(seconds)145        while Date() < deadline { if condition() { return true }; try? await Task.sleep(for: .milliseconds(50)) }146        Issue.record("timed out after \(seconds) s waiting for: \(what) — position \(player.position), playing \(player.isPlaying), buffering \(player.isBuffering), error \(String(describing: player.error))")147        return false148    }149    func track(_ title: String) async throws -> Track { try #require(await db.allTracks().first { $0.title == title }, "track \(title)") }150    func album(_ title: String) async throws -> Album { try #require(await db.albums().first { $0.title == title }, "album \(title)") }151    func cleanup() { player.stop(); try? FileManager.default.removeItem(at: dir) }152}153154@Suite(.serialized, .enabled(if: testURL != nil && testSession != nil, "test backend not configured (run Scripts/test-server.sh up)")) @MainActor155struct IntegrationTests {156    let base = testURL!157158    @Test func signsInWithARecoveryCodeAndSignsOut() async throws {159        let code = try #require(ProcessInfo.processInfo.environment["SPMUSIC_TEST_RECOVERY_1"])160        let s = try await Stack(base: base, token: nil, online: true); defer { s.cleanup() }161        #expect(try await s.api.sessionInfo().authenticated == false)162        await #expect(throws: APIError.self) { try await s.api.librarySync(since: 0) }163        try await s.api.loginWithRecoveryCode(code)164        let info = try await s.api.sessionInfo()165        #expect(info.authenticated); #expect(info.user?.isOwner == true)166        #expect(try await s.api.sessions().contains { $0.current && $0.userAgent.hasPrefix("SPMusic-iOS") })     // the device shows up in "Compte"167        try await s.api.logout()168        #expect(try await s.api.sessionInfo().authenticated == false)169        await #expect(throws: APIError.self) { try await s.api.loginWithRecoveryCode(code) }                      // one use only170    }171172    @Test func aDeviceLinkApprovedElsewhereOpensItsOwnSession() async throws {173        struct Decide: Encodable, Sendable { var userCode: String; var approve: Bool }174        let device = try await Stack(base: base, token: nil, online: true); defer { device.cleanup() }175        let browser = APIClient(baseURL: base, tokens: InMemoryTokenStore(testSession))           // stands in for the signed-in browser at /appareil176        let auth = AuthService(api: device.api, defaults: UserDefaults(suiteName: "spmusic-it-\(UUID().uuidString)")!)177        let link = try await auth.startDeviceLink(deviceName: "SP Music — iPhone (tests)")178        #expect(link.userCode.count == 9); #expect(link.verificationUrl.contains("/appareil?code="))179        #expect(try await device.api.pollDeviceLink(deviceCode: link.deviceCode).status == "pending")180        _ = try await browser.sessionInfo()181        try await browser.send("POST", "api/v1/auth/device/decide", body: Decide(userCode: link.userCode, approve: true), as: APIClient.Empty.self)182        try await auth.awaitDeviceLink(link)183        #expect(auth.state == .signedIn); #expect(auth.me?.isOwner == true)184        #expect(try await device.api.sessions().contains { $0.current && $0.method == "device" })185        await #expect(throws: APIError.self) { _ = try await device.api.pollDeviceLink(deviceCode: link.deviceCode) }       // consumed: one use186        await auth.signOut()187        #expect(auth.state == .signedOut); #expect(!device.api.hasSession)188    }189190    @Test func synchronisesTheCatalogueThenOnlyChanges() async throws {191        let s = try await Stack(base: base, token: testSession, online: true); defer { s.cleanup() }192        let first = try await s.sync.sync()193        let counts = await s.db.counts()194        #expect(first.full); #expect(counts.tracks == 17); #expect(counts.albums == 5)195        #expect(await s.db.tracks(albumId: try await s.album("Fréquences").id).map(\.trackNo) == [1, 2, 3, 4, 5, 6])196        #expect(await s.db.search("helene").artists.first?.name == "Hélène Côté")197        let hi = try await s.track("FLAC 24-96")198        #expect(hi.formatDescription == "FLAC · 24 bits / 96 kHz"); #expect(hi.isHiRes); #expect(hi.file?.sha256?.count == 64)199        let second = try await s.sync.sync()200        #expect(!second.full); #expect(second.catalogRows == 0)201202        // Favourite and playlist round trip with the server.203        let t = try await s.track("Éclat 1")204        await s.sync.setFavorite(kind: "track", id: t.id, on: true)205        #expect(try await s.api.userSync().favoriteTracks.contains { $0.id == t.id })206        await s.sync.setFavorite(kind: "track", id: t.id, on: false)207        let pl = try await s.api.createPlaylist(name: "Test iOS \(Int.random(in: 1000...9999))", trackIds: [t.id, hi.id])208        try await s.sync.refreshAccount()209        var entries = await s.db.playlistTracks(id: pl)210        #expect(entries.map(\.title) == ["Éclat 1", "FLAC 24-96"])211        try await s.api.orderPlaylist(id: pl, entryIds: entries.reversed().compactMap(\.entryId))212        try await s.sync.refreshAccount(); entries = await s.db.playlistTracks(id: pl)213        #expect(entries.map(\.title) == ["FLAC 24-96", "Éclat 1"])214        try await s.api.deletePlaylist(id: pl)215        try await s.sync.refreshAccount()216        #expect(await s.db.playlist(id: pl) == nil)217    }218219    @Test(arguments: ["Onde 220 Hz", "FLAC 24-48", "FLAC 24-96", "MP3 320", "AAC 256", "ALAC 16-44", "WAV 16-44", "AIFF 16-44"])220    func streamsAndDecodes(_ title: String) async throws {221        let s = try await Stack(base: base, token: testSession, online: true); defer { s.cleanup() }222        _ = try await s.sync.sync()223        let t = try await s.track(title)224        s.player.play([t])225        #expect(await s.until(20, "\(title) to play 1.5 s from the stream") { s.player.position >= 1.5 && s.player.error == nil })226        #expect(s.player.source?.isLocal == false); #expect(s.player.source?.variant == .original)          // the original file, decoded by iOS227        #expect(abs(s.player.duration - t.duration) < 0.6)228        s.player.seek(to: t.duration - 6)229        #expect(await s.until(15, "playback to continue after a seek near the end") { s.player.position >= t.duration - 5 && s.player.position < t.duration })230    }231232    @Test func compactQualityStreamsTheAACRendition() async throws {233        let s = try await Stack(base: base, token: testSession, online: true); defer { s.cleanup() }234        _ = try await s.sync.sync()235        s.settings.withLock { $0.streamQualityWifi = .compact }236        s.player.play([try await s.track("ALAC 16-44")])                                                       // its rendition exists already237        #expect(await s.until(20, "the rendition to play") { s.player.position >= 1 })238        #expect(s.player.source?.variant == .compat)239        s.player.play([try await s.track("Onde 523 Hz")])                                                      // this one is prepared on demand by the server240        #expect(await s.until(30, "the on-demand rendition to play") { s.player.position >= 1 })241        #expect(s.player.source?.variant == .compat)242    }243244    @Test func downloadsAnAlbumAndPlaysItWithNoNetwork() async throws {245        let online = try await Stack(base: base, token: testSession, online: true); defer { online.cleanup() }246        _ = try await online.sync.sync()247        let album = try await online.album("Fréquences")248        await online.downloads.pin(.album, album.id)249        try await online.settle()250        let status = await online.downloads.pinStatus(.album, album.id)251        #expect(status.complete); #expect(status.total == 6)252        for t in await online.db.tracks(albumId: album.id) {253            let local = try #require(await online.downloads.localFile(trackId: t.id))254            #expect(try FileHash.sha256(of: local.url) == t.file?.sha256)                                       // byte-identical to MacLustr's original255            #expect(local.url.path.contains("/support/Media/"))256        }257        let art = try online.files.artworkURL(artworkId: try #require(album.artworkId))258        #expect(FileManager.default.fileExists(atPath: art.path))                                               // the cover is on the device too259260        // "Aeroplane mode": no network, no session, and a server address nothing answers at.261        let off = try await Stack(base: URL(string: "http://127.0.0.1:9")!, token: nil, online: false, sharing: online)262        #expect(await off.db.albums(downloadedOnly: true).map(\.title) == ["Fréquences"])263        #expect(await off.db.search("onde", downloadedOnly: true).tracks.count == 6)264        let tracks = await off.db.tracks(albumId: album.id, downloadedOnly: true)265        off.player.play(tracks)266        #expect(await off.until(10, "local playback to start") { off.player.position >= 1 })267        #expect(off.player.source?.isLocal == true); #expect(off.player.error == nil)268        off.player.next()269        #expect(await off.until(10, "the next track to play") { off.player.queue.index == 1 && off.player.position >= 0.5 })270        // The track ends by itself: the prepared item takes over without a reload.271        off.player.seek(to: tracks[1].duration - 2)272        #expect(await off.until(15, "automatic change of track") { off.player.queue.index == 2 && off.player.position >= 0.5 && off.player.position < 6 && off.player.isPlaying })273        #expect(off.player.source?.isLocal == true)274        off.player.setRepeat(.one); off.player.seek(to: tracks[2].duration - 1.5)275        #expect(await off.until(15, "repeat-one to restart the track") { off.player.queue.index == 2 && off.player.position >= 0.3 && off.player.position < 5 })276        off.player.setRepeat(.off); off.player.setShuffle(true)277        #expect(Set(off.player.queue.tracks.map(\.id)) == Set(tracks.map(\.id)))278        off.player.pause()279        let at = off.player.position280        try await Task.sleep(for: .seconds(1))281        #expect(abs(off.player.position - at) < 0.3); #expect(!off.player.isPlaying)282        // A track that is not on the device says so instead of hanging.283        off.player.play([try await off.track("MP3 320")])284        #expect(await off.until(5, "the offline error") { off.player.error == .offline })285        off.player.stop()286    }287288    @Test func aPlaylistDownloadReusesFilesAlreadyOnTheDevice() async throws {289        let s = try await Stack(base: base, token: testSession, online: true); defer { s.cleanup() }290        _ = try await s.sync.sync()291        let album = try await s.album("Aurores")292        let albumTracks = await s.db.tracks(albumId: album.id)293        let extra = try await s.track("MP3 320")294        let pl = try await s.api.createPlaylist(name: "Route \(Int.random(in: 1000...9999))", trackIds: [albumTracks[2].id, extra.id, albumTracks[0].id])295        try await s.sync.refreshAccount()296        await s.downloads.pin(.album, album.id); try await s.settle()297        await s.downloads.pin(.playlist, pl); try await s.settle()298        #expect(await s.db.downloads(states: [.done]).count == 4)                                               // 3 of the album + 1 new, not 6299        #expect(await s.db.playlistTracks(id: pl, downloadedOnly: true).map(\.title) == ["Éclat 3", "MP3 320", "Éclat 1"])   // the playlist's own order300        await s.downloads.unpin(.album, album.id)301        #expect(Set(await s.db.downloads(states: [.done]).map(\.trackId)) == [albumTracks[2].id, extra.id, albumTracks[0].id])302        #expect(await s.downloads.storageReport().tracks == 3)303        await s.downloads.removeEverything()304        #expect(await s.downloads.storageReport().audioBytes == 0)305        try await s.api.deletePlaylist(id: pl)306    }307308    @Test func aLargeDownloadCanBePausedAndResumed() async throws {309        let s = try await Stack(base: base, token: testSession, online: true); defer { s.cleanup() }310        _ = try await s.sync.sync()311        let t = try await s.track("Bruit blanc")312        let size = try #require(t.file?.sizeBytes)313        #expect(size > 20_000_000)314        await s.downloads.pin(.track, t.id)315        var sawProgress = false316        for await p in s.downloads.updates where p.trackId == t.id {317            if p.state == .running, p.bytesDone > 0, p.bytesDone < size { sawProgress = true; break }318            if p.state == .done || p.state == .failed { break }319        }320        await s.downloads.pause(t.id)321        let paused = try #require(await s.db.download(trackId: t.id))322        if paused.state == .done { print("NOTE: the transfer finished before it could be paused (fast link); resume path not exercised in this run") }323        else {324            #expect(sawProgress); #expect(paused.state == .paused)325            try await Task.sleep(for: .milliseconds(600))326            #expect(await s.downloads.localFile(trackId: t.id) == nil)327            await s.downloads.resume(t.id)328        }329        try await s.settle(120)330        let local = try #require(await s.downloads.localFile(trackId: t.id))331        #expect(try FileHash.sha256(of: local.url) == t.file?.sha256)                                           // whole and intact after the interruption332    }333334    @Test func publishesNowPlayingInfoAndReactsToTheSystem() async throws {335        let s = try await Stack(base: base, token: testSession, online: true); defer { s.cleanup() }336        _ = try await s.sync.sync()337        let tracks = await s.db.tracks(albumId: try await s.album("Fréquences").id)338        s.player.artworkProvider = { _ in UIGraphicsImageRenderer(size: CGSize(width: 64, height: 64)).image { $0.fill(CGRect(x: 0, y: 0, width: 64, height: 64)) } }339        s.player.play(tracks, startAt: 1)340        #expect(await s.until(20, "playback") { s.player.position >= 1 })341        let info = s.player.nowPlaying.currentInfo342        #expect(info[MPMediaItemPropertyTitle] as? String == "Onde 262 Hz"); #expect(info[MPMediaItemPropertyArtist] as? String == "Les Sinusoïdes")343        #expect(info[MPMediaItemPropertyAlbumTitle] as? String == "Fréquences"); #expect((info[MPMediaItemPropertyPlaybackDuration] as? Double ?? 0) > 39)344        #expect(info[MPNowPlayingInfoPropertyPlaybackRate] as? Double == 1); #expect(info[MPMediaItemPropertyArtwork] is MPMediaItemArtwork)345        #expect(info[MPNowPlayingInfoPropertyPlaybackQueueIndex] as? Int == 1); #expect(info[MPNowPlayingInfoPropertyPlaybackQueueCount] as? Int == 6)346        #expect(MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String == "Onde 262 Hz")347        let c = MPRemoteCommandCenter.shared()348        #expect(c.playCommand.isEnabled && c.pauseCommand.isEnabled && c.nextTrackCommand.isEnabled && c.previousTrackCommand.isEnabled && c.changePlaybackPositionCommand.isEnabled)349350        // The notifications iOS sends for a phone call and for AirPods taken out, posted by hand: the simulator has351        // neither. This checks the app's reaction, not the system's behaviour.352        let session = AVAudioSession.sharedInstance()353        NotificationCenter.default.post(name: AVAudioSession.interruptionNotification, object: session, userInfo: [AVAudioSessionInterruptionTypeKey: AVAudioSession.InterruptionType.began.rawValue])354        s.player.player.pause()                                                                                  // what the system does to the player during a call355        try await Task.sleep(for: .milliseconds(400))356        #expect(s.player.isPlaying)                                                                              // still meant to play: it must come back357        #expect(s.player.nowPlaying.currentInfo[MPNowPlayingInfoPropertyPlaybackRate] as? Double == 0)358        let before = s.player.position359        NotificationCenter.default.post(name: AVAudioSession.interruptionNotification, object: session, userInfo: [360            AVAudioSessionInterruptionTypeKey: AVAudioSession.InterruptionType.ended.rawValue, AVAudioSessionInterruptionOptionKey: AVAudioSession.InterruptionOptions.shouldResume.rawValue])361        #expect(await s.until(10, "playback to resume after the interruption") { s.player.position > before + 0.8 })362        NotificationCenter.default.post(name: AVAudioSession.routeChangeNotification, object: session, userInfo: [AVAudioSessionRouteChangeReasonKey: AVAudioSession.RouteChangeReason.oldDeviceUnavailable.rawValue])363        #expect(await s.until(5, "pause when the output disappears") { !s.player.isPlaying && s.player.player.rate == 0 })364    }365366    @Test func aTrackPlayedToTheEndReachesTheServerHistory() async throws {367        let s = try await Stack(base: base, token: testSession, online: true); defer { s.cleanup() }368        _ = try await s.sync.sync()369        let t = try await s.track("Éclat 2")370        let played = Mutex<PlayEvent?>(nil)371        s.player.onPlayed = { e in played.withLock { $0 = e } }372        s.player.play([t])373        #expect(await s.until(40, "the 12 s track to end") { played.withLock { $0 } != nil })374        let e = try #require(played.withLock { $0 })375        #expect(e.completed); #expect(e.trackId == t.id); #expect(e.source == "stream"); #expect(e.listenedMs > 9000)376        #expect(!s.player.isPlaying)                                                                             // end of the queue377        await s.sync.recordPlay(e)378        #expect(try await s.api.history().contains { $0.id == e.id && $0.completed })379        #expect(await s.db.recentlyPlayed().first?.id == t.id)380    }381}382
Files main
Menu

Theme