Cotton code
322 lines · 22.0 KB · SwiftRaw
import CottonKitimport Foundationimport XCTest@testable import CottonUI#if os(iOS)/// Cotton Data on iPhone reads the core's answers as `crates/cotton-ffi/src/phone/data_app.rs` shapes them (CONTRACT/// "The core calls each screen needs"): snake_case keys, nulls where the core has nothing to say. Every table, row and/// name here is invented.@MainActorfinal class DataAnswersTests: XCTestCase {    private func decode<T: Decodable>(_ json: String, as: T.Type) throws -> T {        try DataCalls.decode(Data(json.utf8), as: T.self)    }    func testFirstOpenReadsKeepWithAndWithoutItsCost() throws {        let welcome = try decode("""        {"title":"Everything you keep, laid out to look at","lead":"Every table in your database.","only_looks":"This app only looks.",         "keep":{"on":true,"title":"Keep everything on this phone","cost_line":"About 30 MB of room, and about 1 minute on home Wi-Fi the first time. This phone has 41 GB free.","off_line":"With it off, rows come from the server."},         "start":"Start"}        """, as: DataWelcome.self)        XCTAssertTrue(welcome.keep.on)        XCTAssertEqual(welcome.onlyLooks, "This app only looks.")        XCTAssertNotNil(welcome.keep.costLine)        let unmeasured = try decode("""        {"title":"t","lead":"l","only_looks":"o","keep":{"on":false,"title":"k","cost_line":null,"off_line":"off"},"start":"Start"}        """, as: DataWelcome.self)        XCTAssertNil(unmeasured.keep.costLine)    }    func testTablesReadGroupsChipsRoomLeftoversAndCounting() throws {        let tables = try decode("""        {"title":"Tables","count":204,"search":"Search 204 tables",         "room":{"used_line":"6.5 GB","line":"6.5 GB of 9.5 GB","share":0.68,"go":"Where room goes"},         "chips":[{"id":"app","title":"By app","on":true},{"id":"biggest","title":"Biggest","on":false},{"id":"lately","title":"Changed lately","on":false},{"id":"az","title":"A to Z","on":false}],         "groups":[{"title":"Books","count_line":"3 tables","tables":[            {"table":"book","rows_line":"1,204 rows","line":"1,204 rows · also Days","room_line":"12 MB","mark":null,"on_phone":false,"openable":true},            {"table":"memory","rows_line":"Counting…","line":"Counting…","room_line":null,"mark":"server_reads","on_phone":false,"openable":true}]},          {"title":null,"tables":[]}],         "leftovers":{"title":"Leftovers","line":"4 tables no app uses, 1 of them retired","count":4},         "foot":"Still read by the server. Every other table is sealed."}        """, as: DataTables.self)        XCTAssertEqual(tables.count, 204)        XCTAssertEqual(tables.room?.share, 0.68)        XCTAssertEqual(tables.chips.first { $0.on == true }?.id, "app")        XCTAssertEqual(tables.groups[0].tables[1].mark, "server_reads")        XCTAssertNil(tables.groups[0].tables[1].roomLine)        XCTAssertNil(tables.groups[1].title)        XCTAssertEqual(tables.leftovers?.count, 4)        let bare = try decode("""        {"title":"Tables","count":2,"search":"Search 2 tables","room":null,"chips":[],"groups":[],"leftovers":null,"foot":null}        """, as: DataTables.self)        XCTAssertNil(bare.room)        XCTAssertNil(bare.leftovers)    }    /// FIRST SYNC STATES (f80d9c3312): Tables, a table's rows and Lately carry the first sync's words, the count while a    /// pass counts it, and nothing once it is over.    func testTheFirstSyncIsReadOnTablesRowsAndLately() throws {        let tables = try decode("""        {"title":"Tables","count":2,"search":"Search 2 tables","room":null,"chips":[],"groups":[],"leftovers":null,"foot":null,         "firstSync":{"state":"bringing","line":"Loading your data…","seen":{"state":"catching_up","line":"Syncing 1,200 of 3,108","percent":38}}}        """, as: DataTables.self)        XCTAssertEqual(tables.firstSync?.state, "bringing")        XCTAssertEqual(tables.firstSync?.said, "Syncing 1,200 of 3,108", "the count while a pass counts it")        XCTAssertEqual(tables.firstSync?.seen?.percent, 38)        let rows = try decode("""        {"table":"note","lead":"Notes you wrote.","groups":[],"empty":{"title":"No rows yet","body":"Words writes these."},         "firstSync":{"state":"unreached","line":"Can't reach Cotton right now.","seen":{"state":"offline","line":"Offline"}}}        """, as: DataRows.self)        XCTAssertEqual(rows.firstSync?.said, "Can't reach Cotton right now.", "no pass counting: the standing's own line")        let lately = try decode("""        {"title":"Lately","lead":"Every change.","chips":[],"days":[],"more":false,"foot":"Read only."}        """, as: DataLately.self)        XCTAssertNil(lately.firstSync, "over: no first sync")    }    /// At the largest text a table's name breaks after an underscore, never inside a word; its letters are unchanged.    func testATablesNameBreaksOnlyAfterAnUnderscore() {        let wrapped = DataWrap.atUnderscores("event_attendee")        XCTAssertEqual(wrapped, "event_\u{200B}attendee")        XCTAssertEqual(wrapped.replacingOccurrences(of: "\u{200B}", with: ""), "event_attendee")        XCTAssertEqual(DataWrap.atUnderscores("note"), "note")    }    func testWhereRoomGoesReadsItsPartsAndBiggest() throws {        let room = try decode("""        {"title":"Where room goes","lead":"6.5 GB of the 9.5 GB your database may grow to.",         "parts":[{"id":"free","name":"Free","size_line":"3 GB","line":"Room left before the cap.","share":0.32,"stays_on_server":false},                  {"id":"rows","name":"Your rows","size_line":"1.5 GB","line":"What you actually keep.","share":0.16,"stays_on_server":false}],         "biggest_title":"Biggest tables","biggest_note":"rows only",         "biggest":[{"table":"message","size_line":"310 MB","share":1.0}],         "deleted_line":"88 rows","measured_line":"Measured 2 hours ago."}        """, as: DataRoom.self)        XCTAssertEqual(room.parts.count, 2)        XCTAssertFalse(room.parts[1].staysOnServer)        XCTAssertEqual(room.biggest.first?.share, 1.0)    }    func testRowsReadMonthsPagingEmptyAndTheLockedList() throws {        let rows = try decode("""        {"table":"book","lead":"1,204 rows · used by Books","search":"Search 1,204 rows","sort_line":"Newest first","date_line":"Any time",         "groups":[{"title":"November 2026","count":2,"rows":[{"id":"b1","title":"The Salt Monsoon","line":"Meera Joshi · paperback","when":"3 days ago"},{"id":"b2","title":"River Map","line":"","when":null}]}],         "more":true,"after":{"at":"2026-11-01T09:00:00Z","id":"b2"},"foot":"Each line is made from the fields that tell rows apart: author, format.","empty":null}        """, as: DataRows.self)        XCTAssertEqual(rows.groups[0].rows.count, 2)        XCTAssertEqual(rows.more, true)        XCTAssertEqual(rows.after?["id"], .string("b2"))        XCTAssertNil(rows.sealedView)        let empty = try decode("""        {"table":"trip","lead":"No rows · used by Days","search":null,"sort_line":"Newest first","date_line":"Any time","groups":[],"more":false,"after":null,"foot":null,         "empty":{"title":"No rows yet","body":"Days adds one when it has something to keep. The table is ready, with 9 columns.","act":"See its columns"}}        """, as: DataRows.self)        XCTAssertEqual(empty.empty?.act, "See its columns")        let searched = try decode("""        {"table":"book","lead":"l","q":"salt","groups":[{"title":"1 row","count":1,"rows":[{"table":"book","id":"b1","title":"The Salt Monsoon","line":"Meera Joshi"}]}],"more":false,"empty":null}        """, as: DataRows.self)        XCTAssertEqual(searched.groups[0].rows[0].table, "book")        let locked = try decode("""        {"table":"note","lead":"88 rows · used by Words","sealed_view":true,         "locked":{"title":"Locked","line":"You are seeing only what the server sees.","sizes":"Sizes are rounded up.","unlock":"Unlock",                   "no_key_line":"This phone doesn't have your key yet.","acts":[{"id":"approve","title":"Approve from your other phone"},{"id":"recovery","title":"Use a recovery code"}]},         "rows":[{"id":"n1","made_line":"Made 3 Nov 2026","clear_line":"archived false","points_line":"links to a notebook","size_line":"256 bytes"}],         "groups":[],"more":false}        """, as: DataRows.self)        XCTAssertEqual(locked.sealedView, true)        XCTAssertEqual(locked.locked?.acts?.count, 2)        XCTAssertEqual(locked.rows?.first?.pointsLine, "links to a notebook")    }    func testPagingPlacesAreSentAsText() {        XCTAssertEqual(DataCalls.place(.number(4821)), .string("4821"))        XCTAssertEqual(DataCalls.place(.object(["at": .number(1_764_000_000_000), "id": .string("b2")])),                       .object(["at": .string("1764000000000"), "id": .string("b2")]))        XCTAssertEqual(DataCalls.place(.string("2026-11-01T09:00:00Z")), .string("2026-11-01T09:00:00Z"))        XCTAssertNil(DataCalls.place(nil))    }    func testOneRowReadsEveryKindPointsHereAndTheTrail() throws {        let row = try decode("""        {"table":"book","id":"b1","title":"The Salt Monsoon","lead":"A row in book · made 3 Oct 2026",         "trail":[{"table":"author","id":"a1","name":"Meera Joshi"},{"table":"book","id":"b1","name":"The Salt Monsoon"}],         "fields":[          {"column":"author","type_line":"link","kind":"link","value_line":"Meera Joshi","link":{"table":"author","id":"a1"},"clear":true,"empty":false},          {"column":"tags","type_line":"text, several","kind":"several","value_line":"travel, rain","items":["travel","rain"],"clear":false,"empty":false},          {"column":"people","type_line":"link, several","kind":"link","value_line":"Asha, Ravi","items":["Asha","Ravi"],"link":{"table":"person","ids":["p1","p2"]},"clear":false,"empty":false},          {"column":"price","type_line":"amount","kind":"amount","value_line":"₹ 499.00","clear":false,"empty":false},          {"column":"bought_on","type_line":"date","kind":"date","value_line":"3 October 2026","sub":"A Saturday","clear":true,"empty":false},          {"column":"site","type_line":"url","kind":"url","value_line":"books.example","url":"https://books.example/salt","clear":false,"empty":false},          {"column":"cover","type_line":"photo","kind":"photo","value_line":"cover.jpg","media":"files/cover.jpg","clear":false,"empty":false},          {"column":"notes","type_line":"long text, 12 lines","kind":"long","value_line":"line","folded":{"lines":12,"all_line":"Show all 12 lines"},"clear":false,"empty":false},          {"column":"finished","type_line":"yes or no","kind":"bool","value_line":"Yes","clear":true,"empty":false},          {"column":"format","type_line":"choice","kind":"choice","value_line":"Paperback","sub":"Of Paperback, Hardback","clear":false,"empty":false},          {"column":"isbn","type_line":"text","kind":"text","value_line":"Nothing yet","clear":false,"empty":true}],         "points_here":[{"table":"loan","column":"book","through_line":"through book","count":3,"rows":[{"table":"loan","id":"l1","title":"To Asha"}]}],         "points_title":"Points here","several_note":"Links that hold several values aren't counted here yet.","stored":"As stored",         "foot":"Read only. This row is changed in Books."}        """, as: DataRow.self)        XCTAssertEqual(row.trail?.count, 2)        XCTAssertEqual(row.fields?.count, 11)        XCTAssertEqual(row.fields?[0].link?.id, "a1")        XCTAssertEqual(row.fields?[2].link?.ids, ["p1", "p2"])        XCTAssertEqual(row.fields?[7].folded?.lines, 12)        XCTAssertEqual(row.fields?[10].empty, true)        XCTAssertEqual(row.pointsHere?.first?.count, 3)        XCTAssertNil(row.sealedView)        let sealed = try decode("""        {"table":"note","id":"n1","sealed_view":true,"title":"Locked",         "band":{"title":"This phone doesn't have your key yet","line":"Everything below is what the server can show without it."},         "facts":[{"label":"Table","value":"note"},{"label":"Made","value":"3 Nov 2026"}],         "acts":[{"id":"approve","title":"Approve from your other phone"},{"id":"recovery","title":"Use a recovery code"}]}        """, as: DataRow.self)        XCTAssertEqual(sealed.facts?.count, 2)        XCTAssertNil(sealed.fields)    }    func testTheTrailIsSentBackAsTheCoreReadsIt() throws {        let sent = try JSONEncoder().encode(["trail": DataValue.steps([DataStep(table: "author", id: "a1", name: "Meera Joshi")])])        let back = try JSONSerialization.jsonObject(with: sent) as? [String: [[String: String]]]        XCTAssertEqual(back?["trail"]?.first, ["table": "author", "id": "a1", "name": "Meera Joshi"])    }    func testStoredLinkAndMedia() throws {        let stored = try decode("""        {"fields":[{"column":"author","stored":"a1"},{"column":"price","stored":"{\\"amount\\":49900,\\"currency\\":\\"INR\\"}"}],"plain":"Plain words"}        """, as: DataStored.self)        XCTAssertEqual(stored.fields.count, 2)        let link = try decode("""        {"title":"A link","from_line":"From site on The Salt Monsoon","address":"https://books.example/salt","site":"books.example",         "open":"Open in browser","copy":"Copy link","copied":"Copied","note":"Opens in your browser, outside Cotton."}        """, as: DataLinkSheet.self)        XCTAssertEqual(link.site, "books.example")        let media = try decode("""        {"name":"cover.jpg","key":"files/cover.jpg","kind":"photo","size_title":"Size","from_title":"From","from_line":"cover on The Salt Monsoon",         "note":"Fetched from your files to show it here.","offline":"This file needs the network to open.","close":"Close"}        """, as: DataMedia.self)        XCTAssertEqual(media.key, "files/cover.jpg")    }    func testAboutColumnsAndLinks() throws {        let about = try decode("""        {"table":"book","title":"About book","lead":"1,204 rows, 12 MB. Oldest from 3 Oct 2021, newest from 2 days ago.",         "facts":[{"icon":"lock","title":"Sealed","line":"Opened only on your phones.","clear":["bought_on"]},                  {"icon":"app","title":"No app uses it","line":null},                  {"icon":"assistant","title":"Claude may read it","line":"Inside a window you open.","act":"assistants"}],         "rows":[{"id":"columns","title":"Columns","value_line":"9"},{"id":"links","title":"How it links","value_line":"2"}],         "foot":"This page tells; it changes nothing."}        """, as: DataAbout.self)        XCTAssertEqual(about.facts[2].act, "assistants")        XCTAssertNil(about.facts[1].line)        let columns = try decode("""        {"title":"Columns","lead":"9 columns.","clear_word":"clear",         "columns":[{"name":"author","type_line":"Link to author","clear":true,"link":"author"},{"name":"title","type_line":"Text","clear":false,"link":null}]}        """, as: DataColumns.self)        XCTAssertEqual(columns.columns[0].link, "author")        XCTAssertNil(columns.columns[1].link)        let links = try decode("""        {"table":"book","title":"How book links","lead":"One table in the middle.","out_title":"It points at","in_title":"Point at it",         "out":[{"table":"author","column":"author","through_line":"through author","counted":true,"count_line":null}],         "in":[{"table":"note","column":"books","through_line":"through books, several","counted":false,"count_line":"not counted yet"}],         "two_steps_line":"Two steps away: person.","none":null}        """, as: DataLinks.self)        XCTAssertEqual(links.in.first?.counted, false)        XCTAssertEqual(links.out.first?.table, "author")    }    func testSearchLatelyAssistantsAndLeftovers() throws {        let empty = try decode("""        {"title":"Search","placeholder":"Search everything","groups":[],"tables":[],"columns":[]}        """, as: DataSearch.self)        XCTAssertNil(empty.searchedLine)        let search = try decode("""        {"title":"Search","chips":[{"id":"everything","title":"Everything"},{"id":"rows","title":"Rows"}],         "groups":[{"table":"book","title":"Books","rows":[{"table":"book","id":"b1","title":"The Salt Monsoon","line":"Meera Joshi"}]}],         "found_line":"1 row in 1 table","tables":[{"table":"book","line":"Books"}],"columns":[{"table":"book","column":"booked_on"}],         "searched_line":"Searched every word in all 204 tables, on this phone. Passwords and passkeys are left out of search.",         "nothing":null}        """, as: DataSearch.self)        XCTAssertEqual(search.groups[0].rows[0].id, "b1")        XCTAssertEqual(search.columns.first?.column, "booked_on")        let lately = try decode("""        {"title":"Lately","lead":"Every change to your database, and who made it.",         "chips":[{"id":"all","title":"All"},{"id":"you","title":"You"}],         "days":[{"title":"Today","count_line":"4 changes","items":[{"line":"Claude added 3 rows to memory","table":"memory","when":"9:12","count":3}]}],         "more":true,"before":4821,"foot":"Changes are kept for 90 days."}        """, as: DataLately.self)        XCTAssertEqual(lately.days[0].items[0].count, 3)        XCTAssertEqual(DataCalls.place(lately.before), .string("4821"))        let assistants = try decode("""        {"title":"Assistants","lead":"What each one has read and written.",         "assistants":[{"name":"Claude","items":[{"table":"memory, project","line":"read 14 rows · search_records","when":"2 days ago"}],"more_line":null}],         "none":null,"never_title":"Never allowed","never_line":"secret, passkey and code_credential.","gap_line":"Reads of the three open tables aren't logged yet."}        """, as: DataAssistants.self)        XCTAssertEqual(assistants.assistants.first?.items.count, 1)        let leftovers = try decode("""        {"title":"Leftovers","lead":"Kept in your database, but nothing uses them now.",         "unused":{"title":"No app uses these","line":"2 tables · 4 MB","tables":[{"table":"old_list","line":"12 rows · last written 2 years ago","room_line":"1 MB"}]},         "retired":null,         "dangling":{"title":"Links pointing at nothing","items":[{"line":"11 notes point at a missing notebook","through_line":"through notebook","table":"note","column":"notebook"}]},         "foot":"This app only shows them.","none":null}        """, as: DataLeftovers.self)        XCTAssertNil(leftovers.retired)        XCTAssertEqual(leftovers.dangling?.items.first?.table, "note")    }    func testKeepAndYou() throws {        let keep = try decode("""        {"title":"Keep everything on this phone","switch":"Keep everything","on":true,"wifi_only":true,"costs_title":"What it costs you",         "cost":[{"name":"Room on this phone","value_line":"1.5 GB"},{"name":"This phone has","value_line":"41 GB free"}],         "why_line":"Only your rows come down.","privacy_line":"Rows are kept opened on this phone.","how_title":"How","wifi":"Only on Wi-Fi",         "wifi_line":"Waits rather than use mobile data","short_title":"When room runs short","short_line":"It keeps the newest rows first.",         "all_mail_line":"Mail and chats included.","state":"filling","state_line":"Filling this phone, 42%",         "progress":{"percent":42,"left_line":"About 29 minutes left","line":"Everything already here works now."},"too_small_line":null}        """, as: DataKeep.self)        XCTAssertEqual(keep.switch, "Keep everything")        XCTAssertEqual(keep.progress?.percent, 42)        let off = try decode("""        {"title":"t","switch":"s","on":false,"wifi_only":true,"costs_title":"c","cost":[],"why_line":null,"privacy_line":"p","how_title":"h","wifi":"w",         "wifi_line":"wl","short_title":"st","short_line":"sl","all_mail_line":"m","state":"off","state_line":null,"progress":null,"too_small_line":"small"}        """, as: DataKeep.self)        XCTAssertNil(off.progress)        XCTAssertEqual(off.state, "off")        let you = try decode("""        {"title":"You","card":{"line":"204 tables"},         "rows":[{"id":"keep","title":"Keep everything on this phone","value_line":"On"},{"id":"assistants","title":"Assistants","value_line":null},                 {"id":"look","title":"Look","value_line":null}],         "privacy_line":"Read only, opened on this phone"}        """, as: DataYou.self)        XCTAssertEqual(you.rows.map(\.id), ["keep", "assistants", "look"])    }    /// Look's preview for Data (`look.json`'s `preview.data`): its row line, table line and amount, beside every other    /// app's shape.    func testLookPreviewReadsDatasShape() throws {        let preview = try JSONDecoder().decode(LookAnswer.Preview.self, from: Data("""        {"rows":[{"title":"The Salt Monsoon","line":"Meera Joshi · paperback","when":"3 Oct"},{"title":"message","line":"412,880 rows","when":"310 MB","mono":true}],         "shown":{"column":"price","type":"amount","value":"₹ 499.00"}}        """.utf8))        XCTAssertEqual(preview.dataRows?.count, 2)        XCTAssertEqual(preview.dataRows?[1].mono, true)        XCTAssertEqual(preview.field?.value, "₹ 499.00")        XCTAssertNil(preview.rows)        XCTAssertNil(preview.sites)        XCTAssertNil(preview.shown)        let again = try JSONDecoder().decode(LookAnswer.Preview.self, from: JSONEncoder().encode(preview))        XCTAssertEqual(again, preview)        let sites = try JSONDecoder().decode(LookAnswer.Preview.self, from: Data("""        {"rows":[{"letter":"W","label":"Work mail","line":"mail.example"}],"bar":{"label":"Work mail","site":"mail.example","thread":true}}        """.utf8))        XCTAssertEqual(sites.sites?.count, 1)        XCTAssertNil(sites.dataRows)    }    func testUnmeteredIsWifiOrWiredNeitherExpensiveNorConstrained() {        XCTAssertTrue(NetworkUnmetered.unmetered(satisfied: true, wifiOrWired: true, expensive: false, constrained: false))        XCTAssertFalse(NetworkUnmetered.unmetered(satisfied: true, wifiOrWired: true, expensive: true, constrained: false))        XCTAssertFalse(NetworkUnmetered.unmetered(satisfied: true, wifiOrWired: true, expensive: false, constrained: true))        XCTAssertFalse(NetworkUnmetered.unmetered(satisfied: true, wifiOrWired: false, expensive: false, constrained: false))        XCTAssertFalse(NetworkUnmetered.unmetered(satisfied: false, wifiOrWired: true, expensive: false, constrained: false))    }}#endif