Cotton code
123 lines · 7.5 KB · SwiftRaw
import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class MessagesConversionTests: XCTestCase {  private func definitions() -> TableDefinitions {    TableDefinitions(      FixtureDefinitions.load(        from: Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources"))      ).definitions)  }  /// RULE: A group chat's Details name its people: the title of every person a several-record link holds is asked for, so each draws as a tag that opens that person.  func testAGroupsPeopleAreAskedForByName() throws {    let thread = try XCTUnwrap(definitions()["thread"])    XCTAssertEqual(thread.column("member_people")?.linkTo, "person")    let group = TableRecord(id: "synthetic-group", values: ["member_people": .list([.text("person-a"), .text("person-b"), .text("person-a")])])    let asked = Set(thread.links(in: [group]))    XCTAssertEqual(asked, [RecordLink(table: "person", id: "person-a"), RecordLink(table: "person", id: "person-b")])    XCTAssertEqual(thread.links(in: [TableRecord(id: "synthetic-dm", values: [:])]), [])  }  /// RULE: Pin ordering puts the newest pin first and unpinned threads newest-message first; a missing pin never reverses chronology.  func testPinsAndUnpinnedChronology() throws {    let d = try XCTUnwrap(definitions()["thread"])    let rows = [      TableRecord(id: "old", values: ["last_message_at": .text("2026-09-01")]),      TableRecord(id: "new", values: ["last_message_at": .text("2026-10-01")]),      TableRecord(id: "pin", values: ["pinned_at": .text("2026-08-01")]),    ]    XCTAssertEqual(d.sorted(rows).map(\.id), ["pin", "new", "old"])  }  /// RULE: A command with a `when` is offered only on a record holding those values, an absent value reading as false, so Pin and Unpin are never offered together.  func testACommandIsOfferedOnlyWhenItsConditionHolds() throws {    let thread = try XCTUnwrap(definitions()["thread"])    let offered = { (record: TableRecord) in Set((thread.commands ?? []).filter { $0.applies(to: record) }.map(\.id)) }    let plain = offered(TableRecord(id: "a", values: [:]))    let marked = offered(TableRecord(id: "a", values: ["pinned": .bool(true), "muted": .bool(true), "archived": .bool(true)]))    for (on, off) in [("pin", "unpin"), ("mute", "unmute"), ("archive", "unarchive")] {      XCTAssertTrue(plain.contains(on) && !plain.contains(off), "an unmarked chat is offered \(off) or not \(on)")      XCTAssertTrue(marked.contains(off) && !marked.contains(on), "a marked chat is offered \(on) or not \(off)")    }  }  /// RULE: Clear/hide remain private engine operations behind confirmation, and hide passes an id array rather than an invented single-id verb.  func testPrivateActionsKeepTheirExistingArguments() throws {    let tables = definitions()    let thread = try XCTUnwrap(tables["thread"])    XCTAssertEqual(thread.commands?.first(where: { $0.id == "clear" })?.destructive, true)    let message = try XCTUnwrap(tables["message"])    let hide = try XCTUnwrap(message.commands?.first(where: { $0.id == "hide" }))    XCTAssertEqual(hide.destructive, true)    XCTAssertEqual(      hide.arguments(for: TableRecord(id: "example-message", values: [:]))["messageIds"],      .list([.text("example-message")]))  }  /// RULE: Opening a large imported chat reads the latest fifty, grows only on demand, and never renders more than a thousand messages.  func testConversationLoadsBoundedPagesOnDemand() async throws {    let tables = definitions()    let thread = try XCTUnwrap(tables["thread"])    let message = try XCTUnwrap(tables["message"])    let rows = (0..<1100).map { i in      TableRecord(id: "m-\(i)", values: ["thread_id": .text("example-thread"), "sent_at": .text(String(format: "2026-09-%02dT%02d:%02d:00Z", 1 + i / 1440, (i / 60) % 24, i % 60))])    }    let records = FixtureRecords(definitions: [thread, message], records: ["message": rows])    let model = ConversationModel(layout: try XCTUnwrap(thread.conversation), thread: "example-thread", store: records)    await model.load()    XCTAssertEqual(model.messages.count, 50)    XCTAssertEqual(model.messages.last?.id, "m-1099")    XCTAssertTrue(model.hasMore)    await model.loadMore()    XCTAssertEqual(model.messages.count, 100)    for _ in 0..<30 { await model.loadMore() }    XCTAssertEqual(model.messages.count, 1000)    XCTAssertFalse(model.hasMore)  }  /// RULE: A group chat names its sender's picture as a column of the message, and a run of notes is told apart by who wrote them, so a name and a photo stand once, with the first note of a run.  func testAChatNamesItsSendersPicture() throws {    let d = try XCTUnwrap(definitions()["thread"])    let layout = try XCTUnwrap(d.conversation)    let theirs = TableRecord(id: "synthetic-1", values: ["paper_sender": .text(" Example Ben "), "sender_photo": .text("synthetic/key.jpg")])    XCTAssertEqual(layout.writer(of: theirs), "Example Ben")    XCTAssertEqual(layout.photoKey(of: theirs), "synthetic/key.jpg")    let mine = TableRecord(id: "synthetic-2", values: ["direction": .text("out")])    XCTAssertNil(layout.writer(of: mine))    XCTAssertNil(layout.photoKey(of: mine), "a sender with no photo has nothing drawn, never an initial")  }  /// RULE: A note's words are Markdown where the body column says so, and a chat's message says so: words with no block are set line for line, a list, a quote or code is its own block, never the stars and dashes typed.  func testANotesWordsAreMarkdownWhereTheColumnSaysSo() throws {    XCTAssertTrue(ConversationWords.isPlain(MarkdownBlocks.parse("see you at **six**\nbring the pot")))    XCTAssertFalse(ConversationWords.isPlain(MarkdownBlocks.parse("to bring:\n- the pot\n- chairs")))    XCTAssertFalse(ConversationWords.isPlain(MarkdownBlocks.parse("```\ncargo test\n```")))  }  /// RULE: DMs remain cream even with sender metadata; group members use the collision-resolving palette.  func testConversationUsesGroupPaletteOnlyForGroups() {    let assigned = ChatPaper.groupDyes(["example-one", "example-two"])    XCTAssertEqual(Set(assigned.values).count, 2)    XCTAssertEqual(ChatPaper.dye(mine: false, sender: "example-one", isGroup: false, assigned: assigned), .cream)  }  /// RULE: A chat's archive and kept lists open under their own names and empty words (the related entry's, not the table's) with no list-level links or "+" of their own, Members is offered on a group only, and Clear chat asks first.  func testRelatedListsSayWhatTheyAre() throws {    let d = try XCTUnwrap(definitions()["thread"])    let archive = try XCTUnwrap(d.related?.first { $0.table == "thread" && $0.archived == true })    let listed = archive.listed(d)    XCTAssertEqual(listed.plural, try XCTUnwrap(archive.title))    XCTAssertEqual(try XCTUnwrap(listed.empty).title, try XCTUnwrap(archive.empty).title)    XCTAssertNil(listed.create)    XCTAssertTrue((listed.related ?? []).allSatisfy { $0.column != nil })    let kept = try XCTUnwrap(d.related?.first { $0.table == "message" && $0.empty != nil })    let message = try XCTUnwrap(definitions()["message"])    XCTAssertEqual(try XCTUnwrap(kept.listed(message).empty).title, try XCTUnwrap(kept.empty).title)    let members = try XCTUnwrap(d.related?.first { $0.table == "thread_member" })    XCTAssertTrue(members.applies(to: TableRecord(id: "g", values: ["kind": .text("group")])))    XCTAssertFalse(members.applies(to: TableRecord(id: "d", values: ["kind": .text("dm")])))    let clear = try XCTUnwrap(d.commands?.first { $0.id == "clear" })    XCTAssertNotNil(clear.confirm)  }}