SPB Git

Repository Public

AdminTests.swift 6.3 KB 95 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/AdminTests.swift3// Description: Tests: administration API against the real test backend (import, duplicate, edit, cover, delete, health) and lyrics decoding.4import XCTest5@testable import SPMusicCore67final class AdminTests: ClusterTestCase {8    func testAnAdministratorImportsEditsAndDeletesThroughTheApp() async throws {9        guard let ffmpeg = Fixtures.ffmpeg else { throw XCTSkip("ffmpeg is not installed") }10        let s = try await makeSession()11        try await s.sync.sync()12        let admin = AdminAPI(api: s.api)13        let tag = String(UUID().uuidString.prefix(6))14        let file = temp.appendingPathComponent("import-\(tag).flac")15        try Fixtures.run(ffmpeg, ["-v", "error", "-nostdin", "-y", "-f", "lavfi", "-i", "sine=frequency=\(300 + Int.random(in: 0...400)):duration=9", "-ac", "2", "-c:a", "flac",16                                  "-metadata", "title=Importé \(tag)", "-metadata", "artist=Depuis le Mac", "-metadata", "album=Album \(tag)", "-metadata", "album_artist=Depuis le Mac", "-metadata", "track=1", file.path])17        // Sent in chunks through the cluster's own import pipeline, analysed by its worker.18        let progress = ProgressBox()19        let result = try await admin.importFile(file) { sent, total in progress.set(sent, total) }20        XCTAssertEqual(result.status, "ready"); XCTAssertEqual(result.trackTitle, "Importé \(tag)")21        XCTAssertEqual(progress.last.0, progress.last.1); XCTAssertGreaterThan(progress.last.1, 10_000)22        let before = await s.store.stats().tracks23        try await s.sync.sync()24        let after = await s.store.stats().tracks25        XCTAssertEqual(after, before + 1, "the new track reaches the library at the next sync")26        let track = try some(await s.store.tracks().first { $0.title == "Importé \(tag)" })27        XCTAssertEqual(track.sha256, try StorageManager.sha256(of: file), "the cluster stored the file byte for byte")2829        // The same file again is recognised, not stored twice.30        let again = try await admin.importFile(file)31        XCTAssertEqual(again.status, "duplicate")3233        // Album edit and cover, then the change comes back through sync.34        try await admin.updateAlbum(track.albumID, title: "Renommé \(tag)", artist: "Depuis le Mac", year: 2026, genre: "Essai")35        let cover = temp.appendingPathComponent("cover.png")36        try Fixtures.run(ffmpeg, ["-v", "error", "-nostdin", "-y", "-f", "lavfi", "-i", "color=c=green:s=500x500", "-frames:v", "1", cover.path])37        try await admin.setAlbumArtwork(track.albumID, image: try Data(contentsOf: cover))38        try await s.sync.sync()39        let album = try some(await s.store.album(track.albumID))40        XCTAssertEqual(album.title, "Renommé \(tag)"); XCTAssertEqual(album.year, 2026); XCTAssertEqual(album.genre, "Essai"); XCTAssertNotNil(album.artworkID)41        do { try await admin.updateAlbum(track.albumID, year: 99999); XCTFail("the cluster validates") } catch { XCTAssertEqual((error as? APIError).map { if case .http(400, _, _) = $0 { true } else { false } }, true) }4243        let health = try await admin.health()44        XCTAssertTrue(health.storage.available); XCTAssertTrue(health.worker.ok); XCTAssertEqual(health.library.tracks, after)45        let uploads = try await admin.uploads()46        XCTAssertTrue(uploads.contains { $0.id == result.id })4748        // Deleting on the cluster: gone from the library here at the next sync.49        try await admin.deleteAlbum(track.albumID)50        try await s.sync.sync()51        let gone = await s.store.track(track.id)52        XCTAssertNil(gone)53        let final = await s.store.stats().tracks54        XCTAssertEqual(final, before)55    }5657    func testAListenerCannotAdminister() async throws {58        let email = "auditeur-\(UUID().uuidString.prefix(6).lowercased())@example.test"59        psql("INSERT INTO users (email, display_name, role) VALUES ('\(email)', 'Auditeur', 'listener')")60        defer { psql("DELETE FROM users WHERE email = '\(email)'") }61        let c = try await deviceLink(as: email)62        XCTAssertFalse(c.account.isAdmin)63        let s = try await makeSession(credential: c)64        try await s.sync.sync()65        let count = await s.store.stats().tracks66        XCTAssertGreaterThan(count, 0, "a listener hears the library")67        do { _ = try await AdminAPI(api: s.api).health(); XCTFail() } catch { XCTAssertEqual(error as? APIError, .http(status: 403, code: "forbidden", message: "Administrator role required")) }68        let album = try some(await s.store.albums().first)69        do { try await AdminAPI(api: s.api).deleteAlbum(album.id); XCTFail() } catch { XCTAssertEqual((error as? APIError).map { if case .http(403, _, _) = $0 { true } else { false } }, true) }70        XCTAssertEqual(psql("SELECT count(*) FROM albums WHERE id = '\(album.id)'"), "1")71    }72}7374final class ProgressBox: @unchecked Sendable {75    private let lock = NSLock(); private var value: (Int64, Int64) = (0, 0)76    func set(_ a: Int64, _ b: Int64) { lock.withLock { value = (a, b) } }77    var last: (Int64, Int64) { lock.withLock { value } }78}7980final class LyricsDecodingTests: XCTestCase {81    func testSynchronisedLyricsWithWordTimingsDecodeAndSurviveTheCache() async throws {82        let json = #"{"state":"ready","language":"fr","source":"whisper","edited":false,"enabled":true,"lines":[{"t":1200,"e":3400,"text":"Sur la route encore","w":[[1200,1500,"Sur"],[1500,1700," la"],[1700,2600," route"],[2600,3400," encore"]]},{"t":5000,"e":6000,"text":"Ligne tapée à la main"}]}"#83        let l = try APIClient.decoder.decode(Lyrics.self, from: Data(json.utf8))84        XCTAssertEqual(l.state, "ready"); XCTAssertEqual(l.lines.count, 2)85        XCTAssertEqual(l.lines[0].words?.map(\.text), ["Sur", " la", " route", " encore"]); XCTAssertEqual(l.lines[0].words?[2].start, 1700)86        XCTAssertNil(l.lines[1].words)87        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("ly-\(UUID().uuidString.prefix(6))")88        defer { try? FileManager.default.removeItem(at: dir) }89        let store = try LibraryStore(path: dir.appendingPathComponent("l.sqlite").path)90        await store.cacheLyrics("t1", l)91        let back = await store.cachedLyrics("t1")92        XCTAssertEqual(back, l, "lyrics read offline are the ones that were fetched")93    }94}95
Files main
Menu

Theme