Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/ClusterSupport.swift3// Description: Tests: base class for tests against the real test backend, and the offline rendering helper.4import XCTest5import AVFoundation6@testable import SPMusicCore78/// Base of the tests that run against the real backend started by Scripts/backend-dev.sh (skipped when it is not running).9class ClusterTestCase: XCTestCase {10 struct Env { let url: URL; let db: String; let port: UInt16; let script: String }11 static let env: Env? = {12 var e = ProcessInfo.processInfo.environment13 if e["SPMUSIC_TEST_URL"] == nil, let text = try? String(contentsOfFile: "/tmp/spmusic-backend-dev/env", encoding: .utf8) {14 for line in text.split(separator: "\n") { let p = line.replacingOccurrences(of: "export ", with: "").split(separator: "=", maxSplits: 1); if p.count == 2 { e[String(p[0])] = String(p[1]) } }15 }16 guard let u = e["SPMUSIC_TEST_URL"].flatMap(URL.init(string:)), let db = e["SPMUSIC_TEST_DB"], let port = e["SPMUSIC_TEST_PORT"].flatMap(UInt16.init), let script = e["SPMUSIC_TEST_SCRIPT"] else { return nil }17 return Env(url: u, db: db, port: port, script: script)18 }()19 nonisolated(unsafe) static var sharedCredential: Credential?2021 var env: Env!22 var proxy: FaultProxy!23 var temp: URL!2425 override func setUp() async throws {26 guard let e = Self.env else { throw XCTSkip("test backend not running (Scripts/backend-dev.sh start)") }27 var probe = URLRequest(url: e.url.appendingPathComponent("api/health")); probe.timeoutInterval = 328 guard let (_, r) = try? await URLSession.shared.data(for: probe), (r as? HTTPURLResponse)?.statusCode == 200 else { throw XCTSkip("test backend not answering") }29 env = e30 proxy = try FaultProxy(upstreamPort: e.port)31 temp = FileManager.default.temporaryDirectory.appendingPathComponent("spmusic-it-\(UUID().uuidString.prefix(8))")32 try FileManager.default.createDirectory(at: temp, withIntermediateDirectories: true)33 }34 override func tearDown() async throws {35 proxy?.stop()36 if let temp { try? FileManager.default.removeItem(at: temp) }37 }3839 @discardableResult40 func psql(_ sql: String) -> String {41 let p = Process(); p.executableURL = URL(fileURLWithPath: "/opt/homebrew/opt/postgresql@17/bin/psql")42 p.arguments = ["-At", "-v", "ON_ERROR_STOP=1", "-c", sql, env.db]43 let out = Pipe(); p.standardOutput = out; p.standardError = FileHandle.nullDevice44 try? p.run(); let data = out.fileHandleForReading.readDataToEndOfFile(); p.waitUntilExit()45 return String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""46 }47 func backend(_ command: String) {48 let p = Process(); p.executableURL = URL(fileURLWithPath: "/bin/bash"); p.arguments = [env.script, command]49 p.standardOutput = FileHandle.nullDevice; p.standardError = FileHandle.nullDevice50 try? p.run(); p.waitUntilExit()51 }5253 /// Real device linking against the backend: the app side is the code under test; the approval that a signed-in54 /// browser would give is written straight into the test database (the web side has its own tests on the cluster).55 func deviceLink(as email: String = "owner@example.test") async throws -> Credential {56 psql("DELETE FROM rate_limits")57 let api = APIClient(baseURL: env.url, credentials: MemoryCredentialStore(), connectivity: Connectivity())58 let auth = AuthService(api: api)59 let start = try await auth.startDeviceLink()60 let pending = try await auth.pollDeviceLink(start)61 XCTAssertNil(pending, "not approved yet")62 psql("UPDATE device_links SET approved_by = (SELECT id FROM users WHERE email = '\(email)'), decided_at = now() WHERE user_code = '\(start.userCode)'")63 let account = try await auth.awaitDeviceLink(start)64 XCTAssertEqual(account.email, email)65 return try XCTUnwrap(api.currentCredential)66 }6768 func credential() async throws -> Credential {69 if let c = Self.sharedCredential { return c }70 let c = try await deviceLink(); Self.sharedCredential = c; return c71 }7273 /// A session of the app talking to the backend through the fault proxy, with its own data and library folders.74 func makeSession(_ name: String = "a", credential given: Credential? = nil, concurrent: Int = 3) async throws -> LibrarySession {75 var c: Credential76 if let given { c = given } else { c = try await credential() }77 c.serverURL = proxy.url78 let api = APIClient(baseURL: proxy.url, credentials: MemoryCredentialStore(c), connectivity: Connectivity())79 return try await LibrarySession(api: api, account: c.account, dataRoot: temp.appendingPathComponent("data-\(name)"), libraryRoot: temp.appendingPathComponent("Library-\(name)"), maxConcurrentDownloads: concurrent)80 }8182 func waitUntil(_ timeout: TimeInterval = 20, _ what: String = "condition", file: StaticString = #filePath, line: UInt = #line, _ cond: () async -> Bool) async {83 let deadline = Date().addingTimeInterval(timeout)84 while Date() < deadline { if await cond() { return }; try? await Task.sleep(nanoseconds: 50_000_000) }85 XCTFail("timed out waiting for \(what)", file: file, line: line)86 }8788 /// XCTUnwrap for values obtained with `await` (XCTUnwrap's autoclosure cannot await).89 func some<T>(_ v: T?, file: StaticString = #filePath, line: UInt = #line) throws -> T { try XCTUnwrap(v, file: file, line: line) }9091 func trackID(titled title: String) -> String { psql("SELECT id FROM tracks WHERE title = '\(title)'") }92}9394/// Plays a source through the real engine in offline rendering mode and returns what came out.95enum OfflinePlayer {96 static let rate = 44100.097 static func engine() -> AudioEngine { AudioEngine(offlineFormat: AVAudioFormat(standardFormatWithSampleRate: rate, channels: 2)!) }98 static func render(_ engine: AudioEngine, seconds: Double, patience: TimeInterval = 10) -> [Float] {99 var out: [Float] = []100 let total = Int(seconds * rate)101 var emptyRenders = 0102 while out.count < total {103 let deadline = Date().addingTimeInterval(patience)104 while !engine.isFed(), Date() < deadline {105 // A deck being connected to a new format needs the engine to render in order to finish.106 if engine.isReconnecting, let b = engine.render(frames: 256) { out += Signal.samples(b) } else { usleep(2000) }107 }108 _ = engine.status()109 // A render can come back empty while a deck is being reconnected to another format: try again shortly, never forever.110 guard let b = engine.render(frames: 2048), b.frameLength > 0 else {111 emptyRenders += 1112 if emptyRenders > 2000 { XCTFail("the engine stopped rendering"); break }113 usleep(1000); continue114 }115 out += Signal.samples(b)116 }117 return out118 }119}120