SPB Git

Repository Public

ProductionSmokeTests.swift 5.1 KB 75 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/ProductionSmokeTests.swift3// Description: Tests: read-only smoke test against the real cluster (runs only when a session token is provided).4import XCTest5import AVFoundation6@testable import SPMusicCore78/// Read-only checks against the production cluster: the catalogue synchronises, a real album track streams and9/// seeks by range, and a real file downloads and verifies. Nothing is written to the library or to the account.10///   SPMUSIC_PROD_URL=https://music.spboucher.ai SPMUSIC_PROD_TOKEN=<session token> swift test --filter ProductionSmokeTests11final class ProductionSmokeTests: XCTestCase {12    func testTheRealClusterSyncsStreamsSeeksAndDownloads() async throws {13        let env = ProcessInfo.processInfo.environment14        guard let token = env["SPMUSIC_PROD_TOKEN"], let base = env["SPMUSIC_PROD_URL"].flatMap(URL.init(string:)) else { throw XCTSkip("no production session provided") }15        let temp = FileManager.default.temporaryDirectory.appendingPathComponent("spmusic-prod-\(UUID().uuidString.prefix(6))")16        defer { try? FileManager.default.removeItem(at: temp) }17        let api = APIClient(baseURL: base, credentials: MemoryCredentialStore(), connectivity: Connectivity())18        try api.adopt(Credential(serverURL: base, sessionToken: token, csrfToken: "", account: Account(id: "", email: "", displayName: "", role: "listener", isOwner: false), expiresAt: nil))19        let account = try await AuthService(api: api).refresh()20        let s = try await LibrarySession(api: api, account: account, dataRoot: temp.appendingPathComponent("data"), libraryRoot: temp.appendingPathComponent("Library"))2122        let t0 = Date()23        let report = try await s.sync.sync()24        let stats = await s.store.stats()25        print(String(format: "PROD first sync: %d tracks, %d albums, %d artists in %.2f s", stats.tracks, stats.albums, stats.artists, Date().timeIntervalSince(t0)))26        XCTAssertTrue(report.full); XCTAssertGreaterThan(stats.tracks, 100); XCTAssertGreaterThan(stats.albums, 10)27        let again = try await s.sync.sync()28        XCTAssertEqual(again.tracksChanged, 0)2930        // A real FLAC of the library, a few tens of megabytes.31        let all = await s.store.tracks()32        let track = try XCTUnwrap(all.first { $0.codec == "flac" && $0.sizeBytes > 20_000_000 && $0.durationMs > 150_000 })33        let r = try await s.resolve(track, normalize: false)34        XCTAssertEqual(r.kind, .stream)35        let engine = OfflinePlayer.engine()36        let started = Date()37        engine.load(token: UUID(), source: r.source, typeHint: r.typeHint, autoplay: true)38        let first = OfflinePlayer.render(engine, seconds: 3, patience: 30)39        let firstSound = Date().timeIntervalSince(started)40        XCTAssertGreaterThan(Signal.rms(first[44100...]), 0.001, "the real track sounds")41        let fractionAtStart = r.source.bufferedFraction42        // Seek to three quarters of the track straight away: the bytes there are fetched by range.43        let target = Double(track.durationMs) / 1000 * 0.7544        let seekStart = Date()45        engine.seek(to: target)46        let after = OfflinePlayer.render(engine, seconds: 2, patience: 30)47        let seekTime = Date().timeIntervalSince(seekStart)48        XCTAssertGreaterThan(Signal.rms(after[22050...]), 0.001)49        XCTAssertEqual(engine.status().position, target + 2, accuracy: 1.0)50        print(String(format: "PROD stream: %@ %d Hz/%d bits, %.1f MB — first 3 s rendered after %.2f s (%.0f %% of the file received), seek to 75 %% playing after %.2f s (%.0f %% received)",51                     track.codec, track.sampleRate ?? 0, track.bitDepth ?? 0, Double(track.sizeBytes) / 1e6, firstSound, fractionAtStart * 100, seekTime, r.source.bufferedFraction * 100))52        XCTAssertLessThan(r.source.bufferedFraction, 0.95, "the seek did not wait for the whole file")53        engine.stop()5455        // Download another real track, verified against the cluster's SHA-256, then play it with no network.56        let siblings = await s.store.albumTracks(track.albumID)57        let other = try XCTUnwrap(siblings.first { $0.id != track.id })58        await s.downloads.start()59        let d0 = Date()60        _ = await s.downloads.enqueue([other.id])61        let deadline = Date().addingTimeInterval(180)62        while Date() < deadline, await s.store.track(other.id)?.isDownloaded != true { try await Task.sleep(nanoseconds: 100_000_000) }63        let fetched = await s.store.track(other.id)64        let done = try XCTUnwrap(fetched)65        XCTAssertTrue(done.isDownloaded)66        let file = try XCTUnwrap(s.storage.localFile(for: done))67        XCTAssertEqual(try StorageManager.sha256(of: file), other.sha256)68        print(String(format: "PROD download: %.1f MB in %.2f s, SHA-256 verified, stored as …/%@", Double(other.sizeBytes) / 1e6, Date().timeIntervalSince(d0), done.localRelativePath ?? ""))69        s.connectivity.forcedOffline = true70        let local = try await s.resolve(done, normalize: false)71        XCTAssertEqual(local.kind, .local); XCTAssertTrue(AudioDecoder.canDecode(local.source, typeHint: local.typeHint))72        await s.shutdown()73    }74}75
Files main
Menu

Theme