Cotton code
113 lines · 5.8 KB · SwiftRaw
#if os(iOS)import CottonKitimport CottonValuesimport SwiftUIimport UIKitimport XCTest@testable import CottonUI@MainActorfinal class BackupScreenTests: XCTestCase {    func testFreshCopyGetsItsCalendarPassInsideThePreviousCopiesThrottle() async {        let core = ScriptedCore([CottonMethod.write: .ok("{}")])        let calendars = RecurrenceMaterializer(core: core)        await calendars.run()        await calendars.run()        let before = await core.methodsCalled()        XCTAssertEqual(before.filter { $0 == CottonMethod.write }.count, 1)        await calendars.copyReplaced()        let after = await core.methodsCalled()        XCTAssertEqual(after.filter { $0 == CottonMethod.write }.count, 2)    }    /// Long cards and their acts must be scrollable above the standing fan,    /// including at large text sizes. Folding the fan must not move the page.    func testActsScrollFullyAboveTheFan() async throws {        let cover = FanCover()        cover.scrollClearance = 220        var lastAct = CGRect.zero        let page = PaperScreen(clearsFan: true) {            Color.clear.frame(height: 1100)            TypedRow(label: ShellLines.line("board", "object.backup.stop"), chevron: false) {}            TypedRow(label: ShellLines.line("board", "object.backup.remove"), chevron: false, destructive: true) {}                .onGeometryChange(for: CGRect.self, of: { $0.frame(in: .global) }) { lastAct = $0 }        }.environment(\.fanCover, cover)        let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)        let window = UIWindow(windowScene: scene)        window.rootViewController = UIHostingController(rootView: page)        window.makeKeyAndVisible()        defer { window.isHidden = true; window.rootViewController = nil }        try await Task.sleep(for: .milliseconds(150))        func scroll(in view: UIView) -> UIScrollView? {            if let view = view as? UIScrollView { return view }            return view.subviews.lazy.compactMap { scroll(in: $0) }.first        }        let scroller = try XCTUnwrap(scroll(in: try XCTUnwrap(window.rootViewController?.view)))        XCTAssertTrue(scroller.clipsToBounds)        XCTAssertLessThanOrEqual(scroller.convert(scroller.bounds, to: window).maxY,                                 window.bounds.maxY - cover.scrollClearance,                                 "the initial viewport must stop above the fan, not draw through it")        scroller.setContentOffset(CGPoint(x: 0, y: max(0, scroller.contentSize.height - scroller.bounds.height + scroller.adjustedContentInset.bottom)), animated: false)        try await Task.sleep(for: .milliseconds(150))        XCTAssertGreaterThan(lastAct.height, 40)        XCTAssertLessThanOrEqual(lastAct.maxY, window.bounds.maxY - cover.scrollClearance)        let before = scroller.bounds.height        cover.edge = nil        try await Task.sleep(for: .milliseconds(50))        XCTAssertEqual(scroller.bounds.height, before, "a fold changes no scroll layout")    }    func testBackupActsBelongToThePageAndNeverTheSettingsRail() throws {        let code = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Join/BackupRoutes.swift", ownedBy: "Backup walk"))        for act in ["act", "stop", "remove"] {            XCTAssertTrue(code.contains("TypedRow("))            XCTAssertTrue(code.contains("object.backup.\(act)"))        }        XCTAssertTrue(code.contains("clearsFan: true"))        let raw = try SourceSweep.mustRead("crates/cotton-core/kits/shell/boards/settings.json", ownedBy: "Backup walk")        let board = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(raw.utf8)) as? [String: Any])        let parts = try XCTUnwrap(board["parts"] as? [[String: Any]])        let rows = try XCTUnwrap(parts.first?["rows"] as? [[String: Any]])        XCTAssertEqual(rows.prefix(2).compactMap { $0["id"] as? String }, ["backup", "server"])        XCTAssertTrue(rows.allSatisfy { ($0["data"] as? [String: Any])?["route"] != nil })        XCTAssertFalse(code.contains("ToolView("), "acts never become view choices")    }    /// RULE: an empty Home says the kit's one invitation in the app's own    /// name — Rigby's says "into Rigby", a business's its own, never Cotton.    func testHomeInvitationIsTheSharedKitsLineInTheAppsName() throws {        let previous = ShellLines.speaker        defer { ShellLines.speaker = previous }        for flavour in ["Cotton", "Rigby", "Invented"] {            ShellLines.speaker = flavour            XCTAssertEqual(ShellLines.line("board", "today.empty"), "Nothing here yet. Tap + to add something, or share a picture, a page or a file into \(flavour).")        }    }    func testCopyReplacementRereadsEveryMountedBoardFamily() async {        let sync = SyncModel(core: ScriptedCore())        let boards = CountingBackupBoards()        let home = BoardModel(boards: boards, id: "home")        let settings = BoardModel(boards: boards, id: "settings")        await home.load()        await settings.load()        sync.copyReplaced()        XCTAssertEqual(Set(sync.invalidated), Set(ScreenFamily.allCases))        XCTAssertEqual(sync.revision, 1)        XCTAssertEqual(sync.foreignRevision, 1)        await sync.reread(home, in: nil)?.value        await sync.reread(settings, in: nil)?.value        let counts = await boards.counts        XCTAssertEqual(counts, ["home": 2, "settings": 2])    }}private actor CountingBackupBoards: BoardsCalling {    var counts: [String: Int] = [:]    func board(_ id: String) async throws -> DrawnBoard {        counts[id, default: 0] += 1        return DrawnBoard(definition: Data("{\"format_version\":1,\"id\":\"\(id)\",\"parts\":[]}".utf8))    }    func passedOver(board: String, part: String, databaseId: String, databaseName: String) async throws -> Bool { false }}#endif