Cotton code
188 lines · 12.1 KB · SwiftRaw
import CottonKitimport Foundationimport XCTest@testable import CottonUI#if os(iOS)import UIKit@MainActorfinal class InkStoryTests: XCTestCase {    // RULE: the home's title shows whole at any size: words wrap, and a word wider than the line (a title in a    // script written without spaces) breaks between whole letters, never inside one, and loses none.    func testATitleWithNoSpacesBreaksBetweenLettersAndShowsWhole() {        let face = UIFont.monospacedSystemFont(ofSize: 40, weight: .regular)        let mark = UIFont.monospacedSystemFont(ofSize: 20, weight: .regular)        let title = "రాత్రిబస్సుస్టాప్దగ్గరఎవరూలేరు"        let lines = InkTitle.wrap(title, face: face, mark: mark, width: 160)        XCTAssertGreaterThan(lines.count, 1)        XCTAssertEqual(lines.joined(), title)        let latin = InkTitle.wrap("The Night Bus", face: face, mark: mark, width: 160)        XCTAssertEqual(latin.joined(separator: " "), "The Night Bus")    }    // RULE (launch-ios walk, 22 Nov 2026): at a large text size a title is drawn smaller until its longest word fits    // the line ("Monsoon" broke into "Monso / on"), down to the least scale; only a word wider still breaks.    func testATitleShrinksSoItsLongestWordFits() {        XCTAssertEqual(InkTitle.fitted(70, longest: 200, width: 240), 70, "a word that fits keeps the size")        let fitted = InkTitle.fitted(70, longest: 294, width: 240)        XCTAssertLessThan(fitted, 70)        XCTAssertLessThanOrEqual(294 * fitted / 70, 240, "the longest word now fits")        XCTAssertEqual(InkTitle.fitted(70, longest: 2000, width: 240), 70 * InkTitle.leastScale, "never below the least scale")        XCTAssertEqual(InkTitle.fitted(70, longest: 294, width: 0), 70, "unmeasured, unchanged")    }    // RULE: a picture moves earlier or later among its own by naming the one it goes after (`start` for the first    // place); the first has no earlier, the last no later.    func testAPictureMovesByTheOneItGoesAfter() {        let ids = ["a", "b", "c"]        XCTAssertEqual(InkPictureWords.after(moving: 1, by: -1, in: ids), "start")        XCTAssertEqual(InkPictureWords.after(moving: 2, by: -1, in: ids), "a")        XCTAssertEqual(InkPictureWords.after(moving: 0, by: 1, in: ids), "b")        XCTAssertNil(InkPictureWords.after(moving: 0, by: -1, in: ids))        XCTAssertNil(InkPictureWords.after(moving: 2, by: 1, in: ids))    }    // RULE: each picture says where it stands; the first of a person or a place also says it is their face, a    // day's first does not.    func testTheFirstPictureSaysItIsTheFace() {        let face = InkPictureWords.label(at: 0, of: 3, name: "Anu", day: false)        XCTAssertTrue(face.contains("Anu"))        XCTAssertTrue(face.contains(InkWords.line("ink.picture_label", ["n": "1", "of": "3"])))        XCTAssertEqual(InkPictureWords.label(at: 0, of: 3, name: "Anu", day: true), InkWords.line("ink.picture_label", ["n": "1", "of": "3"]))        XCTAssertEqual(InkPictureWords.label(at: 1, of: 3, name: "Anu", day: false), InkWords.line("ink.picture_label", ["n": "2", "of": "3"]))    }    // RULE: counted words take one, other, and the zero form where the set has one ("Has not spoken yet").    func testCountedWordsTakeTheirForms() {        XCTAssertEqual(InkWords.counted("character.speaks", 0), InkWords.line("character.speaks.zero"))        XCTAssertEqual(InkWords.counted("character.speaks", 1), InkWords.line("character.speaks.one"))        XCTAssertEqual(InkWords.counted("ink.changed_since", 3, ["draft": "Second draft"]),                       InkWords.line("ink.changed_since.other", ["n": "3", "draft": "Second draft"]))        XCTAssertEqual(InkWords.counted("length.scenes", 0), InkWords.line("length.scenes.other", ["n": "0"]))    }    // RULE: a character's page reads the core's answer whole: their lines in each scene, their story days, and    // their pictures, the face first and day pictures by day.    func testAPersonDecodesTheirScenesDaysAndPictures() throws {        let json = """        {"id":"c1","name":"Anu","initial":"A","picture":"photo:x","lines":3,"about":null,"scenes":2,"scene_ids":["s1","s2"],         "lines_in":{"s1":"2 lines","s2":"1 line"},"days":[{"day":2,"label":"Day 2"}],         "pictures":[{"id":"p1","picture":"photo:x","caption":null,"day":null,"character":"c1"},                     {"id":"p2","picture":"photo:y","caption":null,"day":2,"character":"c1"}]}        """        let person = try JSONDecoder().decode(StoryPerson.self, from: Data(json.utf8))        XCTAssertEqual(person.linesIn?["s1"], "2 lines")        XCTAssertEqual(person.days?.first?.label, "Day 2")        XCTAssertEqual(person.pictures?.filter { $0.day == nil }.map(\.id), ["p1"])        XCTAssertEqual(person.pictures?.filter { $0.day == 2 }.map(\.id), ["p2"])    }    // RULE: what changed since a draft decodes scene by scene; the working copy counts scenes added, taken out    // and changed (a moved scene alone is not a change in it).    func testChangesSinceADraftCountScenes() throws {        let json = """        {"scenes":[{"scene":"s1","number_then":1,"number_now":2,"change":"moved","lines":{"added":0,"removed":0,"changed":0}},                   {"scene":"s2","number_then":null,"number_now":1,"change":"added","heading_now":"EXT. DEPOT - NIGHT","lines":{"added":3,"removed":0,"changed":0}},                   {"scene":"s3","number_then":2,"number_now":null,"change":"removed","heading_then":"INT. BUS - DAY","lines":{"added":0,"removed":2,"changed":0}}],         "since":{"scenes_added":1,"scenes_removed":1,"scenes_changed":0,"scenes_moved":1,"lines_added":3,"lines_removed":2,"lines_changed":0},         "draft":{"id":"d1","name":"Second draft"}}        """        let changes = try JSONDecoder().decode(StoryChanges.self, from: Data(json.utf8))        XCTAssertEqual(changes.since.scenes, 2)        XCTAssertEqual(changes.scenes.map(\.change), ["moved", "added", "removed"])        XCTAssertEqual(changes.scenes[2].headingThen, "INT. BUS - DAY")        XCTAssertEqual(InkDraftsScreen.since(changes.since, draft: "Second draft"),                       InkWords.line("ink.changed_since.other", ["n": "2", "draft": "Second draft"]))    }    // RULE: Read's foot says the page in view of all of them and about how long the film runs (a page a minute).    func testReadsFootSaysThePageAndTheMinutes() {        let words = InkReadFoot.words(page: 3, of: 18)        XCTAssertTrue(words.hasPrefix(InkWords.line("ink.page_of", ["n": "3", "of": "18"])))        XCTAssertTrue(words.hasSuffix(InkWords.line("length.minutes.other", ["n": "18"])))    }    // RULE: Bring in a script offers Fountain, Final Draft, PDF and plain text.    func testBringInOffersEveryScriptFile() {        let types = StoryScriptTypes.all        XCTAssertTrue(types.contains(.pdf))        XCTAssertTrue(types.contains(.plainText))        XCTAssertTrue(types.contains { $0.preferredFilenameExtension == "fdx" })        XCTAssertTrue(types.contains { $0.preferredFilenameExtension == "fountain" })        XCTAssertEqual(StoryFountainOpen.extensions.sorted(), ["fdx", "fountain", "pdf", "txt"])    }    // RULE: no Story screen changes the case of what a person wrote or the core said.    func testNoStoryScreenChangesTheCaseOfWords() throws {        let files = try SourceSweep.swiftSources().filter { $0.name.hasPrefix("CottonUI/Story/") && !$0.name.hasSuffix("InkListen.swift") }        XCTAssertFalse(files.isEmpty)        for file in files {            let hits = try SourceSweep.matches(#"\.uppercased\(\)|\.textCase\(\.uppercase\)"#, in: SourceSweep.withoutComments(file.text))            XCTAssertTrue(hits.isEmpty, "\(file.name) changes the case of words: \(hits)")        }    }    // RULE: a scene dragged past half of a neighbour takes its place; the others part by its height; the drop    // is the new order (NOTE2 2).    func testADraggedSceneLandsPastHalfOfItsNeighbour() {        let heights: [CGFloat] = [60, 80, 60, 60]        XCTAssertEqual(InkReorder.target(from: 0, offset: 30, heights: heights), 0)        XCTAssertEqual(InkReorder.target(from: 0, offset: 41, heights: heights), 1)        XCTAssertEqual(InkReorder.target(from: 0, offset: 200, heights: heights), 3)        XCTAssertEqual(InkReorder.target(from: 3, offset: -95, heights: heights), 2)        XCTAssertEqual(InkReorder.target(from: 3, offset: -130, heights: heights), 1)        XCTAssertEqual(InkReorder.target(from: 3, offset: -999, heights: heights), 0)        XCTAssertEqual(InkReorder.moved(["a", "b", "c", "d"], from: 0, to: 2), ["b", "c", "a", "d"])        XCTAssertEqual(InkReorder.moved(["a", "b", "c", "d"], from: 3, to: 1), ["a", "d", "b", "c"])        XCTAssertEqual(InkReorder.parting(1, from: 0, to: 2, lift: 60), -60)        XCTAssertEqual(InkReorder.parting(3, from: 0, to: 2, lift: 60), 0)        XCTAssertEqual(InkReorder.parting(1, from: 3, to: 1, lift: 60), 60)    }    // RULE: while scripts are still coming the list says so; the chooser holds characters and the bar's switches    // are Action and Note (NOTE2 1, 5).    func testArrivingAndTheSwitchesDecode() throws {        let list = try JSONDecoder().decode(StoryListAnswer.self, from: Data(#"{"stories":[],"empty":"x","arriving":true,"arriving_line":"Loading your data…"}"#.utf8))        XCTAssertEqual(list.arriving, true)        XCTAssertEqual(list.arrivingLine, "Loading your data…")        let pick = try JSONDecoder().decode(StorySceneAnswer.Pick.self, from: Data("""        {"next":{"kind":"action"},"label":"Next line","new":{"label":"New character…","hint":"Their name"},         "sections":[{"key":"characters","rows":[{"kind":"character","character":"c1","name":"Anu","suggested":true}]}],         "switches":[{"kind":"action","name":"Action","suggested":true},{"kind":"note","name":"Note","suggested":false}]}        """.utf8))        XCTAssertEqual(pick.switches?.map(\.choice), [.action, .note])        XCTAssertEqual(pick.suggestedSpeaker, .character("c1"))    }    // RULE: Settings shows your number from your own person's phones, a list or lines of text, as Android does.    func testYourNumberIsYourPersonsFirstPhone() {        XCTAssertEqual(InkYou.number(.array([.string(" "), .string("+91 98450 00000")])), "+91 98450 00000")        XCTAssertEqual(InkYou.number(.string("\n+44 7700 900000\n+1 555")), "+44 7700 900000")        XCTAssertNil(InkYou.number(nil))        XCTAssertNil(InkYou.number(.array([])))    }    // RULE: the speaker chooser keeps the core's order (in this scene first, then by lines spoken), finds by any    // part of a name ignoring case and accents, and offers its find field only past eight characters (owner, 20 Nov).    func testTheSpeakerChooserFindsInTheCoresOrderAmongSixty() throws {        let names = (0..<60).map { $0 == 7 ? "RENÉE \($0)" : "PERSON \($0)" }        let rows = names.enumerated().map { at, name in            #"{"kind":"character","character":"c\#(at)","name":"\#(name)","suggested":\#(at == 0)}"#        }        let pick = try JSONDecoder().decode(StorySceneAnswer.Pick.self, from: Data("""        {"next":{"kind":"character","character":"c0"},"label":"Next line","new":{"label":"New character…","hint":"Their name"},         "sections":[{"key":"characters","rows":[\(rows.joined(separator: ","))]}],         "switches":[{"kind":"action","name":"Action","suggested":false},{"kind":"note","name":"Note","suggested":false}]}        """.utf8))        let people = InkSpeakerSheet.people(pick, changing: false)        XCTAssertEqual(people.count, 60)        XCTAssertEqual(people.map(\.name), names, "the phone never sorts the core's order")        XCTAssertGreaterThan(people.count, InkSpeakerSheet.findAbove)        XCTAssertEqual(InkSpeakerSheet.found(people, "renee").map(\.name), ["RENÉE 7"])        XCTAssertEqual(InkSpeakerSheet.found(people, "son 5").map(\.name), ["PERSON 5", "PERSON 50", "PERSON 51", "PERSON 52", "PERSON 53",                                                                          "PERSON 54", "PERSON 55", "PERSON 56", "PERSON 57", "PERSON 58", "PERSON 59"])        XCTAssertEqual(InkSpeakerSheet.found(people, "  ").count, 60)        XCTAssertTrue(InkSpeakerSheet.found(people, "nobody").isEmpty)    }}#endif