Cotton code
669 lines · 43.1 KB · SwiftRaw
import CottonKitimport CottonValuesimport XCTest@testable import CottonUI/// Cinemas Dev on iPhone, the streaming build (assets/design/cinemas/CONTRACT-2.md): each `cinemas.*` answer reads as/// the contract shapes it, a refusal comes back in the core's words, the streaming root is Cinemas' own, and the invented library a walk runs on answers Home's rows in the contract's order with empty automatic/// rows left out and his groups kept in his order. Invented titles only.#if os(iOS)@MainActorfinal class CinemasAppTests: XCTestCase {    private func decode<T: Decodable>(_ json: String, as type: T.Type) throws -> T {        try JSONDecoder().decode(type, from: Data(json.utf8))    }    /// RULE: Home reads its featured title and its rows, each Item with its states (CONTRACT-2 "Home").    func testHomeReadsAsTheContractShapesIt() throws {        let home = try decode(#"""        {"featured":{"item":{"table":"film","id":"f1","title":"Night Ferry","year":"2019","kind":"film","poster":"films/f1/poster.jpg",                             "backdrop":null,"caption":null,"progress":0.42,"on_phone":"kept","preparing":false,"from":null,"minutes":124.0},                     "line":"Carry on · 1:12 of 2:04","play":"Resume","tv":"Play on TV"},         "rows":[{"id":"carry_on","title":"Carry on","group":null,"count":1,"more":false,                  "items":[{"table":"film_episode","id":"e4","title":"What the Fog Said","year":null,"kind":"episode","poster":null,"backdrop":null,                            "caption":"S1 E4","progress":0.35,"on_phone":null,"preparing":false,"from":null,"minutes":51}]},                 {"id":"group:g1","title":"Rainy Sundays","group":"g1","count":0,"more":false,"items":[]}],         "empty":null}        """#, as: CinemasHome.self)        XCTAssertEqual(home.featured?.item.title, "Night Ferry")        XCTAssertEqual(home.featured?.item.onPhone, .kept)        XCTAssertEqual(home.featured?.item.progress, 0.42)        XCTAssertEqual(home.featured?.play, "Resume")        XCTAssertEqual(home.rows.map(\.id), ["carry_on", "group:g1"])        XCTAssertEqual(home.rows[0].items[0].kind, .episode)        XCTAssertEqual(home.rows[0].items[0].caption, "S1 E4")        XCTAssertEqual(home.rows[1].group, "g1")        XCTAssertTrue(home.rows[1].items.isEmpty)    }    /// RULE: A library with no titles reads the core's empty words, and an Item of a kind the phone does not know yet    /// draws as a film.    func testAnEmptyHomeAndAnUnknownKindRead() throws {        let home = try decode(#"""        {"featured":null,"rows":[],"empty":{"title":"Your films will live here.","line":"Add films from Files.","add":"Add films"}}        """#, as: CinemasHome.self)        XCTAssertNil(home.featured)        XCTAssertEqual(home.empty?.add, "Add films")        let item = try decode(#"{"table":"film","id":"x","title":"Odd","kind":"hologram"}"#, as: CinemasItem.self)        XCTAssertEqual(item.kind, .film)        XCTAssertFalse(item.preparing)    }    /// RULE: A title reads Play's words, its acts, his groups with their ticks, the subtitle line and a series' seasons.    func testATitleReadsAsTheContractShapesIt() throws {        let title = try decode(#"""        {"item":{"table":"film","id":"s1","title":"Lowmarsh","year":"2021","kind":"series","poster":null,"backdrop":null,"caption":"S1 E4",                 "progress":0.35,"on_phone":null,"preparing":false,"from":"Priya","minutes":52},         "synopsis":"A constable and the marsh.","facts":["2021","2 seasons"],         "play":{"label":"Resume S1 E4","from_start":"Play from the start"},"tv":"Play on TV",         "acts":[{"id":"keep","label":"Keep on this phone"},{"id":"group","label":"Add to a category"}],         "groups":[{"id":"g1","name":"Rainy Sundays","in":true},{"id":"g2","name":"Watch again","in":false}],         "subtitles":{"line":null,"work":null},"preparing":null,"playable":true,         "seasons":[{"id":"se1","number":1.0,"title":null,"episodes":6.0,"watched":3.0}],"source":null}        """#, as: CinemasTitle.self)        XCTAssertEqual(title.play.label, "Resume S1 E4")        XCTAssertEqual(title.play.fromStart, "Play from the start")        XCTAssertEqual(title.acts.map(\.id), ["keep", "group"])        XCTAssertEqual(title.groups.filter(\.in).map(\.name), ["Rainy Sundays"])        XCTAssertEqual(title.seasons?.first?.watched, 3)        XCTAssertEqual(title.seasons?.first?.episodes, 6)        XCTAssertEqual(title.seasons?.first?.title, ShellLines.line("cinemas", "intake.season_title", ["number": "1"]), "a season with no name is called by its number")        XCTAssertNil(title.subtitles?.line, "no subtitle line, no line drawn")        XCTAssertEqual(title.item.from, "Priya")    }    /// RULE: A season's episodes read as an Item with its number, name, length and still beside it in one object.    func testASeasonReadsItsEpisodes() throws {        let season = try decode(#"""        {"season":{"id":"se1","number":1.0,"title":null,"series":"s1"},         "episodes":[{"table":"film_episode","id":"e1","title":"The Reed Cutter","kind":"episode","caption":"S1 E1","progress":null,                      "on_phone":"keeping","preparing":false,"number":1.0,"minutes":52.0,"episode_title":"The Reed Cutter",                      "synopsis":null,"still":"films/e1/still.jpg"}]}        """#, as: CinemasSeason.self)        XCTAssertEqual(season.episodes.first?.number, 1)        XCTAssertEqual(season.episodes.first?.minutes, 52)        XCTAssertEqual(season.episodes.first?.title, "The Reed Cutter")        XCTAssertEqual(season.episodes.first?.still, "films/e1/still.jpg")        XCTAssertEqual(season.episodes.first?.item.onPhone, .keeping)    }    /// RULE: A refusal comes back in the core's words for the screen to say where it stands.    func testARefusalIsSaidInTheCoresWords() async {        let core = ScriptedCore(["cinemas.home": .refuse(code: "unknown_method", message: "Cinemas cannot read its rows just now.")])        let read = await CinemasCoreSource(core: core).home()        guard case .refused(let line) = read else { return XCTFail("a refusal read as an answer") }        XCTAssertEqual(line, "Cinemas cannot read its rows just now.")    }    /// RULE: Adding a title to a group is one `groups.update {id, add}` call with the title's id.    func testAddingToAGroupIsOneUpdate() async throws {        let core = ScriptedCore([CottonMethod.groupsUpdate: .ok(#"{"group":{"id":"g1"}}"#)])        let item = CinemasItem(table: "film", id: "f1", title: "Night Ferry", kind: .film)        let done = await CinemasCoreSource(core: core).group("g1", item: item, in: true)        XCTAssertEqual(done.answer, true)        let callscall = await core.calls        let call = try XCTUnwrap(callscall.last { $0.method == CottonMethod.groupsUpdate })        let sent = try JSONDecoder().decode([String: JSONValue].self, from: Data(call.requestJSON.utf8))        XCTAssertEqual(sent["id"], .string("g1"))        XCTAssertEqual(sent["add"], .array([.string("f1")]))    }    /// RULE: What a title is goes to the core as `cinemas.kind {id, to}` and its words are the toast; the sheet's ticks read    /// `cinemas.title`'s own `groups` (never `groups.list`, which knows nothing of hidden: CONTRACT-2 HIDDEN).    func testKindAndTheTicksAskTheCore() async throws {        let title = #"""        {"item":{"table":"film","id":"f1","title":"Night Ferry","kind":"film"},"synopsis":null,"facts":[],         "play":{"label":"Play","from_start":null},"tv":"Play on TV","acts":[],"seasons":null,"source":null,         "groups":[{"id":"g1","name":"Rainy Sundays","in":true},{"id":"g2","name":"Kids","in":false}]}        """#        let core = ScriptedCore([            "cinemas.kind": .ok(#"{"id":"f1","kind":"clip","said":"Moved to Videos"}"#),            CottonMethod.cinemasTitle: .ok(title),        ])        let source = CinemasCoreSource(core: core)        let item = CinemasItem(table: "film", id: "f1", title: "Night Ferry", kind: .film)        let said = await source.kind(item, to: .clip).answer        XCTAssertEqual(said, "Moved to Videos")        let callskindCall = await core.calls        let kindCall = try XCTUnwrap(callskindCall.last { $0.method == "cinemas.kind" })        let sent = try JSONDecoder().decode([String: JSONValue].self, from: Data(kindCall.requestJSON.utf8))        XCTAssertEqual(sent["to"], .string("clip"))        XCTAssertEqual(sent["id"], .string("f1"))        let groupsRead = await source.groups(holding: item, hidden: false).answer        let groups = try XCTUnwrap(groupsRead)        XCTAssertEqual(groups.groups.map(\.holds), [true, false])        let calls = await core.calls        XCTAssertFalse(calls.contains { $0.method == CottonMethod.groupsList }, "never groups.list")        let titleCall = try XCTUnwrap(calls.last { $0.method == CottonMethod.cinemasTitle })        let asked = try JSONDecoder().decode([String: JSONValue].self, from: Data(titleCall.requestJSON.utf8))        XCTAssertEqual(asked["id"], .string("f1"))        XCTAssertNil(asked["hidden"])    }    /// RULE: `hidden: true` is said only when asked from inside Hidden; every other read says nothing of it, so the core    /// leaves hidden titles out (CONTRACT-2 HIDDEN). Hide sends `{id, hidden}`; the core's unlock is asked with `no_lock`    /// only when the phone has none, and `cinemas.lock` shuts it.    func testHiddenIsSaidOnlyFromInside() async throws {        let core = ScriptedCore([            CottonMethod.cinemasRow: .ok(#"{"title":"Films","items":[],"next":null}"#),            CottonMethod.cinemasSearch: .ok(#"{"items":[],"groups":[]}"#),            CottonMethod.cinemasGroups: .ok(#"{"groups":[]}"#),            CottonMethod.cinemasHide: .ok(#"{"id":"g1","hidden":true,"line":"Edits is hidden","undo":{"method":"cinemas.hide","args":{"id":"g1","hidden":false,"undo":"t-1"}}}"#),            CottonMethod.cinemasHidden: .ok(#"{"title":"Hidden","locked":true,"unlock":"Show hidden"}"#),            CottonMethod.cinemasUnlock: .ok(#"{"unlocked":true}"#),            CottonMethod.cinemasLock: .ok(#"{"unlocked":false}"#),        ])        let source = CinemasCoreSource(core: core)        _ = await source.row("films", after: nil)        _ = await source.row("group:g1", after: nil, filter: nil, hidden: true)        _ = await source.search("kite")        _ = await source.search("kite", hidden: true)        _ = await source.groups()        _ = await source.groups(hidden: true)        let calls = await core.calls        let said = try calls.map { try JSONDecoder().decode([String: JSONValue].self, from: Data($0.requestJSON.utf8))["hidden"] }        XCTAssertEqual(said, [nil, .bool(true), nil, .bool(true), nil, .bool(true)])        let hid = await source.hide("g1", hidden: true).answer        XCTAssertEqual(hid?.line, "Edits is hidden")        let place = await source.hiddenPlace().answer        XCTAssertEqual(place?.locked, true)        XCTAssertEqual(place?.unlock, "Show hidden")        let opened = await source.unlock(noLock: false).answer        XCTAssertEqual(opened, true)        let openedBare = await source.unlock(noLock: true).answer        XCTAssertEqual(openedBare, true)        let shut = await source.lock().answer        XCTAssertEqual(shut, true)        let after = await core.calls        let sent = try after.dropFirst(calls.count).map { ($0.method, try JSONDecoder().decode([String: JSONValue].self, from: Data($0.requestJSON.utf8))) }        XCTAssertEqual(sent.map(\.0), [CottonMethod.cinemasHide, CottonMethod.cinemasHidden, CottonMethod.cinemasUnlock, CottonMethod.cinemasUnlock, CottonMethod.cinemasLock])        XCTAssertEqual(sent[0].1, ["id": .string("g1"), "hidden": .bool(true)])        XCTAssertNil(sent[2].1["no_lock"], "a phone with a lock says nothing of it")        XCTAssertEqual(sent[3].1["no_lock"], .bool(true))        // Undo runs exactly as handed back: its method, its args, the one-use token with them.        let handed = try XCTUnwrap(hid?.undo)        _ = await source.undo(handed)        let last = await core.calls        let undoCall = try XCTUnwrap(last.last)        XCTAssertEqual(undoCall.method, "cinemas.hide")        let undoArgs = try JSONDecoder().decode([String: JSONValue].self, from: Data(undoCall.requestJSON.utf8))        XCTAssertEqual(undoArgs, ["id": .string("g1"), "hidden": .bool(false), "undo": .string("t-1")])    }    /// RULE: The hidden place reads as the contract writes it: `search_hint`, `no_lock`, `set_lock`, rows as Home's.    func testTheHiddenPlaceDecodes() throws {        let json = #"""        {"title":"Hidden","locked":false,"search_hint":"Search hidden titles","no_lock":"No lock","set_lock":"Set a screen lock",         "rows":[{"id":"group:g1","title":"Edits","group":"g1","count":1,"more":false,                  "items":[{"table":"film","id":"f1","title":"Cut 3","kind":"clip"}]}]}        """#        let place = try JSONDecoder().decode(CinemasHiddenPlace.self, from: Data(json.utf8))        XCTAssertEqual(place.rows.first?.group, "g1")        XCTAssertEqual(place.searchHint, "Search hidden titles")        XCTAssertEqual(place.noLock, "No lock")        XCTAssertEqual(place.setLock, "Set a screen lock")        let locked = try JSONDecoder().decode(CinemasHiddenPlace.self, from: Data(#"{"title":"Hidden","locked":true}"#.utf8))        XCTAssertTrue(locked.locked)        XCTAssertTrue(locked.rows.isEmpty)    }    /// RULE: To the Bin is `records.delete`, and its change is what Undo takes back with `records.undo`.    func testTheBinCarriesItsChangeForUndo() async throws {        let core = ScriptedCore([            "records.delete": .ok(#"{"change":{"id":"ch-9"}}"#),            CottonMethod.recordsUndo: .ok(#"{"ok":true}"#),        ])        let source = CinemasCoreSource(core: core)        let item = CinemasItem(table: "film", id: "f1", title: "Night Ferry", kind: .film)        let changeRead = await source.bin(item).answer        let change = try XCTUnwrap(changeRead)        XCTAssertEqual(change, "ch-9")        let got = await source.undo("ch-9").answer        XCTAssertEqual(got, true)        let callsundo = await core.calls        let undo = try XCTUnwrap(callsundo.last { $0.method == CottonMethod.recordsUndo })        XCTAssertTrue(undo.requestJSON.contains("ch-9"))    }    /// RULE: His groups come from `cinemas.groups` in his order, and a drag sends the whole order to `cinemas.groupsOrder`.    func testGroupsReadAndOrderInOneCall() async throws {        let core = ScriptedCore([            CottonMethod.cinemasGroups: .ok(#"{"groups":[{"id":"g1","name":"Rainy Sundays","count":3.0},{"id":"g2","name":"Kids","count":0}]}"#),            CottonMethod.cinemasGroupsOrder: .ok(#"{"groups":["g2","g1"]}"#),        ])        let source = CinemasCoreSource(core: core)        let groupsRead = await source.groups().answer        let groups = try XCTUnwrap(groupsRead)        XCTAssertEqual(groups.groups.map(\.count), [3, 0])        let got = await source.orderGroups(["g2", "g1"]).answer        XCTAssertEqual(got, true)        let callscall = await core.calls        let call = try XCTUnwrap(callscall.last { $0.method == CottonMethod.cinemasGroupsOrder })        let sent = try JSONDecoder().decode([String: JSONValue].self, from: Data(call.requestJSON.utf8))        XCTAssertEqual(sent["order"], .array([.string("g2"), .string("g1")]))    }    /// RULE: A title's acts say where they stand: `place: row` in the row of four with `short` and `second`, `more`    /// behind More (PUNCH Both 2).    func testActsCarryTheirPlaceShortAndSecond() throws {        let json = #"""        {"item":{"table":"film","id":"f1","title":"Night Ferry","kind":"film"},"synopsis":null,"facts":[],         "play":{"label":"Play","from_start":null},"tv":"Play on TV","groups":[],"seasons":null,"source":null,         "acts":[{"id":"keep","label":"Keep on this phone","short":"Keep","place":"row","second":"2.3 GB"},                 {"id":"bin","label":"Move to the Bin","short":"Bin","place":"more","second":null}]}        """#        let title = try JSONDecoder().decode(CinemasTitle.self, from: Data(json.utf8))        XCTAssertEqual(title.acts.first?.short, "Keep")        XCTAssertEqual(title.acts.first?.second, "2.3 GB")        XCTAssertEqual(title.acts.map { $0.place ?? "" }, ["row", "more"])    }    /// RULE: On this phone is the core's (`cinemas.onPhone {free_bytes}`), and the Mobile data switch turns    /// `films.keeping {cellular}` over (PUNCH Both 6).    func testOnPhoneAndTheMobileDataSwitchAskTheCore() async throws {        let core = ScriptedCore([            CottonMethod.cinemasOnPhone: .ok(#"{"title":"On this phone","space":"Cinemas 2 GB · 48 GB free","flight":{"line":"Ready for a flight: 2h 4m","what":"1 film. They play with no internet."},"items":[{"item":{"table":"film","id":"f1","title":"Night Ferry","kind":"film","on_phone":"kept"},"line":"2 GB"}],"empty":null}"#),            CottonMethod.filmsKeeping: .ok(#"{"keep_everything":false,"cellular":true,"budget_gb":64}"#),        ])        let source = CinemasCoreSource(core: core)        let pageRead = await source.onPhone(free: 48_000_000_000).answer        let page = try XCTUnwrap(pageRead)        XCTAssertEqual(page.flight?.line, "Ready for a flight: 2h 4m")        XCTAssertEqual(page.items.first?.line, "2 GB")        let now = await source.setCellular(true).answer        XCTAssertEqual(now, true)        let calls = await core.calls        let onPhone = try XCTUnwrap(calls.first { $0.method == CottonMethod.cinemasOnPhone })        let asked = try JSONDecoder().decode([String: JSONValue].self, from: Data(onPhone.requestJSON.utf8))        XCTAssertEqual(asked["free_bytes"], .number(48_000_000_000))        let keeping = try XCTUnwrap(calls.last { $0.method == CottonMethod.filmsKeeping })        let set = try JSONDecoder().decode([String: JSONValue].self, from: Data(keeping.requestJSON.utf8))        XCTAssertEqual(set["cellular"], .bool(true))    }    /// RULE: The remote's words are the core's (`cinemas.remote`), asked with where the film stands, its length and the    /// TV's name; between asks the phone keeps the time gone and the time left in the core's own form (PUNCH Both 8).    @MainActor    func testTheRemoteAsksTheCoreWithThePlace() async throws {        let core = ScriptedCore([            CottonMethod.cinemasRemote: .ok(#"{"playing":"Playing on Living room TV","title":"The Wardens","caption":"Lowmarsh · Season 2, Episode 5","at":"23:10","left":"−27:50","next":{"table":"film_episode","id":"e6","label":"Next episode"},"volume":"The phone's volume buttons change the TV's volume."}"#),        ])        let source = CinemasCoreSource(core: core)        let wordsRead = await source.remote(table: "film_episode", id: "e5", at: 1390, length: 3060, device: "Living room TV").answer        let words = try XCTUnwrap(wordsRead)        XCTAssertEqual(words.playing, "Playing on Living room TV")        XCTAssertEqual(words.next?.id, "e6")        let calls = await core.calls        let asked = try JSONDecoder().decode([String: JSONValue].self, from: Data(try XCTUnwrap(calls.first).requestJSON.utf8))        XCTAssertEqual(asked["at_s"], .number(1390))        XCTAssertEqual(asked["length_s"], .number(3060))        XCTAssertEqual(asked["device"], .string("Living room TV"))        XCTAssertEqual(CinemasTV.clock(1390), "23:10")        XCTAssertEqual(CinemasTV.clock(3725), "1:02:05")        let tv = CinemasTV()        let playing = FilmPlayback.OnTV(table: "film_episode", id: "e5", title: "The Wardens", caption: nil, cover: nil, at: 1390, length: 3060, paused: true)        XCTAssertEqual(tv.clock(playing).left, "−27:50", "the time left, not the length, in the core's words")    }    /// RULE: The Subtitles sheet draws `cinemas.subtitles`, and its acts ask the Mac through the core: find →    /// `records.command find_subtitles`, make → `generate_subtitles`, give → `films.subtitleFile {path}` (PUNCH Both 4).    @MainActor    func testSubtitlesActsAskTheCore() async throws {        let core = ScriptedCore([            CottonMethod.cinemasSubtitles: .ok(#"{"title":"Subtitles","line":"English","tracks":[{"language":"en","name":"English","from":"in the file","chosen":true}],"working":null,"acts":[{"id":"find","label":"Find subtitles"},{"id":"make","label":"Make them on your Mac"},{"id":"give","label":"Give a subtitle file"}]}"#),            "records.command": .ok(#"{"command":"find_subtitles","kind":"set"}"#),            CottonMethod.filmsSubtitleFile: .ok(#"{"key":"films/f1/given/sub-1.srt","language":"en","said":"Your Mac will add it"}"#),        ])        let source = CinemasCoreSource(core: core)        let item = CinemasItem(table: "film", id: "f1", title: "Night Ferry", kind: .film)        let pageRead = await source.subtitles(item).answer        let page = try XCTUnwrap(pageRead)        XCTAssertEqual(page.tracks.first?.from, "in the file")        XCTAssertEqual(page.acts.map(\.id), ["find", "make", "give"])        _ = await source.subtitlesAct("make", item: item, file: nil)        let said = await source.subtitlesAct("give", item: item, file: URL(fileURLWithPath: "/tmp/Night Ferry.en.srt")).answer        XCTAssertEqual(said, "Your Mac will add it")        let calls = await core.calls        let command = try XCTUnwrap(calls.first { $0.method == "records.command" })        let asked = try JSONDecoder().decode([String: JSONValue].self, from: Data(command.requestJSON.utf8))        XCTAssertEqual(asked["command"], .string("generate_subtitles"))        let given = try XCTUnwrap(calls.first { $0.method == CottonMethod.filmsSubtitleFile })        let file = try JSONDecoder().decode([String: JSONValue].self, from: Data(given.requestJSON.utf8))        XCTAssertEqual(file["path"], .string("/tmp/Night Ferry.en.srt"))    }    /// RULE: Send to a friend draws the Send step every app has (`shell.opened {step: send}`) and sends to the    /// person's number with `send.make`; its Undo is `send.undo` with the send's id (PUNCH Both 5).    @MainActor    func testSendToAFriendAsksTheCore() async throws {        let core = ScriptedCore([            CottonMethod.shellOpened: .ok(#"{"step":{"kind":"send","says":"Night Ferry · 2.1 GB goes","rows":[{"value":"+15550100001","words":"Arjun","number":"+15550100001","initials":"A","detail":"2.1 GB"}]}}"#),            CottonMethod.sendMake: .ok(#"{"id":"m1","receipt":{"words":"Sent Night Ferry to Arjun","undo":"Undo","undone":"Taken back"}}"#),            CottonMethod.sendUndo: .ok(#"{"state":"undone"}"#),        ])        let source = CinemasCoreSource(core: core)        let item = CinemasItem(table: "film", id: "f1", title: "Night Ferry", kind: .film)        let stepRead = await source.sendStep(item).answer        let step = try XCTUnwrap(stepRead)        let person = try XCTUnwrap(step.rows.first)        let sentRead = await source.send(item, to: person).answer        let sent = try XCTUnwrap(sentRead)        XCTAssertEqual(sent.words, "Sent Night Ferry to Arjun")        _ = await source.unsend(sent.id)        let calls = await core.calls        let opened = try JSONDecoder().decode([String: JSONValue].self, from: Data(try XCTUnwrap(calls.first { $0.method == CottonMethod.shellOpened }).requestJSON.utf8))        XCTAssertEqual(opened["step"], .string("send"))        let made = try JSONDecoder().decode([String: JSONValue].self, from: Data(try XCTUnwrap(calls.first { $0.method == CottonMethod.sendMake }).requestJSON.utf8))        XCTAssertEqual(made["to"], .string("+15550100001"))        XCTAssertEqual(made["table"], .string("film"))        XCTAssertEqual(calls.filter { $0.method == CottonMethod.sendMake }.count, 1, "a send is made once")        let undo = try JSONDecoder().decode([String: JSONValue].self, from: Data(try XCTUnwrap(calls.first { $0.method == CottonMethod.sendUndo }).requestJSON.utf8))        XCTAssertEqual(undo["id"], .string("m1"))    }    /// RULE: signed out, Send says so in Cinemas' words, not the core's (`not_connected`).    @MainActor    func testSendSignedOutSaysSignIn() async throws {        let core = ScriptedCore([CottonMethod.shellOpened: .refuse(code: "not_connected", message: "this phone is not connected to its database yet")])        let source = CinemasCoreSource(core: core)        let read = await source.sendStep(CinemasItem(table: "film", id: "f1", title: "Night Ferry", kind: .film))        guard case .refused(let line) = read else { return XCTFail("signed out, Send cannot read") }        XCTAssertEqual(line, CinemasWords.line("stream.send_sign_in"))        XCTAssertFalse(line.contains("database"))    }    /// RULE: You › Bin is `cinemas.bin`, and Put back is `cinemas.restore {id}`; nothing here erases.    @MainActor    func testTheBinAsksTheCore() async throws {        let core = ScriptedCore([            CottonMethod.cinemasBin: .ok(#"{"title":"Bin","items":[{"item":{"table":"film","id":"f1","title":"Night Ferry","kind":"film"},"line":"Moved to the Bin today"}],"empty":null}"#),            CottonMethod.cinemasRestore: .ok(#"{"id":"f1","said":"Back in Cinemas"}"#),        ])        let source = CinemasCoreSource(core: core)        let binRead = await source.binned().answer        let bin = try XCTUnwrap(binRead)        XCTAssertEqual(bin.items.first?.line, "Moved to the Bin today")        let said = await source.restore(try XCTUnwrap(bin.items.first?.item)).answer        XCTAssertEqual(said, "Back in Cinemas")        let calls = await core.calls        XCTAssertFalse(calls.contains { $0.method == "cinemas.erase" })    }    /// RULE (HIDE FROM SCREEN core 4): inside Hidden, its Bin row opens `cinemas.bin {hidden: true}`; Restore and Delete    /// forever are the acts the core names, asked for one title with its id added (Delete forever keeps `hidden: true`).    @MainActor    func testTheHiddenBinAsksTheCoreAsNamed() async throws {        let place = try JSONDecoder().decode(CinemasHiddenPlace.self, from: Data(#"{"title":"Hidden","locked":false,"rows":[{"id":"bin","title":"Bin","count":2,"hidden":true,"act":{"method":"cinemas.bin","request":{"hidden":true}}}]}"#.utf8))        XCTAssertEqual(place.rows.first?.act?.method, CottonMethod.cinemasBin)        XCTAssertEqual(place.rows.first?.count, 2)        XCTAssertTrue(place.rows.first?.items.isEmpty == true)        let core = ScriptedCore([            CottonMethod.cinemasBin: .ok(#"{"title":"Bin","hidden":true,"count":1,"items":[{"item":{"table":"film","id":"f1","title":"Quiet Signal","kind":"film"},"line":"Moved to the Bin today"}],"empty":null,"restore":{"label":"Restore","method":"cinemas.restore","args":{}},"erase":{"label":"Delete forever","method":"cinemas.erase","args":{"hidden":true}}}"#),            CottonMethod.cinemasRestore: .ok(#"{"id":"f1","said":"Back in Cinemas"}"#),            "cinemas.erase": .ok(#"{"erased":1}"#),        ])        let source = CinemasCoreSource(core: core)        let read = await source.binned(hidden: true).answer        let bin = try XCTUnwrap(read)        XCTAssertEqual(bin.erase?.label, "Delete forever")        let restore = try XCTUnwrap(bin.restore)        let said = await source.named(restore, id: "f1").answer        XCTAssertEqual(said, "Back in Cinemas")        let erase = try XCTUnwrap(bin.erase)        _ = await source.named(erase, id: "f1")        let calls = await core.calls        XCTAssertTrue(calls.contains { $0.method == CottonMethod.cinemasBin && $0.requestJSON.contains(#""hidden":true"#) })        XCTAssertTrue(calls.contains { $0.method == CottonMethod.cinemasRestore && $0.requestJSON.contains(#""id":"f1""#) })        let erased = try XCTUnwrap(calls.first { $0.method == "cinemas.erase" })        XCTAssertTrue(erased.requestJSON.contains(#""hidden":true"#) && erased.requestJSON.contains(#""id":"f1""#))    }    /// RULE: Search draws the core's top line and its people and channels (frame 6).    @MainActor    func testSearchReadsTheTopLineAndPeople() async throws {        let json = #"{"items":[{"table":"film","id":"f1","title":"Night Ferry","kind":"film"}],"groups":[],"top_line":"Film · 2019 · 1h 12m left","people":[{"name":"Mara Quill","kind":"person","ids":["f1"],"line":"1 title"}]}"#        let found = try JSONDecoder().decode(CinemasFound.self, from: Data(json.utf8))        XCTAssertEqual(found.topLine, "Film · 2019 · 1h 12m left")        XCTAssertEqual(found.people.first?.name, "Mara Quill")        let older = try JSONDecoder().decode(CinemasFound.self, from: Data(#"{"items":[],"groups":[]}"#.utf8))        XCTAssertNil(older.topLine)        XCTAssertTrue(older.people.isEmpty)    }    /// RULE: his real library (PUNCH, 27 Nov): an episode draws the core's `label` ("2. Reeds"); a name in Telugu or    /// Hindi keeps its marks (no tight lines); a dotted file name can break at its dots.    @MainActor    func testARealLibrarysNames() throws {        let json = #"{"table":"film_episode","id":"e2","title":"Reeds","kind":"episode","number":2,"episode_title":"Reeds","label":"2. Reeds"}"#        let episode = try JSONDecoder().decode(CinemasSeason.Episode.self, from: Data(json.utf8))        XCTAssertEqual(episode.label, "2. Reeds")        XCTAssertTrue(CinemasDrawn.tall("వెన్నెల దారి"))        XCTAssertTrue(CinemasDrawn.tall("चाँदनी की सड़क"))        XCTAssertFalse(CinemasDrawn.tall("Night Ferry — 2019"))        XCTAssertEqual(CinemasDrawn.breakable("a.b_c"), "a.\u{200B}b_\u{200B}c")    }    /// RULE: You is drawn from `cinemas.you`; a switch sends its act as the core wrote it (frame 12).    @MainActor    func testYouReadsTheCoreAndTurnsItsSwitches() async throws {        let core = ScriptedCore([            CottonMethod.cinemasYou: .ok(#"{"sections":[{"id":"watching","title":"Watching","rows":[{"id":"autoplay_next","label":"Play the next episode by itself","switch":true,"act":{"method":"cinemas.setting","request":{"key":"autoplay_next","value":false}}},{"id":"tv","label":"The TV","value":null,"act":{"open":"tv"}}]}]}"#),            CottonMethod.cinemasSetting: .ok(#"{"sections":[]}"#),        ])        let source = CinemasCoreSource(core: core)        let youRead = await source.you(free: 1_000).answer        let you = try XCTUnwrap(youRead)        let row = try XCTUnwrap(you.sections.first?.rows.first)        XCTAssertEqual(row.switch, true)        XCTAssertEqual(you.sections.first?.rows.last?.act?.open, "tv")        _ = await source.youAct(try XCTUnwrap(row.act?.method), row.act?.request)        let calls = await core.calls        let asked = try JSONDecoder().decode([String: JSONValue].self, from: Data(try XCTUnwrap(calls.first { $0.method == CottonMethod.cinemasSetting }).requestJSON.utf8))        XCTAssertEqual(asked["key"], .string("autoplay_next"))        XCTAssertEqual(asked["value"], .bool(false))        let read = try JSONDecoder().decode([String: JSONValue].self, from: Data(try XCTUnwrap(calls.first { $0.method == CottonMethod.cinemasYou }).requestJSON.utf8))        XCTAssertEqual(read["free_bytes"], .number(1_000))    }    /// RULE: a row's chip asks the core again with its filter, and the count and chips are the core's (frame 2).    @MainActor    func testARowsChipAsksTheCore() async throws {        let core = ScriptedCore([CottonMethod.cinemasRow: .ok(#"{"id":"films","title":"Films","count":12,"chips":[{"id":"all","label":"All","on":false},{"id":"az","label":"A–Z","on":true}],"filter":"az","items":[],"next":"60"}"#)])        let source = CinemasCoreSource(core: core)        let pageRead = await source.row("films", after: nil, filter: "az").answer        let page = try XCTUnwrap(pageRead)        XCTAssertEqual(page.count, 12)        XCTAssertEqual(page.chips?.first { $0.on }?.id, "az")        XCTAssertEqual(page.next, "60")        let calls = await core.calls        let asked = try JSONDecoder().decode([String: JSONValue].self, from: Data(try XCTUnwrap(calls.first).requestJSON.utf8))        XCTAssertEqual(asked["filter"], .string("az"))    }    /// RULE: "It is an episode" asks the core to move the film into its series (`cinemas.toEpisode`), naming an existing    /// series by id or a new one by name, with its season and episode (PUNCH Both 9).    @MainActor    func testItIsAnEpisodeAsksTheCore() async throws {        let core = ScriptedCore([CottonMethod.cinemasToEpisode: .ok(#"{"table":"film_episode","id":"e9","series":"s1","season":"se2"}"#)])        let source = CinemasCoreSource(core: core)        let item = CinemasItem(table: "film", id: "f1", title: "The Wardens", kind: .film)        _ = await source.toEpisode(item, series: "s1", newSeries: nil, season: 2, episode: 5)        _ = await source.toEpisode(item, series: nil, newSeries: "Lowmarsh", season: 1, episode: 1)        let calls = await core.calls        XCTAssertEqual(calls.count, 2)        let first = try JSONDecoder().decode([String: JSONValue].self, from: Data(calls[0].requestJSON.utf8))        XCTAssertEqual(first["series"], .string("s1"))        XCTAssertEqual(first["season"], .number(2))        XCTAssertEqual(first["episode"], .number(5))        let second = try JSONDecoder().decode([String: JSONValue].self, from: Data(calls[1].requestJSON.utf8))        XCTAssertEqual(second["series"], .object(["new": .string("Lowmarsh")]))    }    /// RULE: A row opened follows `next` past its first page, and a title met twice is drawn once (PUNCH Both 12).    @MainActor    func testARowOpenedFollowsNext() async throws {        let core = ScriptedCore([            CottonMethod.cinemasRow: .ok(#"{"title":"Films","items":[{"table":"film","id":"f1","title":"Night Ferry","kind":"film"}],"next":"f1"}"#),        ])        let pages = CinemasRowPages(id: "films")        await pages.first(CinemasCoreSource(core: core))        XCTAssertEqual(pages.next, "f1")        await pages.more(CinemasCoreSource(core: core))        XCTAssertEqual(pages.items.count, 1, "the same title on the next page is drawn once")        XCTAssertNil(pages.next, "a page that names itself as next ends the asking")        let calls = await core.calls        let second = try XCTUnwrap(calls.last { $0.method == CottonMethod.cinemasRow })        let asked = try JSONDecoder().decode([String: JSONValue].self, from: Data(second.requestJSON.utf8))        XCTAssertEqual(asked["after"], .string("f1"))    }    /// RULE: A title wears the core's drawn picture (`art {a, b, shape}`), says where he is in it (`watched_line`), and    /// an episode says its state in the core's words (`state_line`); nothing of these is worked out on the phone.    func testArtWatchedLineAndStateLineAreTheCores() throws {        let title = try JSONDecoder().decode(CinemasTitle.self, from: Data(#"""        {"item":{"table":"film","id":"f1","title":"Night Ferry","kind":"film","art":{"a":"#14302e","b":"#d99a4e","shape":"kite"}},         "facts":[],"play":{"label":"Resume 28:00","from_start":"Play from the start"},"tv":"Play on TV","acts":[],"groups":[],         "watched_line":"28 min watched · 1h 53m left"}        """#.utf8))        XCTAssertEqual(title.item.art, CinemasArt(a: "#14302e", b: "#d99a4e", shape: "kite"))        XCTAssertEqual(title.watchedLine, "28 min watched · 1h 53m left")        let season = try JSONDecoder().decode(CinemasSeason.self, from: Data(#"""        {"season":{"id":"se1","number":1,"title":null},         "episodes":[{"table":"film_episode","id":"e1","title":"The Reed Cutter","kind":"episode","number":1,"state_line":"23 min left"}]}        """#.utf8))        XCTAssertEqual(season.episodes.first?.stateLine, "23 min left")        XCTAssertEqual(CinemasArt.standIn("f1"), CinemasArt.standIn("f1"), "a title with no art from the core still draws the same every time")    }    /// RULE: The streaming screens are Cinemas' own (the Cinemas app and Cinemas Dev, owner 26 Nov 2026); no other app    /// takes them.    func testTheStreamingRootIsCinemasOnly() {        // The test host is Cotton itself, not Cinemas.        XCTAssertFalse(CinemasRoot.applies)    }    #if COTTON_DEV    /// RULE: Home's rows come in the contract's order, an empty automatic row is left out, and his groups follow in his    /// order, an empty one kept (it carries "Add films").    func testTheInventedHomeKeepsTheContractsOrder() async throws {        let invented = CinemasInvented(empty: false)        let homeRead = await invented.home().answer        let home = try XCTUnwrap(homeRead)        let automatic = ["carry_on", "recent", "films", "series", "videos", "on_phone", "getting_ready", "from_friends"]        let ids = home.rows.map(\.id)        let shown = ids.filter { automatic.contains($0) }        XCTAssertEqual(shown, automatic.filter { shown.contains($0) }, "the automatic rows keep the contract's order")        XCTAssertEqual(Array(ids.drop { automatic.contains($0) }), ["group:g-sundays", "group:g-kids", "group:g-again"])        XCTAssertFalse(home.rows.contains { $0.items.isEmpty && $0.group == nil }, "an empty automatic row is left out")        XCTAssertEqual(home.featured?.item.id, "f-ferry", "the featured title is the one he watched last")        XCTAssertTrue(home.rows.first { $0.id == "carry_on" }?.items.allSatisfy { $0.progress != nil } ?? false)    }    /// RULE: A title added to a group stands first in its row; moving a group moves its row on Home.    func testAGroupTakesATitleAndMoves() async throws {        let invented = CinemasInvented(empty: false)        let kite = CinemasItem(table: "film", id: "f-kite", title: "Kite Season", kind: .film)        _ = await invented.group("g-again", item: kite, in: true)        let rowRead = await invented.row("group:g-again", after: nil).answer        let row = try XCTUnwrap(rowRead)        XCTAssertEqual(row.items.first?.id, "f-kite")        _ = await invented.moveGroup("g-again", earlier: true)        let homeRead = await invented.home().answer        let home = try XCTUnwrap(homeRead)        XCTAssertEqual(home.rows.compactMap(\.group), ["g-sundays", "g-again", "g-kids"])    }    /// RULE: A title in any hidden category is nowhere outside Hidden — not Featured, a row, another category's row    /// (one hidden and one open: hidden), Search, a title page, the picker or a count — and a hidden category's name is    /// nowhere either. Inside Hidden they all answer; Stop hiding brings them back everywhere.    func testAHiddenCategoryLeavesEveryAnswer() async throws {        let invented = CinemasInvented(empty: false)        let children = ["f-kite", "f-paper", "f-moonbus", "f-lantern"]        _ = await invented.hide("g-kids", hidden: true)        let homeRead = await invented.home().answer        let home = try XCTUnwrap(homeRead)        XCTAssertFalse(home.rows.contains { $0.group == "g-kids" }, "the hidden category's row is gone")        let shown = Set(home.rows.flatMap(\.items).map(\.id) + [home.featured?.item.id].compactMap { $0 })        XCTAssertTrue(shown.isDisjoint(with: children), "no hidden title on Home: \(shown.intersection(children))")        let read3 = await invented.row("group:g-sundays", after: nil).answer        let sundays = try XCTUnwrap(read3)        XCTAssertFalse(sundays.items.contains { $0.id == "f-lantern" }, "in one hidden and one open category: hidden")        let read4 = await invented.search("kite").answer?.items.isEmpty ?? false        XCTAssertTrue(read4)        let read5 = await invented.search("children").answer?.groups.isEmpty ?? false        XCTAssertTrue(read5, "a hidden name is not found outside")        let read6 = await invented.title(table: "film", id: "f-kite").answer        XCTAssertNil(read6, "a hidden title's page is not there outside")        let read7 = await invented.groups().answer        let open = try XCTUnwrap(read7)        XCTAssertFalse(open.groups.contains { $0.id == "g-kids" })        XCTAssertEqual(open.groups.first { $0.id == "g-sundays" }?.count, 4, "an open count leaves the hidden title out")        let kite = CinemasItem(table: "film", id: "f-kite", title: "Kite Season", kind: .film)        let ferry = CinemasItem(table: "film", id: "f-ferry", title: "Night Ferry", kind: .film)        let read8 = await invented.groups(holding: ferry, hidden: false).answer?.groups.contains { $0.id == "g-kids" } ?? true        XCTAssertFalse(read8)        // Inside Hidden.        let read9 = await invented.hiddenPlace().answer        let locked = try XCTUnwrap(read9)        XCTAssertTrue(locked.locked)        XCTAssertTrue(locked.rows.isEmpty, "locked, no rows")        let shut = await invented.search("kite", hidden: true).answer        XCTAssertNil(shut, "hidden: true without the unlock is refused")        _ = await invented.unlock(noLock: false)        let read10 = await invented.hiddenPlace().answer        let place = try XCTUnwrap(read10)        XCTAssertEqual(place.rows.compactMap(\.group), ["g-kids"])        let read11 = await invented.search("kite", hidden: true).answer?.items.map(\.id)        XCTAssertEqual(read11, ["f-kite"])        let read12 = await invented.title(table: "film", id: "f-kite", hidden: true).answer        XCTAssertNotNil(read12)        let read13 = await invented.groups(holding: kite, hidden: true).answer        let inside = try XCTUnwrap(read13)        XCTAssertEqual(inside.groups.first { $0.id == "g-kids" }?.hidden, true)        // Stop hiding.        _ = await invented.hide("g-kids", hidden: false)        let read14 = await invented.home().answer        let back = try XCTUnwrap(read14)        XCTAssertTrue(back.rows.contains { $0.group == "g-kids" })        let read15 = await invented.search("kite").answer?.items.map(\.id)        XCTAssertEqual(read15, ["f-kite"])        let read16 = await invented.row("group:g-sundays", after: nil).answer        XCTAssertTrue(try XCTUnwrap(read16).items.contains { $0.id == "f-lantern" })    }    /// RULE: An empty library answers the empty words and no rows.    func testTheInventedEmptyLibrary() async throws {        let homeRead = await CinemasInvented(empty: true).home().answer        let home = try XCTUnwrap(homeRead)        XCTAssertTrue(home.rows.isEmpty)        XCTAssertNotNil(home.empty)    }    #endif    /// A category hidden while its film floats in picture-in-picture: the veil turns on and the window closes; a film    /// already discreet, or shown again, never closes a window.    func testHidingAFloatingFilmClosesItsWindow() {        XCTAssertTrue(FilmPlayback.turned(veiled: false, floating: true, discreet: true) == (true, true))        XCTAssertTrue(FilmPlayback.turned(veiled: false, floating: false, discreet: true) == (true, false))        XCTAssertTrue(FilmPlayback.turned(veiled: true, floating: true, discreet: true) == (true, false))        XCTAssertTrue(FilmPlayback.turned(veiled: true, floating: true, discreet: false) == (false, false))    }    /// A hidden title playing (HIDE FROM SCREEN 3): now-playing says only "Cinemas", with no poster, Hidden open or shut.    func testNowPlayingNeverNamesAHiddenTitle() {        let poster = Data([1, 2, 3])        let shut = FilmPlayback.nowPlaying(hidden: true, open: false, title: "Quiet Signal", artwork: poster, veil: "Cinemas")        XCTAssertEqual(shut.title, "Cinemas")        XCTAssertNil(shut.artwork)        let open = FilmPlayback.nowPlaying(hidden: true, open: true, title: "Quiet Signal", artwork: poster, veil: "Cinemas")        XCTAssertEqual(open.title, "Cinemas")        XCTAssertNil(open.artwork)        let plain = FilmPlayback.nowPlaying(hidden: false, open: false, title: "Quiet Signal", artwork: poster, veil: "Cinemas")        XCTAssertEqual(plain.title, "Quiet Signal")    }}#endif