Cotton code
118 lines · 8.4 KB · SwiftRaw
import CottonKitimport CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class EmailConversionTests: XCTestCase {    private var resources: Bundle { get throws {        try XCTUnwrap(Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources")))    }}    private func tables() throws -> AppTables {        let bundle = try resources        let loaded = FixtureDefinitions.load(from: bundle)        XCTAssertEqual(loaded.failures, [])        let definitions = loaded.definitions        var records: [String: [TableRecord]] = [:]        for definition in definitions { records[definition.id] = try FixtureDefinitions.fixtureRecords(for: definition.id, bundle: bundle) }        return AppTables(records: FixtureRecords(definitions: definitions, records: records), definitions: TableDefinitions(definitions), linkTitles: LinkTitles(definitions, records))    }    // RULE: An archive conversation cannot create mail; ingest and delivery belong to Rust, and no send verb exists for this archive.    func testArchiveConversationCannotCreateMail() async throws {        let definitions = FixtureDefinitions.load(from: try resources)        XCTAssertTrue(definitions.failures.isEmpty, definitions.failures.joined(separator: "\n"))        let thread = try XCTUnwrap(definitions.definitions.first { $0.id == "email_thread" })        let layout = try XCTUnwrap(thread.conversation)        XCTAssertTrue(thread.pageParts.contains(.messages))        XCTAssertFalse(layout.canSend)        XCTAssertNil(layout.sent("Reply", thread: "example-email-thread"))        let store = try tables().records        let before = try await store.list(table: "email", project: nil, query: nil, page: 0)        let model = ConversationModel(layout: layout, thread: "example-email-thread", store: store)        let change = try await model.send("Reply")        XCTAssertNil(change)        let after = try await store.list(table: "email", project: nil, query: nil, page: 0)        XCTAssertEqual(before.records, after.records)    }    // RULE: The imported envelope retains whitespace, address ownership and attachment names; a display name alone never makes a message yours.    func testRustEnvelopeProjectsWithoutChangingTheBody() throws {        let value = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"id":"one","data":{"from_name":"You","from_email":"other@example.invalid","body":" A\n ","direction":"in","thread_id":"thread","to_line":"Example <e@example.invalid>","media":[{"contentType":"application/pdf","name":"note.pdf"}]}}"#.utf8))        let row = try EmailRecords.record(value)        XCTAssertEqual(row["body"].text, " A\n ")        XCTAssertEqual(row["direction"].text, "in")        XCTAssertEqual(row["to_line"].text, "Example <e@example.invalid>")        XCTAssertEqual(row["media"], .list([.object(["contentType": .text("application/pdf"), "name": .text("note.pdf")])]))    }    // RULE: The merged Records protocol counts the same Rust records that lists draw and forwards the engine's pagination handle unchanged.    func testEmailCountAndPaginationUseTheGenericEngine() async throws {        let core = ScriptedCore(["records.list": .ok(#"{"records":[{"id":"one","data":{"subject":"Example"}}],"next_page":null}"#)])        let store = EmailRecords(core: core, definitions: [])        let count = try await store.count(table: "email_thread")        XCTAssertEqual(count, 1)        _ = try await store.list(table: "email_thread", project: nil, query: nil, page: 50, where: [:])        let calls = await core.calls        let request = try XCTUnwrap(calls.last)        let object = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(request.requestJSON.utf8)) as? [String: Any])        XCTAssertEqual(object["page"] as? Int, 50)    }    /// RULE: Email's Today view reads the core's plan section — its section, the reader's zone and day ride the read — never the whole mailbox answered as if it were Today (views programme).    func testAViewSectionRidesTheEmailRead() async throws {        let core = ScriptedCore(["records.list": .ok(#"{"records":[],"next_page":null,"total":0}"#)])        let store = EmailRecords(core: core, definitions: [])        var plan = PlanView(section: "today", timezone: "Area/City")        plan.today = "2026-10-20"        _ = try await store.list(table: "email_thread", project: nil, query: nil, page: 0, where: [:], limit: nil, plan: plan)        let calls = await core.calls        let asked = try JSONDecoder().decode(JSONValue.self, from: Data(try XCTUnwrap(calls.last).requestJSON.utf8))        XCTAssertEqual(asked.text("section"), "today")        XCTAssertEqual(asked.text("timezone"), "Area/City")        XCTAssertEqual(asked.text("today"), "2026-10-20")    }    /// RULE: Empty Junk is offered on the Junk view while Junk holds a conversation, and on no other view — binning every Junk thread is never a click away from another list.    func testEmptyJunkIsTheJunkViewsActWhileJunkHoldsMail() async throws {        let core = ScriptedCore(["records.list": .ok(#"{"records":[{"id":"j1","data":{"subject":"Junk"}}],"next_page":null,"total":1}"#)])        let store = EmailRecords(core: core, definitions: [])        let onJunk = await store.listActions(table: "email_thread", where: ["sender_kind": .text("junk")])        XCTAssertEqual(onJunk.map(\.id), ["empty_junk"])        let onPeople = await store.listActions(table: "email_thread", where: ["sender_kind": .text("person")])        XCTAssertEqual(onPeople, [])        await core.answer("records.list", .ok(#"{"records":[],"next_page":null,"total":0}"#))        let emptied = await store.listActions(table: "email_thread", where: ["sender_kind": .text("junk")])        XCTAssertEqual(emptied, [])    }    /// RULE: The Mail screen's search box asks Find scoped to mail (`read.find`, `scope: "mail"`) and lists the conversations its hits name — once each, in Find's order — read whole by id (mailsearch).    func testTheMailSearchBoxAsksFindScopedToMail() async throws {        let core = ScriptedCore([            CottonMethod.readFind: .ok(#"{"sections":[{"id":"email","words":"Email","count":3,"hits":[{"kind":"email","id":"m2","title":"A","record":{"table":"email_thread","id":"t2"}},{"kind":"email_thread","id":"t1","title":"B","record":{"table":"email_thread","id":"t1"}},{"kind":"email","id":"m3","title":"C","record":{"table":"email_thread","id":"t2"}}]}]}"#),            "records.list": .ok(#"{"records":[{"id":"t2","data":{"subject":"Two"}},{"id":"t1","data":{"subject":"One"}}],"next_page":null,"total":2}"#),        ])        let store = EmailRecords(core: core, definitions: [])        let page = try await store.list(table: "email_thread", project: nil, query: " trellis ", page: 0, where: [:])        XCTAssertEqual(page.records.map(\.id), ["t2", "t1"])        XCTAssertNil(page.next)        let calls = await core.calls        let find = try XCTUnwrap(calls.first { $0.method == CottonMethod.readFind })        let asked = try JSONDecoder().decode(JSONValue.self, from: Data(find.requestJSON.utf8))        XCTAssertEqual(asked.text("query"), "trellis")        XCTAssertEqual(asked.text("scope"), "mail")        let read = try XCTUnwrap(calls.last { $0.method == "records.list" })        let ids = try JSONDecoder().decode(JSONValue.self, from: Data(read.requestJSON.utf8))        XCTAssertEqual(ids["ids"], .array([.string("t2"), .string("t1")]))        XCTAssertNil(ids["query"], "the list's own subject match is not asked")        XCTAssertEqual(EmailRecords.threads([FindHit(kind: "email", id: "m9", title: "Synthetic")]), [], "an email hit standing for no thread names none")    }    // RULE: An imported thread is not binned or its sender blocked from its page (architect, r7: Bin is not an imported thread's act, Block sender is the sender page's); one already in the bin is brought back without a question.    func testAThreadsPageOffersNoBinAndARestoreThatDoesNotAsk() async throws {        let store = EmailRecords(core: ScriptedCore([:]), definitions: [])        let live = await store.pageActions(table: "email_thread", record: TableRecord(id: "t", values: ["binned": .bool(false), "sender_address": .text("e@example.invalid")]))        XCTAssertEqual(live.map(\.id), [])        let binned = await store.pageActions(table: "email_thread", record: TableRecord(id: "t", values: ["binned": .bool(true)]))        let restore = try XCTUnwrap(binned.first { $0.id == "bin" })        XCTAssertNil(restore.confirmation)    }}