Cotton code
285 lines · 13.9 KB · SwiftRaw
// Forgetting the token, the receipts, the prefs, and the one inline ask.//// "The ask broadcasts once; unsubscribe works" does not come over as written:// the permission-change listener list existed because the old view layer needed// one, and here the permission is an `@Observable`// property that SwiftUI reads directly. What it PROTECTED — one prompt, and// every reader seeing the answer — is the two cases at the bottom of this file.import CottonKitimport CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class PushTokenTests: XCTestCase {    private func core() -> ScriptedCore {        ScriptedCore([            CottonMethod.remindersReconcile: .ok(                #"{"schedule":[],"cancel":[],"noop":true}"#            ),        ])    }    private func model(        core: ScriptedCore,        bridge: NotificationBridge,        permission: NotificationPermission = .granted,        answers: NotificationPermission? = nil,        prefs: NotificationPrefs = .defaults,        facts: ScriptedFacts = ScriptedFacts(),        authority: ScriptedAuthority? = nil,        delivered: @escaping @Sendable () async -> [PushReceipt] = { [] }    ) -> NotificationsModel {        NotificationsModel(            core: core,            centre: RecordingCentre(),            authority: authority ?? ScriptedAuthority(state: permission, answers: answers),            prefsStore: InMemoryNotificationPrefsStore(prefs),            facts: facts,            bridge: bridge,            settle: .zero,            timeZone: { "Asia/Kolkata" },            now: { Date(timeIntervalSince1970: 1_789_000_000) },            delivered: delivered        )    }    // ── Receipts ──────────────────────────────────────────────────────────    /// RULE: Only a server push is owed a receipt, named by the payload's `notificationId` wherever the rail nests it — a local reminder carries none and is never told to the Mac as a push that arrived.    func testOnlyAServerPushHasAReceipt() {        let at = Date(timeIntervalSince1970: 1_789_000_000)        let nested: JSONValue = .object(["body": .object(["type": .string("test_push"), "notificationId": .string("p-1")])])        XCTAssertEqual(PushReceipt.of(userInfo: nested, date: at, how: .shown)?.pushId, "p-1")        let flat: JSONValue = .object(["notificationId": .string("p-2")])        XCTAssertEqual(PushReceipt.of(userInfo: flat, date: at, how: .opened)?.pushId, "p-2")        let reminder: JSONValue = .object(["kind": .string("todo"), "id": .string("t1")])        XCTAssertNil(PushReceipt.of(userInfo: reminder, date: at, how: .shown))    }    /// RULE: A push this phone met — shown while open, tapped, or found in Notification Centre — is told to the serving Mac as `device.pushAck`, once per push, and one told before the model listened is told when it does; a push counts as reaching the owner only on that receipt (architect, 12 Oct 2026).    func testEveryPushThePhoneMetIsToldOnce() async throws {        let core = core()        await core.answer(CottonMethod.devicePushAck, .ok(#"{"recorded":true}"#))        let bridge = NotificationBridge()        let at = Date(timeIntervalSince1970: 1_789_000_000)        bridge.met(PushReceipt(pushId: "shown-early", receivedAt: CottonDate.format(at), how: .shown))        let model = model(            core: core, bridge: bridge,            delivered: { [PushReceipt(pushId: "away", receivedAt: CottonDate.format(at), how: .delivered)] })        await model.start(taps: PendingTaps())        bridge.met(PushReceipt(pushId: "away", receivedAt: CottonDate.format(at), how: .opened))        for _ in 0..<50 { await Task.yield() }        await model.foreground()        let told = await acks(in: core)        XCTAssertEqual(told.sorted(), ["away", "shown-early"], "each push once, however many ways it was met")        let bodies = await core.calls.filter { $0.method == CottonMethod.devicePushAck }.compactMap { call in            try? JSONDecoder().decode(JSONValue.self, from: Data(call.requestJSON.utf8))        }        let early = try XCTUnwrap(bodies.first { $0["pushId"]?.string == "shown-early" })        XCTAssertEqual(early["how"]?.string, "shown")        XCTAssertEqual(early["receivedAt"]?.string, CottonDate.format(at))    }    /// RULE: A receipt the Mac could not take blocks nothing and is told again at the next foreground, from Notification Centre.    func testAReceiptThatFailedIsToldAgain() async {        let core = core()        await core.answer(CottonMethod.devicePushAck, .refuse(code: "unreachable", message: "no Mac"))        let receipt = PushReceipt(pushId: "p-9", receivedAt: "2026-10-12T01:09:22.000Z", how: .delivered)        let model = model(core: core, bridge: NotificationBridge(), delivered: { [receipt] })        await model.start(taps: PendingTaps())        await model.foreground()        let told = await acks(in: core)        XCTAssertEqual(told, ["p-9", "p-9"])    }    // ── Forgetting ────────────────────────────────────────────────────────    func testForgettingNamesTheSameDeviceIdAndNeverThrows() async throws {        let core = ScriptedCore([CottonMethod.pushForget: .ok(#"{"forgotten":true}"#)])        let model = model(core: core, bridge: NotificationBridge())        let answer = await model.forgetToken()        XCTAssertTrue(answer.forgotten)        let sent = await sentBody(CottonMethod.pushForget, in: core)        let body = try XCTUnwrap(sent)        XCTAssertEqual(body["deviceId"]?.string, "vendor-1")    }    func testForgettingAnswersEitherWayEvenWhenTheBoundaryRefuses() async {        // A person handing back a phone must never be trapped by a        // deregistration that could not reach the server.        let core = ScriptedCore([            CottonMethod.pushForget: .refuse(code: "unreachable", message: "no")        ])        let model = model(core: core, bridge: NotificationBridge())        let answer = await model.forgetToken()        XCTAssertEqual(answer, PushForgotten(forgotten: false, reason: "unreachable"))    }    func testWithNoVendorIdForgettingStillAnswers() async {        let core = ScriptedCore([:])        let model = model(core: core, bridge: NotificationBridge(), facts: ScriptedFacts(facts: nil))        let answer = await model.forgetToken()        XCTAssertEqual(answer, PushForgotten(forgotten: false, reason: "no_device_id"))    }    func testLeavingForgetsTheToken() async {        // Both paths that stop this phone being a device of that server's run        // it — the deliberate leave here, and a revocation being noticed.        let core = ScriptedCore([            CottonMethod.pushForget: .ok(#"{"forgotten":true}"#),            CottonMethod.readBoot: .ok(#"{"paired":false,"stage":"pairing"}"#),        ])        let notifications = model(core: core, bridge: NotificationBridge())        let boot = BootModel(core: core)        boot.beforeLeaving = { _ = await notifications.forgetToken() }        await boot.leave()        let asked = await core.methodsCalled()        XCTAssertTrue(asked.contains(CottonMethod.pushForget), "the note goes with the leave")    }    // ── The one ask ───────────────────────────────────────────────────────    /// A grant that happened SOMEWHERE ELSE still reaches APNs registration.    ///    /// This is the half of the permission-change broadcast that matters and the    /// one a refactor can silently delete: `/settings#notifications` is the one    /// screen whose subject IS the permission, and everything a grant should    /// trigger — APNs registration and the reminder pass — lives    /// behind this model's `refresh()`, whose only other caller is the scene    /// going `.active`. Drop the `subscribe` in `start(taps:)` and a person who    /// taps Allow on that screen gets nothing scheduled until they background    /// the app and come back; send a message first and the reply earns no push.    /// The previous permission file named that failure in as many words, which    /// is why the broadcast exists at all.    ///    /// Driven through `NotificationPermissionChanges.shared` because that is    /// what the model subscribes to and what `SystemNotificationAuthority.ask()`    /// fires — the same instance the settings screen's Allow button reaches.    func testAGrantMadeOnAnotherScreenReachesAPNsRegistration() async {        let authority = ScriptedAuthority(state: .granted)        let core = core()        let model = model(core: core, bridge: NotificationBridge(), authority: authority)        await model.start(taps: PendingTaps())        let afterStart = authority.registeredForRemote        NotificationPermissionChanges.shared.notify()        // The subscriber hops to the MainActor, so let that hop happen. No        // clock: a yield, not a sleep.        for _ in 0..<50 where authority.registeredForRemote == afterStart {            await Task.yield()        }        XCTAssertGreaterThan(            authority.registeredForRemote,            afterStart,            "a permission granted outside this model told it nothing — APNs registration and the reminder pass would wait for the next foreground"        )    }    // ── The prefs ─────────────────────────────────────────────────────────    func testTheDefaultsAreAllOn() {        let defaults = NotificationPrefs.defaults        XCTAssertTrue(defaults.enabled)        XCTAssertTrue(defaults.enabled(.todo))        XCTAssertTrue(defaults.enabled(.event))        XCTAssertTrue(defaults.enabled(.birthday))        XCTAssertTrue(defaults.enabled(.alarm))        XCTAssertNil(defaults.askedAt)    }    func testStoredPreferencesAreReadSuspiciously() {        // Malformed, partial, or from an older shape: the parts it cannot        // supply take their defaults.        XCTAssertEqual(NotificationPrefs(stored: nil), .defaults)        XCTAssertEqual(NotificationPrefs(stored: .string("yes")), .defaults)        XCTAssertEqual(NotificationPrefs(stored: .object([:])), .defaults)        // A stored `"yes"` is not `true`.        XCTAssertTrue(NotificationPrefs(stored: .object(["enabled": .string("yes")])).enabled)        // Nothing asks about mood on a schedule (owner, 11 Oct 2026): an older        // build's `moodHour` and `mood` switch are not read.        XCTAssertEqual(            NotificationPrefs(stored: .object(["moodHour": .number(7), "categories": .object(["mood": .bool(true)])])),            .defaults)        // A category added later takes ITS default for a record that predates        // it, exactly as a fresh install gets it.        let partial = NotificationPrefs(            stored: .object(["categories": .object(["reminders": .bool(false)])])        )        XCTAssertFalse(partial.enabled(.todo))        XCTAssertTrue(partial.enabled(.event))    }    func testAMissingCategoryKeyIsOffRatherThanOn() {        // Failing closed costs a reminder nobody asked for; failing open sends        // one somebody declined.        let prefs = NotificationPrefs(enabled: true, categories: [:])        for kind in NotificationKind.allCases {            XCTAssertFalse(prefs.enabled(kind), kind.rawValue)        }    }    func testTheMasterSwitchBeatsEveryCategory() {        var prefs = NotificationPrefs.defaults        prefs.enabled = false        for kind in NotificationKind.allCases {            XCTAssertFalse(prefs.enabled(kind), kind.rawValue)        }    }    func testEveryKindHasACategoryAndTheMapIsTotal() {        for kind in NotificationKind.allCases {            XCTAssertTrue(                NotificationCategory.allCases.contains(kind.category),                "\(kind.rawValue) is governed by a category that does not exist"            )        }        XCTAssertEqual(NotificationKind.allCases.map(\.rawValue), [            "todo", "event", "birthday", "alarm",        ])        XCTAssertEqual(NotificationCategory.allCases.map(\.rawValue), [            "reminders", "events", "birthdays", "alarms",        ])    }    func testAStoredRecordSurvivesARoundTrip() {        let store = DefaultsNotificationPrefsStore(            defaults: UserDefaults(suiteName: "cotton-prefs-\(UUID().uuidString)")!        )        var prefs = NotificationPrefs.defaults        prefs.categories[.birthdays] = false        prefs.askedAt = "2026-09-10T12:00:00Z"        store.write(prefs)        XCTAssertEqual(store.read(), prefs)    }    func testAnEmptyStoreAnswersTheDefaults() {        let store = DefaultsNotificationPrefsStore(            defaults: UserDefaults(suiteName: "cotton-prefs-\(UUID().uuidString)")!        )        XCTAssertEqual(store.read(), .defaults)    }    /// One method's request, DECODED rather than matched as a substring.    ///    /// A `contains("\"timezone\":\"Asia/Kolkata\"")` is an assertion about how    /// `JSONEncoder` spells things — key order, whitespace, whether a forward    /// slash comes back escaped — and none of that is the behaviour under test.    /// Decoding asserts what was SENT.    private func sentBody(_ method: String, in core: ScriptedCore) async -> JSONValue? {        let calls = await core.calls        guard let json = calls.first(where: { $0.method == method })?.requestJSON else {            return nil        }        return try? JSONDecoder().decode(JSONValue.self, from: Data(json.utf8))    }    private func acks(in core: ScriptedCore) async -> [String] {        await core.calls.filter { $0.method == CottonMethod.devicePushAck }.compactMap { call in            (try? JSONDecoder().decode(JSONValue.self, from: Data(call.requestJSON.utf8)))?["pushId"]?.string        }    }}