Cotton code
225 lines · 13.8 KB · SwiftRaw
import CottonKitimport CottonMailboximport CottonValuesimport XCTest@testable import CottonUI#if canImport(ReadiumShared)@preconcurrency import ReadiumSharedimport ReadiumStreamerimport ReadiumNavigator#endif/// The book reader: the core's answers it reads (`ReaderAnswer`) and the/// reports it makes (`ReaderReport`), what the phone keeps (`BookHere`), how a/// card and an act open it — and, on the phone, the two fixture books opened/// through Readium. Where it opens, when a place is written and the first/// open's Reading are the core's (`phone::reader`'s tests).final class BookReaderTests: XCTestCase {    private let epubPlace = #"{"href":"OEBPS/8878401390937179042_1952-h-0.htm.xhtml","type":"application/xhtml+xml","locations":{"progression":0.25,"position":3,"totalProgression":0.1234}}"#    // MARK: The core's answer    /// What `shell.reader` answers for a fresh EPUB (the shape `phone::reader` writes; synthetic).    static let opened = #"""    {"book":"b1","title":"The Lantern Orchard","file":"w/books/c.epub","format":"epub",     "at":{"locator":"{\"href\":\"c1.xhtml\"}","chapter":"One","progress":3,"page_label":"3"},     "progress_words":"3%",     "settings":{"face":"sepia","worn":"night","knobs":{"size":1.2,"line_height":null,"margins":1.5,"typeface":"serif",                 "layout":"scroll","follow":true,"weight":"regular","justify":false,"publisher_styles":false,"pdf_fit":"page"}},     "fan":{"hand":{"cards":[{"id":"face-paper","label":"Paper"},{"id":"face-sepia","label":"Sepia"},{"id":"face-night","label":"Night"},                             {"id":"knob-size","label":"Type size","words":"120%",                              "choices":{"cards":[{"id":"choice-0","label":"85%","value":0.85},{"id":"choice-1","label":"100%","value":1.0},{"id":"choice-2","label":"120%","value":1.2}],"raised":"choice-2"}},                             {"id":"knob-follow","label":"Follow the phone's light and dark","words":"On",                              "choices":{"cards":[{"id":"choice-0","label":"On","value":true},{"id":"choice-1","label":"Off","value":false}],"raised":"choice-0"}}],"raised":"face-sepia"},            "faces":{"cards":[{"id":"face-paper","label":"Paper"},{"id":"face-sepia","label":"Sepia"},{"id":"face-night","label":"Night"}],"raised":"face-sepia"},            "selection":{"cards":[{"id":"pencil-red","label":"Red","red":false},{"id":"pencil-yellow","label":"Yellow","red":false},{"id":"pencil-teal","label":"Teal","red":false},{"id":"note","label":"Note","red":false}],"raised":"pencil-yellow"},            "highlight":{"cards":[{"id":"pencil-red","label":"Red","red":false},{"id":"pencil-yellow","label":"Yellow","red":false},{"id":"pencil-teal","label":"Teal","red":false},{"id":"note","label":"Note","red":false},{"id":"remove","label":"Remove","red":true}]},            "note_hint":"Why you marked it"},     "highlights":[{"id":"h1","at":"{\"href\":\"c1.xhtml\"}","chapter":"One","words":"An invented line.","pencil":"teal","note":null}],     "refusals":{"locked":"Locked.","unopened":"Not opened."},     "start_on_open":true}    """#    /// RULE: The reader reads the core's open book whole: where it opens and the bar's words, the face chosen and worn, every knob, the fan's tiers and the highlights, as `shell.reader` writes them.    func testTheReaderReadsTheCoresOpenBook() throws {        let answer = try JSONDecoder().decode(ReaderAnswer.self, from: Data(Self.opened.utf8))        XCTAssertNil(answer.refusal)        XCTAssertEqual(answer.bookFormat, .epub)        XCTAssertEqual(answer.at, ReaderPlace(locator: #"{"href":"c1.xhtml"}"#, chapter: "One", progress: 3, pageLabel: "3"))        XCTAssertEqual(answer.progressWords, "3%")        let settings = try XCTUnwrap(answer.settings)        XCTAssertEqual(settings.face, .sepia)        XCTAssertEqual(settings.worn, .night, "the face worn is the core's")        XCTAssertEqual(settings.knobs.size, 1.2)        XCTAssertNil(settings.knobs.lineHeight)        XCTAssertEqual(settings.knobs.typeface, .serif)        XCTAssertTrue(settings.knobs.scroll)        XCTAssertTrue(settings.knobs.pdfWholePage)        XCTAssertFalse(settings.knobs.publisherStyles)        let fan = try XCTUnwrap(answer.fan)        XCTAssertEqual(fan.hand.cards[3].choices?.cards.last?.value, .number(1.2))        XCTAssertEqual(fan.hand.cards.last?.choices?.cards.first?.value, .bool(true))        XCTAssertEqual(answer.highlights, [BookHighlight(id: "h1", at: #"{"href":"c1.xhtml"}"#, pencil: .teal)])    }    /// RULE: A locked book is the core's refusal line and nothing more.    func testALockedBookIsItsRefusalLine() throws {        let answer = try JSONDecoder().decode(ReaderAnswer.self, from: Data(#"{"book":"b1","refusal":"This book is locked by its seller and cannot open here."}"#.utf8))        XCTAssertEqual(answer.refusal, "This book is locked by its seller and cannot open here.")        XCTAssertNil(answer.file)        XCTAssertNil(answer.settings)    }    /// RULE: A move reports the place as Readium wrote it, whether the app is active, and a PDF page's label (null when it has none); the core's answer says where the page stands and when to report again.    func testAMoveReportsWhatThePageSaysAndHearsWhenToAskAgain() throws {        var report = ReaderReport(book: "b1", at: #"{"href":"doc.pdf"}"#, active: true)        report.pageLabel = .some(nil)        report.contents = .init(toc: [.init(title: "Preface", href: "doc.pdf#page=1")], readingOrder: ["doc.pdf"])        let sent = try JSONSerialization.jsonObject(with: JSONEncoder().encode(report)) as? [String: Any]        XCTAssertEqual(sent?["book"] as? String, "b1")        XCTAssertEqual(sent?["active"] as? Bool, true)        XCTAssertTrue(sent?["page_label"] is NSNull, "a page with no label says so")        XCTAssertNotNil((sent?["contents"] as? [String: Any])?["reading_order"])        XCTAssertNil(sent?["closing"], "a field not said is left out")        let tick = try JSONSerialization.jsonObject(with: JSONEncoder().encode(ReaderReport(book: "b1", active: true))) as? [String: Any]        XCTAssertEqual(Set(tick?.keys.map { $0 } ?? []), ["book", "active"])        let heard = try JSONDecoder().decode(ReaderMovedAnswer.self, from: Data(            #"{"at":{"locator":"{}","chapter":"Preface","progress":4,"page_label":"iv"},"progress_words":"4%","wrote":false,"again_ms":11000}"#.utf8))        XCTAssertEqual(heard.at?.pageLabel, "iv")        XCTAssertEqual(heard.againMs, 11000)        XCTAssertFalse(heard.wrote)    }    // MARK: What the phone keeps    func testTheKeepersStates() {        XCTAssertEqual(BookHere.absent.after(.keep).state, .keeping)        XCTAssertTrue(BookHere.absent.after(.keep).fetch)        XCTAssertFalse(BookHere.keeping.after(.keep).fetch, "a book coming down is not fetched twice")        XCTAssertEqual(BookHere.kept.after(.keep).state, .kept)        XCTAssertFalse(BookHere.kept.after(.keep).fetch)        XCTAssertEqual(BookHere.keeping.after(.landed).state, .kept)        XCTAssertEqual(BookHere.keeping.after(.failed).state, .absent)        for state in [BookHere.absent, .keeping, .kept] {            XCTAssertEqual(state.after(.remove).state, .absent)            XCTAssertFalse(state.after(.remove).fetch)        }        XCTAssertEqual(BookHere.absent.after(.landed).state, .absent, "a fetch landing after Remove download keeps nothing")        XCTAssertEqual(BookHere.absent.after(.failed).state, .absent)    }    // MARK: How it opens    func testReaderOpenAnswersAPlatformAction() throws {        let at = #"{\"href\":\"x\",\"type\":\"application/pdf\"}"#        let answer = try JSONDecoder().decode(CommandOutcome.self, from: Data(            #"{"command":"read","kind":"method","answer":{"platform_action":"open_reader","table":"book","id":"b1","at":"\#(at)"}}"#.utf8))        let change = try answer.change(table: "book", record: "b1")        XCTAssertEqual(change.opened, .platform(.openReader(ReaderOpening(id: "b1", at: #"{"href":"x","type":"application/pdf"}"#))))        XCTAssertFalse(change.undoable, "opening a book changes nothing to undo")        let plain = try JSONDecoder().decode(CommandOutcome.self, from: Data(            #"{"command":"read","kind":"method","answer":{"platform_action":"open_reader","table":"book","id":"b1","at":null}}"#.utf8))        XCTAssertEqual(try plain.change(table: "book", record: "b1").opened, .platform(.openReader(ReaderOpening(id: "b1"))))    }    @MainActor    func testTheReaderOpensOnceAndJumpsWithinTheOpenBook() async {        let presenter = ReaderPresenter()        let opened = await RecordPlatformEffects.perform(.openReader(ReaderOpening(id: "b1")), reader: presenter)        XCTAssertTrue(opened)        XCTAssertEqual(presenter.current, ReaderOpening(id: "b1"))        presenter.open(ReaderOpening(id: "b1", at: epubPlace))        XCTAssertEqual(presenter.current, ReaderOpening(id: "b1"), "the book already open stays open")        XCTAssertEqual(presenter.jump?.at, epubPlace, "and goes to the place asked")        presenter.close()        XCTAssertNil(presenter.current)        XCTAssertNil(presenter.jump)        let nowhere = await RecordPlatformEffects.perform(.openReader(ReaderOpening(id: "b1")))        XCTAssertFalse(nowhere, "no reader, nothing opened")    }}#if canImport(ReadiumShared)/// The two fixture books through Readium itself: the Locator survives the/// round trip as text (what the core keeps in `book.position`), and a PDF's/// place names its page.@MainActorfinal class BookReadiumTests: XCTestCase {    func testAnEpubLocatorRoundTripsThroughThePositionColumn() async throws {        let publication = try await open("the-yellow-wallpaper", "epub", format: .epub)        let positions = try await publication.positions().get()        XCTAssertGreaterThan(positions.count, 10, "a position per 1,024 bytes of each chapter")        let third = positions[2]        XCTAssertEqual(try Locator(jsonString: try third.jsonString()), third, "what is stored opens at the same place")        XCTAssertNotNil(third.locations.totalProgression, "the core reads how far through from it")    }    func testAPdfsPlaceNamesItsPage() async throws {        let publication = try await open("the-yellow-wallpaper", "pdf", format: .pdf)        let positions = try await publication.positions().get()        XCTAssertEqual(positions.count, 14, "one position per page")        let page3 = positions[2]        XCTAssertEqual(page3.mediaType, .pdf)        XCTAssertEqual(page3.locations.position, 3)        XCTAssertEqual(try Locator(jsonString: try page3.jsonString()).locations.position, 3)    }    /// RULE: a book whose container names its text encrypted under a scheme nothing here decrypts is locked: it does not open, and says so, while the same book unlocked opens.    func testABookItsSellerLockedDoesNotOpen() async throws {        do {            _ = try await open("the-yellow-wallpaper-locked", "epub", format: .epub)            XCTFail("a locked book opens nothing")        } catch {            XCTAssertTrue(error is BookLocked, "locked, not corrupt: \(error)")        }        let plain = try await open("the-yellow-wallpaper", "epub", format: .epub)        XCTAssertFalse(BookLocked.holds(plain))    }    /// RULE: a highlight's Open in book opens the reader at its passage: the navigator made at a Locator's progression lands there once its page is laid out, not on the chapter's first pages, and stays.    func testTheReaderOpensAtTheLocatorItIsGiven() async throws {        let navigator = try await passageNavigator()        let delegate = BookNavigatorDelegate()        delegate.landing = BookNavigators.landsLate(try XCTUnwrap(navigator.currentLocation))        XCTAssertNotNil(delegate.landing, "a place half through a chapter is gone to again")        (navigator as? EPUBNavigatorViewController)?.delegate = delegate        let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.first as? UIWindowScene, "the test host's scene")        let window = UIWindow(windowScene: scene)        window.frame = CGRect(x: 0, y: 0, width: 393, height: 852)        window.rootViewController = navigator        window.makeKeyAndVisible()        defer { window.isHidden = true }        try await assertLandsOnThePassage(navigator)    }    private func passageNavigator() async throws -> VisualNavigator & UIViewController {        let publication = try await open("the-yellow-wallpaper", "epub", format: .epub)        let passage = try Locator(jsonString: #"{"href":"OEBPS/8878401390937179042_1952-h-0.htm.xhtml","type":"application/xhtml+xml","locations":{"progression":0.51}}"#)        let settings = ReaderSettings()        return try BookNavigators.navigator(for: publication, format: .epub, at: passage, settings: settings, face: settings.worn)    }    /// Where the page stands after ten seconds.    private func assertLandsOnThePassage(_ navigator: VisualNavigator & UIViewController,                                         file: StaticString = #filePath, line: UInt = #line) async throws {        var seen: [Double] = []        for _ in 0..<100 {            try await Task.sleep(for: .milliseconds(100))            if let progression = navigator.currentLocation?.locations.progression, seen.last != progression { seen.append(progression) }        }        let at = try XCTUnwrap(seen.last, file: file, line: line)        XCTAssertEqual(at, 0.51, accuracy: 0.08, "the page holding the passage; the places it stood: \(seen)", file: file, line: line)    }    private func open(_ name: String, _ ext: String, format: CottonMailbox.BookFormat) async throws -> Publication {        #if SWIFT_PACKAGE        let bundle = Bundle.module        #else        let bundle = Bundle(for: Self.self)        #endif        let url = try XCTUnwrap(bundle.url(forResource: name, withExtension: ext, subdirectory: "Fixtures/Books"))        return try await BookNavigators.publication(at: url, format: format)    }}#endif