Cotton code
369 lines · 15.8 KB · SwiftRaw
// `Route`, held both ways.//// What this holds, and the previous app never could state, is the property// **`parse(r.path) == r` for every case**. An enum with a formatter and a// parser that disagree is a deep link that opens the wrong screen, and the// pair is only a bijection if something says so.//// `everyRoute` below is one value per case, with synthetic ids. It is written// out rather than derived because Swift cannot enumerate an enum with// associated values — which is exactly why the totality test in// `CottonUITests/RouteTableTests.swift` compares `allPatterns` with Rust's own// `ROUTES` instead of trusting this list to be complete.import XCTest@testable import CottonKitfinal class RouteTests: XCTestCase {    // RULE: The Calls tool's root link reaches the same history as its existing address.    func testCallsRootAlias() {        XCTAssertEqual(Route.parse("/calls"), .callsHistory(person: nil))        XCTAssertEqual(Route.parse("/calls?person=synthetic-person"), .callsHistory(person: "synthetic-person"))    }    func testThePairIsABijectionOverEveryCase() {        for route in RouteTests.everyRoute {            XCTAssertEqual(                Route.parse(route.path),                route,                "\(route.path) did not read back as the route that wrote it"            )        }    }    func testTheRecordOnScreenIsThePayloadsIdOrItsThread() {        // `id`, wherever the case puts it.        XCTAssertEqual(Route.documentsDocument(id: "d-1").recordId, "d-1")        XCTAssertEqual(Route.calendarEvent(id: "e-1", date: "2026-09-12", at: nil).recordId, "e-1")        // A thread is a record with its own label.        XCTAssertEqual(Route.messagesThread(thread: "t-1").recordId, "t-1")        // A date, a slug, a kind or nothing at all is not a record.        XCTAssertNil(Route.journalDate(date: "2026-09-12").recordId)        XCTAssertNil(Route.todosDropped(project: "slug-1").recordId)        XCTAssertNil(Route.root.recordId)        XCTAssertNil(Route.videos.recordId)        // Every sample with an `id:` answers it, and none with none invents one.        for route in RouteTests.everyRoute {            let described = String(describing: route)            // `id: "x"` on a required id, `id: Optional("x")` on an optional one.            if described.contains("id: \"") || described.contains("id: Optional(\"") {                XCTAssertNotNil(route.recordId, described)            } else if !described.contains("thread: \"") {                XCTAssertNil(route.recordId, described)            }        }    }    func testEveryPatternIsReachedByAtLeastOneSample() {        // Anti-vacuity for the bijection above: a sample list missing a case        // would pass it while proving nothing about that case.        XCTAssertEqual(RouteTests.everyRoute.count, Route.allPatterns.count)    }    func testTheTableIsAbsoluteSortedAndUnique() {        XCTAssertTrue(Route.allPatterns.allSatisfy { $0.hasPrefix("/") })        XCTAssertEqual(Route.allPatterns, Route.allPatterns.sorted())        XCTAssertEqual(Set(Route.allPatterns).count, Route.allPatterns.count)    }    func testMatchingIsExactAndNeverAPrefix() {        // `/todos/done` and `/todos/todo/[id]` are two screens. A parser that        // answered "yes" to `/todos/anything` would send a notification tap to        // the wrong one.        XCTAssertEqual(Route.parse("/todos/done"), .todosDone(project: nil))        XCTAssertEqual(Route.parse("/todos/todo/abc"), .todosTodo(id: "abc"))        XCTAssertNil(Route.parse("/todos/todo"))        XCTAssertNil(Route.parse("/todos/todo/abc/extra"))        XCTAssertNil(Route.parse("/nothing-of-ours"))        XCTAssertNil(Route.parse("todos"), "a route is absolute")    }    func testALiteralBeatsAParameterAtTheSameLength() {        // Both patterns match `/messages/import`; the literal is the screen.        XCTAssertEqual(Route.parse("/messages/import"), .messagesImport)        XCTAssertEqual(Route.parse("/messages/new"), .messagesNew)        XCTAssertEqual(Route.parse("/messages/xyz"), .messagesThread(thread: "xyz"))        XCTAssertEqual(Route.parse("/members/admit"), .membersAdmit)    }    func testTheFourDeepLinkEntryPointsParse() {        for path in ["/capture", "/take", "/keyboard-take", "/search"] {            XCTAssertNotNil(Route.parse(path), "\(path) is a documented entry point")        }    }    func testTheSchemeSLinksLandWhereTheyAlwaysHave() {        // Wire protocol: the Android keyboard writes one of these, and it is        // already shipped.        //        // The scheme is not read: the system hands a link to the app that        // registered its scheme, so the real app's and Cotton Dev's land alike.        XCTAssertEqual(            Route.deepLink(URL(string: "tinmen-cotton://capture")!),            .capture        )        XCTAssertEqual(Route.deepLink(URL(string: "tinmen-cotton://keyboard-take")!), .take)        XCTAssertEqual(            Route.deepLink(URL(string: "tinmen-cotton://mood?score=4")!),            .mood        )        // A path, read as one.        XCTAssertEqual(            Route.deepLink(URL(string: "tinmen-cotton://people/person/p1")!),            .peoplePerson(id: "p1")        )        XCTAssertEqual(            Route.deepLink(URL(string: "tinmen-cotton://todos")!),            .todos(new: false)        )        XCTAssertEqual(            Route.deepLink(URL(string: "tinmen-cotton://notes/journal-today")!),            .notesJournalToday        )        XCTAssertNil(Route.deepLink(URL(string: "tinmen-cotton://nothing-of-ours")!))        XCTAssertEqual(Route.deepLink(URL(string: "cottondev://capture")!), .capture)        XCTAssertEqual(Route.deepLink(URL(string: "cottondev://keyboard-take")!), .take)    }    func testAnOldMoodScoreLinkOpensTheTimelineAndCarriesNothing() {        // The score went with schema v8. A link still carrying one opens the        // timeline, and the route has nowhere to        // put a number, so nothing downstream can record a moment from it.        XCTAssertEqual(Route.parse("/mood?score=4"), .mood)        XCTAssertEqual(Route.parse("/mood?score=three"), .mood)        XCTAssertEqual(Route.parse("/mood"), .mood)        XCTAssertEqual(Route.mood.path, "/mood")    }    func testQueryStateRidesOnTheCaseThatReadsIt() {        XCTAssertEqual(Route.calendar(date: "2026-09-09").path, "/calendar?date=2026-09-09")        XCTAssertEqual(Route.calendar(date: nil).path, "/calendar")        // The + fan's two open-focused asks.        XCTAssertEqual(Route.todos(new: true).path, "/todos?new=1")        XCTAssertEqual(Route.todos(new: false).path, "/todos")        // The + fan's Recording row, and the Meetings list's Import verb.        XCTAssertEqual(Route.meetings(importing: true).path, "/meetings?import=1")        XCTAssertEqual(Route.meetings(importing: false).path, "/meetings")        // The one library's filter.        XCTAssertEqual(Route.photos(show: "videos").path, "/photos?show=videos")        XCTAssertEqual(Route.photos(show: nil).path, "/photos")        XCTAssertEqual(Route.parse("/photos?show=videos"), .photos(show: "videos"))        XCTAssertEqual(Route.parse("/photos"), .photos(show: nil))    }    func testTheOpenFocusedFlagIsOnlyAnExplicitOne() {        // `wantsNewTodo` / `wantsNewEntry` both read ONLY "1"; a `?new=true`        // is somebody guessing, and it opens nothing.        XCTAssertEqual(Route.parse("/todos?new=1"), .todos(new: true))        XCTAssertEqual(Route.parse("/todos?new=true"), .todos(new: false))        XCTAssertEqual(Route.parse("/todos?new=0"), .todos(new: false))        XCTAssertEqual(Route.parse("/todos"), .todos(new: false))        XCTAssertEqual(Route.parse("/meetings?import=1"), .meetings(importing: true))        XCTAssertEqual(Route.parse("/meetings?import=true"), .meetings(importing: false))        XCTAssertEqual(Route.parse("/meetings"), .meetings(importing: false))        // A query is not a path: the table the Rust half owns gains nothing.        XCTAssertTrue(Route.allPatterns.contains("/todos"))        XCTAssertTrue(Route.allPatterns.contains("/meetings"))        XCTAssertFalse(Route.allPatterns.contains { $0.contains("?") })    }    /// Another device's Storage is that device's own address with `storage`    /// after it; this device's stays `/storage`, which needs no key.    func testAnotherDevicesStorageIsUnderItsOwnAddress() {        let route = Route.deviceStorage(id: "device:1")        XCTAssertEqual(route.path, "/devices/device%3A1/storage")        XCTAssertEqual(Route.parse(route.path), route)        XCTAssertEqual(Route.parse("/devices/other/storage"), .deviceStorage(id: "other"))        XCTAssertEqual(Route.parse("/devices/other"), .devicesId(id: "other"))        XCTAssertEqual(Route.parse("/storage"), .storage)        XCTAssertEqual(Route.deviceStorage(id: "other").tier, .list)    }    /// RULE: there is no settings route; one of this device's host-drawn pages is `/device/[page]`, a page beside the devices list, and `/settings` parses to nothing.    func testAHostPageIsUnderThisDeviceAndSettingsIsGone() {        let route = Route.hostPage(id: "keys")        XCTAssertEqual(route.path, "/device/keys")        XCTAssertEqual(Route.parse("/device/keys"), route)        XCTAssertEqual(Route.parse("/device"), .device)        XCTAssertEqual(route.tier, .page)        XCTAssertEqual(route.listRoot, .devices)        XCTAssertNil(Route.parse("/settings"))        XCTAssertFalse(Route.allPatterns.contains("/settings"))    }    func testAnIdIsEscapedAndReadBack() {        let awkward = "a/b c?d&e"        let route = Route.notesNote(id: awkward)        XCTAssertFalse(route.path.dropFirst().contains("?"), "the id must not punctuate the path")        XCTAssertEqual(Route.parse(route.path), route)    }    // MARK: - `recordPath`    func testEveryRecordKindHasAnAddressThatParses() {        for kind in RecordKind.allCases {            let route = Route.record(kind, "r1")            XCTAssertEqual(                Route.parse(route.path),                route,                "\(kind.rawValue) produced \(route.path), which does not read back"            )        }    }    func testTheRecordPrefixesAreTheOnesThatDoNotMove() {        // Wire protocol: pushes map onto them.        XCTAssertEqual(Route.record(.todo, "x").path, "/todos/todo/x")        XCTAssertEqual(Route.record(.event, "x").path, "/calendar/event/x")        XCTAssertEqual(Route.record(.note, "x").path, "/notes/note/x")        XCTAssertEqual(Route.record(.journal, "x").path, "/notes/note/x")        XCTAssertEqual(Route.record(.person, "x").path, "/people/person/x")        XCTAssertEqual(Route.record(.personNote, "x").path, "/people/person/x")        XCTAssertEqual(Route.record(.thought, "x").path, "/thoughts/thought/x")        XCTAssertEqual(Route.record(.call, "x").path, "/calls/call/x")        XCTAssertEqual(Route.record(.location, "x").path, "/locations/location/x")        XCTAssertEqual(Route.record(.page, "x").path, "/reader/page/x")        XCTAssertEqual(Route.record(.transaction, "x").path, "/money/transactions/x")        XCTAssertEqual(Route.record(.meeting, "x").path, "/meetings/meeting/x")        XCTAssertEqual(Route.record(.document, "x").path, "/documents/document/x")        XCTAssertEqual(Route.record(.newsEdition, "x").path, "/news/edition/x")        XCTAssertEqual(Route.record(.messageThread, "x").path, "/messages/x")        XCTAssertEqual(Route.record(.memory, "x").path, "/memory/x")        XCTAssertEqual(Route.record(.session, "x").path, "/sessions/x")        XCTAssertEqual(Route.record(.goal, "x").path, "/goals/goal/x")        XCTAssertEqual(Route.record(.photo, "x").path, "/photos/photo/x")        XCTAssertEqual(Route.record(.video, "x").path, "/videos/video/x")    }    func testTheTwoKindsWithNoPageOfTheirOwnSaySo() {        // A message has no page: it is read in the conversation it belongs to,        // and this builder is handed a MESSAGE id, which does not know its        // session. The honest landing is the ONE list, which is `/code`.        XCTAssertEqual(Route.record(.sessionMessage, "m1").path, "/code")        // A check-in is one dot among fourteen days, and the fortnight is what        // a person opens to read any of them. The id is deliberately unused.        XCTAssertEqual(Route.record(.mood, "m1").path, "/mood")    }    static let everyRoute: [Route] = [        .root,        .money,        .moneyAccount(id: "id-1"),        .moneyStatement(id: "id-1"),        .moneyTransaction(id: "id-1"),        .activity,        .alarms,        .backup,        .bin,        .briefing(project: "project-1"),        .calendar(date: "date-1"),        .calendarEvent(id: "id-1", date: "date-1", at: "at-1"),        .calendarEventEdit(id: "id-1", date: "date-1", at: "at-1"),        .calendarMonth(date: "date-1"),        .callsCall(id: "id-1"),        .callsHistory(person: "person-1"),        .camera,        .capture,        .code,        .codeNew(project: "project-1"),        .devices,        .devicesId(id: "id-1"),        .deviceStorage(id: "id-1"),        .hostPage(id: "keys"),        .storage,        .database,        .me,        .device,        .bringIn,        .export,        .storageId(id: "id-1"),        .documents(status: "status-1"),        .documentsDocument(id: "id-1"),        .documentsDocumentViewer(id: "id-1"),        .documentsImport,        .email,        .emailId(id: "id-1", at: "at-1"),        .search,        .server,        .goals,        .goalsGoal(id: "id-1"),        .home,        .journal,        .journalDate(date: "date-1"),        .keyboardTake,        .about, .aboutWhatsNew, .aboutHelp,        .legalPrivacy,        .legalTerms,        .tableList(table: "table-1", filter: "{\"key-1\":\"value-1\"}", title: "title-1", query: "query-1"),        .locations,        .locationsLocation(id: "id-1"),        .meetings(importing: false),        .meetingsMeeting(id: "id-1"),        .meetingsRecord,        .memory(id: "id-1"),        .memoryDropped,        .messages,        .messagesThread(thread: "thread-1"),        .messagesInfo(thread: "thread-1"),        .messagesMedia(thread: "thread-1"),        .messagesImport,        .messagesNew,        .messagesStarred,        .mood,        .news,        .newsEdition(id: "id-1"),        .newsSettings,        .newsTopic(id: "id-1"),        .newsTopicNew,        .notes,        .notesJournalToday,        .notesNote(id: "id-1"),        .passwords,        .passwordsSecret(id: "id-1"),        .people,        .peopleImport,        .peoplePerson(id: "id-1"),        .peoplePersonSection(id: "id-1", section: "section-1"),        .photos(show: nil),        .photosAlbum(id: "id-1"),        .photosAlbumAdd(id: "id-1"),        .photosAlbums,        .photosDuplicates,        .photosPeople,        .photosPhoto(id: "id-1"),        .projects,        .projectsSlug(slug: "slug-1"),        .projectsSlugSection(slug: "slug-1", section: "section-1"),        .projectsBrand(slug: "slug-1"),        .projectsCode(slug: "slug-1"),        .projectsFeedback(slug: "slug-1"),        .projectsFeedbackReport(slug: "slug-1", id: "slug-1:id-1"),        .projectsMemory(slug: "slug-1"),        .projectsTodos(slug: "slug-1"),        .reader,        .readerPage(id: "id-1"),        .rejected,        .members,        .membersAdmit,        .membersId(id: "id-1"),        .codeDefaults,        .tools,        .toolBoard(id: "id-1"),        .tableRecord(table: "disk_claim", id: "id-1"),        .sessionsId(id: "id-1"),        .sessionsTerminal(id: "id-1"),        .settingsJoinRequest(id: "pair-1"),        .take,        .thoughts,        .thoughtsThought(id: "id-1"),        .todos(new: true),        .todosDone(project: nil),        .todosDropped(project: "slug-1"),        .todosTodo(id: "id-1"),        .videos,        .videosVideo(id: "id-1"),        .voiceWords,        .voiceWordsId(id: "id-1"),    ]}