210 lines · 12.9 KB · SwiftRaw
import CottonKitimport Foundationimport XCTest@testable import CottonUI#if os(iOS)/// An event's end and its people (assets/design/days CONTRACT §14, §15, §18 steps 1 to 3): read as the contract shapes/// them, and what the sheet sends back.final class DaysEventPartsTests: XCTestCase { private static let item = """ {"words":"Lunch with Priya","whose":"yours","day":"2026-11-22","time":"15:30","end":"16:30", "canChange":{"title":true,"time":true,"mark":true,"note":true,"alert":true}, "ends":{"title":"Ends","says":"16:30 · 1 hour","choices":[ {"key":"30m","minutes":30,"label":"30 min","on":false},{"key":"1h","minutes":60,"label":"1 hour","on":true}, {"key":"2h","minutes":120,"label":"2 hours","on":false},{"key":"pick","label":"Pick a time","on":false}, {"key":"none","label":"No end","on":false}]}, "people":{"title":"People","add":"Add people","canChange":true, "rows":[{"key":"email:priya@example.test","name":"Priya","detail":"priya@example.test","via":"google", "answer":"coming","answerWords":"Coming","organizer":false}], "blocked":{"line":"Connect Google Calendar to send invitations by email.", "connect":{"id":"google_connect","tool":"calendar","label":"Connect Google Calendar", "notice":{"title":"Before Google asks","body":"Days reads your calendar.","go":"Continue to Google","notNow":"Not now"}}}}} """ private func book(_ core: EventCore) -> CoreDaysBook { CoreDaysBook(core: core, clock: .fixed("2026-11-22", zone: TimeZone(identifier: "Europe/London")!)) } // RULE (§14, §15): a timed event's sheet reads its ENDS chips with the one that stands, and its people with // their answers; the blocked line carries section 13's Connect. func testAnEventReadsItsEndAndItsPeople() async throws { let item = try await book(EventCore(["days.item": Self.item])).item(table: "event", id: "e1", occurrenceAt: nil) XCTAssertEqual(item.ends?.says, "16:30 · 1 hour") XCTAssertEqual(item.ends?.standing, "1h") XCTAssertEqual(item.ends?.choices.map(\.key), ["30m", "1h", "2h", "pick", "none"]) XCTAssertEqual(item.people?.rows.first?.name, "Priya") XCTAssertEqual(item.people?.rows.first?.answerWords, "Coming") XCTAssertEqual(item.people?.blocked, "Connect Google Calendar to send invitations by email.") XCTAssertEqual(item.people?.connect?.id, "google_connect") } // RULE (§14): a chip sends its length, No end sends "none", Pick a time sends `end`; the chip that stood sends nothing. func testTheEndsRowSendsALengthNoEndOrAPickedTime() throws { let item = DaysRead.item(table: "event", id: "e1", try XCTUnwrap(JSONSerialization.jsonObject(with: Data(Self.item.utf8)) as? DaysRead.Object)) let ends = try XCTUnwrap(item.ends) XCTAssertEqual(DaysEndsRow.change(ends, chosen: "2h", picked: "", end: "16:30").length, .minutes(120)) XCTAssertEqual(DaysEndsRow.change(ends, chosen: "none", picked: "", end: "16:30").length, DaysLength.none) let picked = DaysEndsRow.change(ends, chosen: "pick", picked: "17:15", end: "16:30") XCTAssertNil(picked.length) XCTAssertEqual(picked.end, "17:15") XCTAssertNil(DaysEndsRow.change(ends, chosen: "1h", picked: "", end: "16:30").length, "the chip that stood sends nothing") XCTAssertNil(DaysEndsRow.change(ends, chosen: "pick", picked: "17", end: "16:30").end, "half a time is not sent") } // RULE (§14, §15): days.change carries the length, the end and the whole list of people as the chips stand. func testSavingSendsTheEndAndThePeople() async throws { let core = EventCore([:]) var change = DaysChange() change.length = DaysLength.none change.people = [DaysPerson(key: "email:priya@example.test", name: "Priya", email: "priya@example.test"), DaysPerson(key: "number:+15550100", name: "Akash", number: "+15550100")] try await book(core).change(table: "event", id: "e1", occurrenceAt: nil, change) let sent = await core.sent.first { $0.method == "days.change" } XCTAssertEqual(sent?.body["length"] as? String, "none") let people = sent?.body["people"] as? [[String: Any]] XCTAssertEqual(people?.map { $0["key"] as? String }, ["email:priya@example.test", "number:+15550100"]) XCTAssertEqual(people?.last?["number"] as? String, "+15550100") } // RULE (§15): Add people asks the core with the words and the event; Tell asks with the chips and reads its lines. func testFindingAndTellingAskTheCore() async throws { let core = EventCore([ "days.people_find": #"{"rows":[{"key":"cotton:akash","name":"Akash","detail":"+15550100","via":"cotton","number":"+15550100"}]}"#, "days.tell": #"{"lines":["Priya gets an invitation by email from Google Calendar.","Akash gets it in Days."],"blocked":null}"#, ]) let found = try await book(core).peopleFind("ak", eventId: "e1") XCTAssertEqual(found.map(\.name), ["Akash"]) XCTAssertEqual(found.first?.via, "cotton") let told = try await book(core).tell(eventId: "e1", people: found) XCTAssertEqual(told.lines.last, "Akash gets it in Days.") let sent = await core.sent XCTAssertEqual(sent.first { $0.method == "days.people_find" }?.body["words"] as? String, "ak") XCTAssertEqual(sent.first { $0.method == "days.people_find" }?.body["eventId"] as? String, "e1") let tell = sent.first { $0.method == "days.tell" } XCTAssertEqual(tell?.body["table"] as? String, "event") XCTAssertEqual((tell?.body["people"] as? [[String: Any]])?.first?["key"] as? String, "cotton:akash") } // RULE (§17, §15): an invitation received reads who sent it and the three answers; Delete reads who it tells. func testAnInvitationAndWhoDeleteTells() throws { let item = DaysRead.item(table: "event", id: "e2", [ "words": "Dinner", "canChange": ["time": false], "invitation": ["says": "Rose invited you", "answer": "tentative", "choices": [["key": "accepted", "label": "Coming"], ["key": "tentative", "label": "Maybe"], ["key": "declined", "label": "Not coming"]]], "deleteTells": "Priya and Akash are told it is off.", ]) XCTAssertEqual(item.invitation?.says, "Rose invited you") XCTAssertEqual(item.invitation?.answer, "tentative") XCTAssertEqual(item.invitation?.choices.map(\.label), ["Coming", "Maybe", "Not coming"]) XCTAssertEqual(item.deleteTells, "Priya and Akash are told it is off.") XCTAssertNil(DaysRead.item(table: "event", id: "e3", ["words": "Dentist"]).invitation) } // RULE (§15, §16): days.change says back what was said, what people were told, and whether something waits. func testAChangeSaysWhatWaits() async throws { let core = EventCore(["days.change": #"{"tells":["Priya gets an invitation by email from Google Calendar."],"google":"waiting"}"#]) var change = DaysChange() change.title = .some("Lunch") let answer = try await book(core).changed(table: "event", id: "e1", occurrenceAt: nil, change) XCTAssertTrue(answer.waiting) XCTAssertEqual(answer.tells.count, 1) XCTAssertNil(answer.said) let nothing = try await book(core).changed(table: "event", id: "e1", occurrenceAt: nil, DaysChange()) XCTAssertEqual(nothing, DaysChanged(), "nothing changed asks nothing") } // RULE (§16): google_needs_write is read as the core's message with section 13's Connect; nothing else is. func testGoogleNeedsWriteKeepsTheSheetWithConnect() async throws { let core = EventCore(["days.change": #"!{"code":"google_needs_write","message":"To save changes to Google Calendar, Days needs your permission once more.","details":{"connect":{"id":"google_connect","tool":"calendar","label":"Connect Google Calendar","notice":{"title":"t","body":"b","go":"Continue to Google","notNow":"Not now"}}}}"#]) var change = DaysChange() change.title = .some("Massage") do { _ = try await book(core).changed(table: "event", id: "e1", occurrenceAt: nil, change) XCTFail("the change was refused") } catch { let refused = try XCTUnwrap(DaysNeedsWrite.of(error)) XCTAssertEqual(refused.message, "To save changes to Google Calendar, Days needs your permission once more.") XCTAssertEqual(refused.connect?.id, "google_connect") } XCTAssertNil(DaysNeedsWrite.of(CottonCallError(code: "write_refused", message: "no"))) } // RULE (§16, §17): a send pass asks Google first, then people on Cotton; their lines together, Google's ask first. func testSendingAsksGoogleThenInvitations() async throws { let core = EventCore([ "days.send_to_google": #"{"sent":1,"said":["Google Calendar changed “Massage” first, so Days kept Google's."],"reconnect":{"line":"Connect again.","connect":{"id":"google_connect","tool":"calendar","label":"Connect","notice":{"title":"t","body":"b","go":"g","notNow":"n"}}},"more":false}"#, "days.invitations": #"{"sent":0,"said":["Rose invited you to “Dinner” on Fri 28 Nov."]}"#, ]) let sent = try await book(core).send() XCTAssertEqual(sent.said.count, 2) XCTAssertEqual(sent.said.last, "Rose invited you to “Dinner” on Fri 28 Nov.") XCTAssertEqual(sent.reconnect, "Connect again.") XCTAssertEqual(sent.connect?.label, "Connect") let asked = await core.sent.map(\.method) XCTAssertEqual(asked, ["days.send_to_google", "days.invitations"]) try await book(core).answer("e2", "accepted") let answer = await core.sent.last XCTAssertEqual(answer?.method, "days.answer") XCTAssertEqual(answer?.body["id"] as? String, "e2") XCTAssertEqual(answer?.body["answer"] as? String, "accepted") } // RULE (§16, §17): what the pass says is said at Days' foot, Google's ask with Connect as its act; after a sync it // is not asked again within the minute. @MainActor func testTheModelSaysWhatThePassSaid() async throws { let core = EventCore([ "days.send_to_google": #"{"sent":0,"said":[],"reconnect":{"line":"Days needs your permission once more.","connect":{"id":"google_connect","tool":"calendar","label":"Connect","notice":{"title":"t","body":"b","go":"g","notNow":"n"}}}}"#, "days.invitations": #"{"sent":0,"said":[]}"#, ]) let model = DaysModel(book: book(core), core: core, clock: .fixed("2026-11-22")) await model.sendAway() XCTAssertEqual(model.said, "Days needs your permission once more.") XCTAssertEqual(model.actWords, "Connect") await model.undo?() XCTAssertEqual(model.noticing?.id, "google_connect", "Connect opens the notice first") await model.sendAway(unlessWithin: 60) let passes = await core.sent.filter { $0.method == "days.send_to_google" }.count XCTAssertEqual(passes, 1, "not again within the minute") } // RULE (§16): Settings reads "Also keep my Days events in Google Calendar" while an account stands. func testSettingsReadTheKeepSwitch() throws { let google = try JSONDecoder().decode(DaysGoogle.self, from: Data(#"{"line":"l","accounts":[],"keep":{"label":"Also keep my Days events in Google Calendar","line":"Off.","on":false}}"#.utf8)) XCTAssertEqual(google.keep?.label, "Also keep my Days events in Google Calendar") XCTAssertEqual(google.keep?.on, false) XCTAssertNil(try JSONDecoder().decode(DaysGoogle.self, from: Data(#"{"line":"l"}"#.utf8)).keep) } // RULE: a core that does not answer ends or people yet draws neither row. func testAnOlderCoreDrawsNeitherRow() throws { let item = DaysRead.item(table: "event", id: "e1", ["words": "Dentist", "canChange": ["time": true]]) XCTAssertNil(item.ends) XCTAssertNil(item.people) }}/// A core answering the event methods (every other with an empty object), saying what it was asked.private actor EventCore: CottonCalling { struct Sent: @unchecked Sendable { let method: String let body: [String: Any] } private let answers: [String: String] private(set) var sent: [Sent] = [] init(_ answers: [String: String]) { self.answers = answers } func callRaw(_ method: String, requestJSON: String) async throws -> String { sent.append(Sent(method: method, body: (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8)) as? [String: Any]) ?? [:])) // An answer starting "!" is the core's refusal. if let answer = answers[method], answer.hasPrefix("!") { return #"{"ok":false,"error":\#(answer.dropFirst())}"# } return #"{"ok":true,"data":\#(answers[method] ?? "{}")}"# } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {}}#endif