Cotton code
177 lines · 13.1 KB · SwiftRaw
import Foundationimport XCTestimport CottonKitimport CottonValues@testable import CottonUI/// The music player reads the core (`shell.player`): it draws `now`, the/// `queue` and the `face` as answered, and reports a play once.final class PlayerAnswerTests: XCTestCase {    private let answered = """    {"now": {"kind": "song", "table": "song", "id": "song-2", "title": "The Pier", "artist": "Ana Vell", "album": "album-1", "album_title": "Night Ferry",             "cover": "db/pictures/1.jpg", "duration_s": 200, "file": "db/music/2.mp3", "gain_db": -4.5},     "queue": [{"kind": "song", "table": "song", "id": "song-3", "title": "Gulls", "artist": "Ana Vell", "duration_s": 180, "file": "db/music/3.mp3", "gain_db": 0}],     "at": {"index": 1, "of": 3}, "played_after_s": 30,     "settings": {"crossfade_s": 6, "gapless": false, "replay_gain": "song", "speed": 1.5, "sleep_minutes": 0,                  "sleep_until": "2026-11-05T16:30:00.000Z", "shuffle": false},     "face": "song.turntable",     "faces": [{"id": "song.hifi", "label": "Hi-fi"}, {"id": "song.turntable", "label": "Turntable"}, {"id": "song.amp", "label": "Amp"}, {"id": "song.party", "label": "Party"}],     "words": {"nothing": "n", "offline": "o", "refused": "r", "locked": "l"},     "platform_action": "play"}    """    private func answer() throws -> PlayerAnswer {        try JSONDecoder().decode(PlayerAnswer.self, from: Data(answered.utf8))    }    /// RULE (shell.player, 5 Nov 2026): the player takes the core's answer as it is: the song playing with its file and gain, the queue after it, its place, the face worn and the knobs the engine honours.    func testTheAnswerIsReadAsTheCoreSaysIt() throws {        let answer = try answer()        XCTAssertEqual(answer.now, QueuedSong(id: "song-2", file: "db/music/2.mp3", title: "The Pier", artist: "Ana Vell", album: "album-1",                                              albumTitle: "Night Ferry", cover: "db/pictures/1.jpg", duration: 200, gain: -4.5))        XCTAssertEqual(answer.queue.map(\.id), ["song-3"])        XCTAssertEqual([answer.at.index, answer.at.of], [1, 3])        XCTAssertEqual(PlayerFace(face: answer.face), .turntable)        XCTAssertEqual(answer.faces.map(\.label), ["Hi-fi", "Turntable", "Amp", "Party"])        let knobs = PlayerKnobs(answer.settings)        XCTAssertEqual([knobs.crossfade, knobs.speed], [6, 1.5])        XCTAssertFalse(knobs.gapless)        XCTAssertEqual(answer.sleepsAt, Date(timeIntervalSince1970: 1_793_896_200))        struct Act: Decodable {            let action: RecordPlatformAction?            init(from decoder: Decoder) throws { action = try RecordPlatformAction.fromAnswer(decoder) }        }        guard case .play(let played)? = try JSONDecoder().decode(Act.self, from: Data(answered.utf8)).action else {            return XCTFail("an act's answer plays")        }        XCTAssertEqual(played, answer)    }    /// RULE (shell.player kinds, 6 Nov 2026): an episode or a film playing is `playing`, never a song: what it plays from, where the core says it starts, its skip and report cadence, its tracks, and what follows it; the music player holds no song then.    func testAnEpisodeOrAFilmIsReadAsPlaying() throws {        let film = """        {"now": {"kind": "film", "table": "film_episode", "id": "e5", "title": "Lowmarsh", "artist": "", "caption": "S2 E5 · The Long Night",                 "series": "s1", "cover": "db/photos/still.jpg", "duration_s": 1500, "gain_db": 0, "stream": "https://cotton.example.test/v1/stream/tok/db/films/e5/master.m3u8",                 "resume_at_s": 1312.5, "skip_s": 15, "save_every_s": 15, "played_after": 0.9, "next_after_s": 10,                 "tracks": {"subtitles": false, "subtitle_language": null, "audio_language": "hi"}},         "queue": [{"kind": "film", "table": "film_episode", "id": "e6", "title": "Lowmarsh", "artist": "", "caption": "S2 E6 · Fog", "duration_s": 1500, "gain_db": 0}],         "at": {"index": 0, "of": 2}, "played_after_s": 1350,         "settings": {"crossfade_s": 0, "gapless": true, "replay_gain": "off", "speed": 1, "sleep_minutes": 0, "shuffle": false},         "face": "song.hifi", "faces": [], "words": {"nothing": "n", "offline": "o", "refused": "r", "locked": "l"}, "platform_action": "play"}        """        let answer = try JSONDecoder().decode(PlayerAnswer.self, from: Data(film.utf8))        XCTAssertNil(answer.now)        XCTAssertEqual(answer.queue, [])        let playing = try XCTUnwrap(answer.playing)        XCTAssertEqual([playing.kind, playing.table, playing.id], ["film", "film_episode", "e5"])        XCTAssertEqual(playing.marquee, "S2 E5 · The Long Night")        XCTAssertEqual([playing.resumeAt, playing.skip, playing.saveEvery, playing.nextAfter], [1312.5, 15, 15, 10])        XCTAssertEqual(playing.tracks, PlayerPlaying.Tracks(subtitles: false, subtitleLanguage: nil, audioLanguage: "hi"))        XCTAssertNil(playing.file)        XCTAssertEqual(answer.following.map(\.caption), ["S2 E6 · Fog"])        let episode = #"{"now": {"kind": "episode", "table": "episode", "id": "p4", "title": "Episode 4", "artist": "Invented Hour", "podcast": "show-1", "duration_s": 1000, "gain_db": 0, "stream": "https://example.test/hour-4.mp3", "file": "hour-4.mp3", "resume_at_s": 0, "skip_s": 15, "save_every_s": 15, "played_after": 0.95, "next_after_s": 0}, "queue": [], "at": {"index": 0, "of": 1}, "played_after_s": 950, "settings": {"crossfade_s": 0, "gapless": true, "replay_gain": "off", "speed": 1, "sleep_minutes": 0, "shuffle": false}, "face": "song.hifi", "faces": [], "words": {"nothing": "n", "offline": "o", "refused": "r", "locked": "l"}}"#        let held = try XCTUnwrap(try JSONDecoder().decode(PlayerAnswer.self, from: Data(episode.utf8)).playing)        XCTAssertEqual([held.kind, held.file, held.stream, held.podcast, held.marquee], ["episode", "hour-4.mp3", "https://example.test/hour-4.mp3", "show-1", "Episode 4"])    }    /// RULE (17 Nov 2026): a film's tracks carry its own subtitle choice (a track, or off) and timing over the cinema's settings, with the timing control's words; an answer from before them reads as no choice and in time.    func testAFilmsOwnSubtitleChoiceAndTimingAreRead() throws {        func tracks(_ json: String) throws -> PlayerPlaying.Tracks {            try JSONDecoder().decode(PlayerPlaying.Tracks.self, from: Data(json.utf8))        }        let timing = #"{"title": "Subtitle timing", "earlier": "Earlier", "later": "Later", "reset": "Reset", "said": "0.3 s later"}"#        let chosen = try tracks(#"{"subtitles": true, "subtitle_language": null, "audio_language": null, "choice": {"language": "fr", "name": "French (made on your Mac)"}, "offset_ms": 300, "timing": \#(timing)}"#)        XCTAssertEqual(chosen.choice, .track(language: "fr", name: "French (made on your Mac)"))        XCTAssertEqual(chosen.offsetMs, 300)        XCTAssertEqual(chosen.timing?.said, "0.3 s later")        XCTAssertEqual(try tracks(#"{"subtitles": true, "choice": "off", "offset_ms": -1200}"#).choice, .off)        let before = try tracks(#"{"subtitles": true, "subtitle_language": "en", "audio_language": null}"#)        XCTAssertEqual(before, PlayerPlaying.Tracks(subtitles: true, subtitleLanguage: "en", audioLanguage: nil))        XCTAssertEqual([before.offsetMs], [0])        XCTAssertNil(before.choice)    }    /// RULE (shell.player kinds, 6 Nov 2026): an episode or a film reports where it stands as often as the core asks, with what was heard forward, and ends once.    func testAnEpisodeReportsWhereItStands() {        var heard = PlayHeard(table: "episode", id: "p4", from: 120)        for second in 121...135 { heard.tick(Double(second)) }        XCTAssertEqual(heard.standing(at: 135, duration: 1000),                       .object(["table": .text("episode"), "id": .text("p4"), "seconds": .number(15), "at_s": .number(135), "duration_s": .number(1000)]))        XCTAssertNotNil(heard.standing(at: 136, duration: nil), "standing is no end")        XCTAssertEqual(heard.report(ended: "finished", at: 1000, duration: 1000),                       .object(["table": .text("episode"), "id": .text("p4"), "seconds": .number(15), "at_s": .number(1000), "duration_s": .number(1000), "ended": .text("finished")]))        XCTAssertNil(heard.standing(at: 1000, duration: 1000), "ended, nothing more is told")    }    /// RULE (shell.player, 5 Nov 2026): the hand cycles the core's ring of faces, named as the core names them.    @MainActor    func testTheHandCyclesTheCoresRing() throws {        MusicNowPlaying.shared.hold(faces: try answer().faces)        XCTAssertEqual(PlayerFace.turntable.next, .amp)        XCTAssertEqual(PlayerFace.party.next, .hifi)        XCTAssertEqual(PlayerFace.amp.said, "Amp")        // The cassette joins the ring once the core names it (7 Nov 2026), after the party.        MusicNowPlaying.shared.hold(faces: try answer().faces + [PlayerAnswer.Face(id: "song.cassette", label: "Cassette")])        XCTAssertEqual(PlayerFace(face: "song.cassette"), .cassette)        XCTAssertEqual(PlayerFace.party.next, .cassette)        XCTAssertEqual(PlayerFace.cassette.next, .hifi)        XCTAssertEqual(PlayerFace.cassette.said, "Cassette")    }    /// RULE (shell.player, 5 Nov 2026): what was heard is the instrument's, forward only, and a play is reported once: the second report of the same play is none.    func testAPlayIsReportedOnce() {        var heard = PlayHeard(table: "song", id: "song-2")        for second in 1...10 { heard.tick(Double(second)) }        heard.tick(120)        heard.jumped(to: 0)        for second in 1...5 { heard.tick(Double(second)) }        XCTAssertEqual(heard.heard, 15, "a scrub is not heard")        XCTAssertEqual(heard.report(ended: "skipped", device: "iPhone"),                       .object(["table": .text("song"), "id": .text("song-2"), "seconds": .number(15), "ended": .text("skipped"), "device": .text("iPhone")]))        XCTAssertNil(heard.report(ended: "finished"), "a play is reported once")    }    /// RULE (Music gaps, 5 Nov 2026): a song on no album playing in Listening is its own player card, in front of the albums: the deck never shows a hole, and the card opens no album.    func testASongOnNoAlbumIsItsOwnPlayerCard() {        let album = TableRecord(id: "album-1", values: ["title": .text("Harbour Lights")])        let cards: [(record: TableRecord, card: DeckCard)] = [(album, DeckCard(face: "album.sleeve", corner: nil, pressing: false, pace: nil, plate: nil, fields: [:]))]        let loose = QueuedSong(id: "song-9", file: "db/music/9.mp3", title: "Paper Moon", artist: "Oru", cover: "db/pictures/9.jpg", duration: 120)        let dealt = ListeningCard.dealt(cards, song: loose, visiting: nil, face: .turntable, volume: nil)        XCTAssertEqual(dealt.map(\.record.id), ["song-9", "album-1"], "the song stands in front of the albums")        let player = dealt[0].card        XCTAssertEqual(ListeningCard.song(of: player), "song-9")        XCTAssertTrue(ListeningCard.isSingle(player))        XCTAssertEqual(player.face, PlayerFace.turntable.face.rawValue)        XCTAssertEqual([player.text("title"), player.text("photo")], ["Paper Moon", "db/pictures/9.jpg"])        let onAlbum = QueuedSong(id: "song-1", file: "db/music/1.mp3", title: "Low Tide", album: "album-1")        let held = ListeningCard.dealt(cards, song: onAlbum, visiting: nil, face: .hifi, volume: nil)        XCTAssertEqual(held.map(\.record.id), ["album-1"], "a song on an album plays on its album's card")        XCTAssertFalse(ListeningCard.isSingle(held[0].card))    }    /// RULE (Music leftovers, 7 Nov 2026): a song on no album as the core answers it (no album, no album title, no    /// cover) is its own player card on every player face, on an empty Listening too: its title and artist, no album    /// invented and no photo, so the face draws its no-cover look.    func testALoneSongAsTheCoreSaysItWearsTheNoCoverLook() throws {        let said = """        {"now": {"kind": "song", "table": "song", "id": "song-9", "title": "Paper Moon", "artist": "Oru", "duration_s": 40, "file": "db/music/9.mp3", "gain_db": 0},         "queue": [], "at": {"index": 0, "of": 1}, "played_after_s": 20,         "settings": {"crossfade_s": 0, "gapless": true, "replay_gain": "off", "speed": 1, "sleep_minutes": 0, "shuffle": false},         "face": "song.hifi", "faces": [{"id": "song.hifi", "label": "Hi-fi"}],         "words": {"nothing": "n", "offline": "o", "refused": "r", "locked": "l"}}        """        let lone = try XCTUnwrap(try JSONDecoder().decode(PlayerAnswer.self, from: Data(said.utf8)).now)        XCTAssertNil(lone.album)        for face in PlayerFace.allCases {            let dealt = ListeningCard.dealt([], song: lone, visiting: nil, face: face, volume: nil)            XCTAssertEqual(dealt.map(\.record.id), ["song-9"], "an empty Listening holds the lone song's card")            let player = dealt[0].card            XCTAssertTrue(ListeningCard.isSingle(player))            XCTAssertEqual(player.face, face.face.rawValue)            XCTAssertEqual([player.text("title"), player.text("artist")], ["Paper Moon", "Oru"])            XCTAssertNil(player.text("album"), "no album is invented")            XCTAssertNil(player.text("photo"), "no cover: the face's no-cover look")        }    }}