Cotton code
188 lines · 7.9 KB · SwiftRaw
// This device's notification preferences and the one ask.//// Two groups of cases:////   • the stored preferences — the revive hook, which is the ONE entry point//     stored data enters through, so anything it lets past is live data to new//     code. In Swift that hook is `CottonKit.NotificationPrefs.init(stored:)`,//     and these tests drive it with `JSONValue` literals;//   • the ask — the predicate deciding when to spend iOS's one prompt, and//     the broadcast every ask makes.//// The switches a person meets are this device's page's columns now// (`DeviceHere`), and `DeviceHereTests` drives them.import CottonKitimport XCTest@testable import CottonKit@testable import CottonUI@MainActorfinal class NotificationsTests: XCTestCase {    /// A store over its own `UserDefaults` suite, so the two tests that need    /// the REAL write path (JSON out, generous decoder back in) get it without    /// two tests in one bundle sharing process-wide state.    private func defaultsStore() -> DefaultsNotificationPrefsStore {        DefaultsNotificationPrefsStore(            defaults: UserDefaults(suiteName: "cotton.tests.notifprefs.\(UUID().uuidString)")                ?? .standard        )    }    // ── The persisted switches (prefs.test.ts) ────────────────────────────    func testTheStorageKeyIsTheOneTheSpecFixed() {        // The key is declared in `StandingKey` — the list `NoStandingTests`        // reads — and `NotificationPrefs.storageKey` is that declaration's        // rawValue. Both are asserted, because the literal is what the        // previous build wrote and the tie between them is what keeps one key.        XCTAssertEqual(StandingKey.notificationPrefs.rawValue, "@cotton:notifprefs")        XCTAssertEqual(NotificationPrefs.storageKey, "@cotton:notifprefs")    }    func testEveryMalformedValueFallsBackToTheDefaults() {        // An array is an object in JavaScript, so it took the partial path and        // supplied nothing — which had to land on the defaults just the same.        // `NSNull()` from the raw-`Any` era is `.null` here, and the untyped        // array is `.array([])`: `JSONValue` names what the old `Any` only        // implied, so these are the same five cases with their types spelled.        let malformed: [JSONValue?] = [nil, .string("off"), .number(42), .array([]), .null]        for raw in malformed {            XCTAssertEqual(NotificationPrefs(stored: raw), NotificationPrefs.defaults)        }    }    func testACompleteStoredRecordIsKept() {        let stored = NotificationPrefs(            enabled: false,            categories: [                .reminders: false, .events: true, .birthdays: false, .alarms: true,            ],            askedAt: "2026-08-11T02:00:00.000Z"        )        let raw: JSONValue = .object([            "enabled": .bool(false),            "categories": .object([                "reminders": .bool(false), "events": .bool(true), "birthdays": .bool(false),                "alarms": .bool(true),            ]),            "askedAt": .string("2026-08-11T02:00:00.000Z"),        ])        XCTAssertEqual(NotificationPrefs(stored: raw), stored)    }    func testNonBooleanSwitchesAreRefusedRatherThanMadeTruthy() {        let raw: JSONValue = .object([            "enabled": .string("yes"),            "categories": .object(["reminders": .number(1), "events": .null]),        ])        let prefs = NotificationPrefs(stored: raw)        XCTAssertTrue(prefs.enabled)        XCTAssertEqual(prefs.categories[.reminders], true)        XCTAssertEqual(prefs.categories[.events], true)    }    func testANonStringAskedAtIsDroppedSoACorruptRecordCanStillBeAsked() {        let raw: JSONValue = .object(["askedAt": .number(1_723_334_400_000)])        XCTAssertNil(NotificationPrefs(stored: raw).askedAt)    }    func testTheDefaultsHaveEveryRecordShapedCategoryOnAndNobodyAskedYet() {        // On does not mean notifications happen: the OS permission is the real        // gate, and Cotton never asks for it at boot.        let defaults = NotificationPrefs.defaults        XCTAssertTrue(defaults.enabled)        XCTAssertEqual(defaults.categories[.reminders], true)        XCTAssertEqual(defaults.categories[.events], true)        XCTAssertEqual(defaults.categories[.birthdays], true)        XCTAssertEqual(defaults.categories[.alarms], true)        XCTAssertNil(defaults.askedAt)    }    func testAWrittenRecordReadsBackAsItself() {        // The write path is this port's own — the TypeScript's atom serialized        // for it — so it owes a round trip the TypeScript did not need. The        // REAL store is the one that round-trips (JSON out, generous decoder        // back in); the in-memory double holds the struct and would prove        // nothing about the format.        let store = defaultsStore()        let prefs = NotificationPrefs(            enabled: false,            categories: [                .reminders: true, .events: false, .birthdays: true, .alarms: false,            ],            askedAt: "2026-08-11T02:00:00.000Z"        )        store.write(prefs)        XCTAssertEqual(store.read(), prefs)    }    func testAnUnwrittenStoreReadsAsTheDefaults() {        XCTAssertEqual(defaultsStore().read(), NotificationPrefs.defaults)        // And so does one holding something that is not JSON at all.        let spoiled = UserDefaults(suiteName: "cotton.tests.notifprefs.\(UUID().uuidString)")        spoiled?.set("{not json", forKey: NotificationPrefs.storageKey)        XCTAssertEqual(            DefaultsNotificationPrefsStore(defaults: spoiled ?? .standard).read(),            NotificationPrefs.defaults        )    }    // ── The broadcast ─────────────────────────────────────────────────────    //    // Restored after the merge deleted it with 4h's permission file. It is not    // decoration: `/settings#notifications` is the one screen whose subject IS    // the permission, and everything a grant should trigger — APNs    // registration, the push-token hand-off, the reminder pass — lives behind    // `NotificationsModel.refresh()`, whose only other caller is the scene    // going `.active`. Without the broadcast, granting here schedules nothing    // until the app is backgrounded and brought back, which is the failure the    // previous permission file named in as many words.    func testAnAskTellsSubscribersOncePerAskWhateverTheAnswer() async {        let changes = NotificationPermissionChanges()        let authority = ScriptedNotificationSettingsAuthority([.granted, .denied], changes: changes)        let heard = NotificationsTestCounter()        let stop = changes.subscribe { heard.bump() }        _ = await authority.ask()        XCTAssertEqual(heard.count, 1)        // A refusal is a change too: the person answered.        let answer = await authority.ask()        XCTAssertEqual(answer, .denied)        XCTAssertEqual(heard.count, 2)        stop()    }    func testASubscriberThatUnsubscribedIsNotToldAgain() async {        let changes = NotificationPermissionChanges()        let authority = ScriptedNotificationSettingsAuthority([.undetermined], changes: changes)        let heard = NotificationsTestCounter()        changes.subscribe { heard.bump() }()        _ = await authority.ask()        XCTAssertEqual(heard.count, 0)    }}/// A counter a `@Sendable` closure may bump. `XCTestExpectation` counts too, but/// a fulfilment count that is WRONG fails as a timeout rather than as a number.final class NotificationsTestCounter: @unchecked Sendable {    private let lock = NSLock()    private var value = 0    func bump() {        lock.lock()        value += 1        lock.unlock()    }    var count: Int {        lock.lock()        defer { lock.unlock() }        return value    }}