Cotton code
71 lines · 3.4 KB · SwiftRaw
#if os(iOS)import CottonKitimport XCTest@testable import CottonUI/// Where the music player finds a song's bytes (`MusicFiles`).final class MusicFilesTests: XCTestCase {    /// RULE: a song not on this phone is fetched and opened by the core (`media.ensure`), never read from the object's signed address: a person's song is kept sealed there (R6) and the decoder cannot read it.    func testASongNotHereIsFetchedAndOpenedByTheCore() async throws {        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)        defer { try? FileManager.default.removeItem(at: folder) }        let opened = folder.appendingPathComponent("0f0f")        let core = SongsCore(opened: opened)        let key = "db/music/0f0f.wav"        let url = try await MusicFiles.url(for: key, core: core).get()        XCTAssertEqual(url.pathExtension, "wav", "the decoder is handed the song's own extension")        XCTAssertEqual(try Data(contentsOf: url), Data("the opened song".utf8))        XCTAssertEqual(core.asked, [CottonMethod.readMediaPath, CottonMethod.mediaEnsure])        // Here now: read where it is, nothing fetched again.        _ = try await MusicFiles.url(for: key, core: core).get()        XCTAssertEqual(core.asked.filter { $0 == CottonMethod.mediaEnsure }.count, 1)        XCTAssertFalse(core.asked.contains(CottonMethod.mediaStream), "the signed address is never the player's")    }    /// RULE: a fetch that reached nothing is offline; any other refusal (a seal that does not open, a file not there) is unreadable.    func testWhatCouldNotBeFetched() async {        let nowhere = URL(fileURLWithPath: "/nowhere/at/all")        let offline = await MusicFiles.url(for: "db/music/aa.mp3", core: SongsCore(opened: nowhere, refusal: "unreachable_server"))        XCTAssertEqual(offline.failure, .offline)        let sealed = await MusicFiles.url(for: "db/music/aa.mp3", core: SongsCore(opened: nowhere, refusal: "seal_key_missing"))        XCTAssertEqual(sealed.failure, .unreadable)    }}private extension Result {    var failure: Failure? { if case .failure(let why) = self { why } else { nil } }}/// The core's `read.mediaPath` and `media.ensure` for one song: not here/// until ensured, which lands the opened file.private final class SongsCore: CottonCalling, @unchecked Sendable {    private let opened: URL    private let refusal: String?    private(set) var asked: [String] = []    init(opened: URL, refusal: String? = nil) {        self.opened = opened        self.refusal = refusal    }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        asked.append(method)        switch method {        case CottonMethod.mediaEnsure:            if let refusal { return #"{"ok":false,"error":{"code":"\#(refusal)","message":"not fetched"}}"# }            try Data("the opened song".utf8).write(to: opened)            return #"{"ok":true,"data":{"path":"\#(opened.path)","fetched":true}}"#        case CottonMethod.readMediaPath where FileManager.default.fileExists(atPath: opened.path):            return #"{"ok":true,"data":{"path":"\#(opened.path)"}}"#        default:            return #"{"ok":true,"data":{}}"#        }    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}    func close() {}}#endif