SPB Git

Repository Public

NotificationTests.swift 13.9 KB 164 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailSystem/Tests/SPMailSystemTests/NotificationTests.swift3// Description: Notifications without the framework: payload → route (the exact payload shapes of sp-mail server/src/next/apns.ts), category and4// action mapping per platform, action → command, de-duplication between local and remote notifications, foreground presentation, badge maths.5import Foundation6import Testing7import SPMailCore8@testable import SPMailSystem910private let mb = "d4246e1d-0dd3-4922-943f-657ae17d2876"11/// The payload `buildPayload` produces for a new message (ARCHITECTURE-NEXT §4.2).12private func alert(kind: String = "new", category: String = "MAIL_NEW", email: String? = "Mabc", thread: String? = "Tdef", mailbox: String? = mb) -> [AnyHashable: Any] {13    var aps: [String: Any] = ["alert": ["title": "Alice Martin", "subtitle": "Budget 2027", "body": "Voici les chiffres…"], "badge": 4, "sound": "default", "category": category, "mutable-content": 1, "interruption-level": "active"]14    if let mailbox, let thread { aps["thread-id"] = "\(mailbox):\(thread)" }15    var p: [AnyHashable: Any] = ["aps": aps, "kind": kind]16    if let mailbox { p["mb"] = mailbox }17    if let email { p["email"] = email }18    if let thread { p["thread"] = thread }19    return p20}2122@Suite struct NotificationRoutingTests {23    @Test func payloadToRoute() {24        #expect(NotificationRoute(userInfo: alert()) == .conversation(mailboxId: mb, emailId: "Mabc", threadId: "Tdef"))25        #expect(NotificationRoute(userInfo: alert(kind: "snooze", category: "MAIL_REMINDER")) == .conversation(mailboxId: mb, emailId: "Mabc", threadId: "Tdef"))26        #expect(NotificationRoute(userInfo: alert(kind: "reminder", category: "MAIL_REMINDER", thread: nil)) == .conversation(mailboxId: mb, emailId: "Mabc", threadId: nil))27        // a mailbox without a message: its inbox; a test notification: the inbox; a silent badge update or an operator alert: nowhere28        #expect(NotificationRoute(userInfo: alert(email: nil, thread: nil)) == .inbox(mailboxId: mb))29        #expect(NotificationRoute(userInfo: ["aps": ["alert": ["title": "SP Mail", "body": "Test"], "category": "MAIL_ALERT"], "kind": "test"]) == .inbox(mailboxId: nil))30        #expect(NotificationRoute(userInfo: ["aps": ["content-available": 1, "badge": 3], "kind": "badge"]) == NotificationRoute.none)31        #expect(NotificationRoute(userInfo: ["aps": ["alert": ["title": "SP Mail", "body": "Disk"], "category": "MAIL_ALERT"], "kind": "alert"]) == NotificationRoute.none)32        // a kind this build does not know still opens the message it names; somebody else's payload opens nothing33        #expect(NotificationRoute(userInfo: alert(kind: "mention")) == .conversation(mailboxId: mb, emailId: "Mabc", threadId: "Tdef"))34        #expect(NotificationRoute(userInfo: ["foo": "bar"]) == NotificationRoute.none)35        // local notifications of the app (same keys) and of 1.x (`account` / `email`)36        #expect(NotificationRoute(userInfo: ["mb": mb, "email": "M1", "thread": "T1", "kind": "new"]) == .conversation(mailboxId: mb, emailId: "M1", threadId: "T1"))37        #expect(NotificationRoute(userInfo: ["account": mb, "email": "M1"]) == .conversation(mailboxId: mb, emailId: "M1", threadId: nil))38        #expect(NotificationRoute.conversation(mailboxId: mb, emailId: "M1", threadId: nil).deepLink == .conversation(mailboxId: mb, emailId: "M1", threadId: nil))39    }4041    @Test func categoriesMatchTheServerContract() {42        let ios = NotificationCategories.all(platform: .iOS), mac = NotificationCategories.all(platform: .macOS)43        #expect(ios.map(\.id) == ["MAIL_NEW", "MAIL_REMINDER", "MAIL_ALERT"] && mac.map(\.id) == ios.map(\.id))44        let new = ios[0].actions45        #expect(new.map(\.id) == [.reply, .markRead, .archive, .delete])46        // the quick reply has a text field and needs the device unlocked; delete is destructive and behind authentication, iOS only47        #expect(new[0].textInput != nil && new[0].authenticationRequired && !new[0].foreground)48        #expect(new[3].destructive && new[3].authenticationRequired)49        #expect(mac[0].actions.map(\.id) == [.reply, .markRead, .archive])50        #expect(ios[1].actions.map(\.id) == [.open, .snoozeHour, .done] && ios[1].actions[0].foreground && ios[2].actions.isEmpty)51        // without the app lock, read / archive run from the lock screen; with it, every action that touches mail waits for the device to be unlocked52        #expect(!new[1].authenticationRequired && !new[2].authenticationRequired)53        let locked = NotificationCategories.all(platform: .iOS, lockEnabled: true)54        #expect(locked[0].actions.allSatisfy(\.authenticationRequired) && locked[1].actions.filter { $0.id != .open }.allSatisfy(\.authenticationRequired))55        #expect(Set(NotificationActionID.allCases.map(\.rawValue)).count == NotificationActionID.allCases.count)56    }5758    @Test func actionsToCommands() {59        let now = Date(timeIntervalSince1970: 1_800_000_000)60        func cmd(_ action: String, _ info: [AnyHashable: Any] = alert(), text: String? = nil) -> NotificationCommand { .resolve(actionIdentifier: action, userInfo: info, replyText: text, now: now) }61        let route = NotificationRoute.conversation(mailboxId: mb, emailId: "Mabc", threadId: "Tdef")62        #expect(cmd(NotificationActionID.systemDefault) == .open(route) && cmd("MAIL_OPEN") == .open(route))63        #expect(cmd(NotificationActionID.systemDismiss) == NotificationCommand.none)64        #expect(cmd("MAIL_ARCHIVE") == .archive(mailboxId: mb, emailId: "Mabc") && cmd("MAIL_MARK_READ") == .markRead(mailboxId: mb, emailId: "Mabc") && cmd("MAIL_DELETE") == .delete(mailboxId: mb, emailId: "Mabc"))65        #expect(cmd("MAIL_REPLY", text: "  D’accord, merci.\n") == .reply(mailboxId: mb, emailId: "Mabc", text: "D’accord, merci."))66        #expect(cmd("MAIL_REPLY", text: "   ") == NotificationCommand.none && cmd("MAIL_REPLY") == NotificationCommand.none)67        #expect(cmd("MAIL_SNOOZE_1H") == .snooze(mailboxId: mb, emailId: "Mabc", until: now.addingTimeInterval(3600)))68        #expect(cmd("MAIL_DONE", alert(kind: "reminder", category: "MAIL_REMINDER")) == .done(mailboxId: mb, emailId: "Mabc", kind: .reminder))69        #expect(cmd("MAIL_DONE", alert(kind: "snooze", category: "MAIL_REMINDER")) == .done(mailboxId: mb, emailId: "Mabc", kind: .snooze))70        // an action on a notification that names no message does nothing; an unknown action does nothing71        #expect(cmd("MAIL_ARCHIVE", alert(email: nil, thread: nil)) == NotificationCommand.none && cmd("SOMETHING_ELSE") == NotificationCommand.none)72        #expect(cmd(NotificationActionID.systemDefault, ["aps": ["content-available": 1], "kind": "badge"]) == NotificationCommand.none)73        // what reveals or sends content waits for the app lock; the rest runs in the background74        #expect(cmd("MAIL_REPLY", text: "ok").needsUnlockedApp && cmd(NotificationActionID.systemDefault).needsUnlockedApp && !cmd("MAIL_ARCHIVE").needsUnlockedApp)75        #expect(cmd("MAIL_ARCHIVE").runsInBackground && !cmd(NotificationActionID.systemDefault).runsInBackground)76    }77}7879@Suite struct NotificationDedupTests {80    @Test func collapseIdentifierMatchesTheServer() {81        // server: sha256("new:<device>:<mailbox>:<email>").hex.slice(0, 40) — computed here with the same inputs82        let id = NotificationIdentity.collapseIdentifier(deviceId: "dev-1", mailboxId: mb, emailId: "Mabc")83        #expect(id.count == 40 && id.allSatisfy(\.isHexDigit))84        #expect(id != NotificationIdentity.collapseIdentifier(deviceId: "dev-2", mailboxId: mb, emailId: "Mabc") && id != NotificationIdentity.collapseIdentifier(deviceId: "dev-1", mailboxId: mb, emailId: "Mabd"))85        #expect(NotificationIdentity.localIdentifier(deviceId: "dev-1", mailboxId: mb, emailId: "Mabc") == id)86        #expect(NotificationIdentity.localIdentifier(deviceId: nil, mailboxId: mb, emailId: "Mabc") == "\(mb)/Mabc")87    }88    @Test func knownCollapseVector() {89        // printf 'new:D:M:E' | shasum -a 256 | cut -c1-4090        #expect(NotificationIdentity.collapseIdentifier(deviceId: "D", mailboxId: "M", emailId: "E") == "b993d4b819c3f1d3d2b8b59dcfc169b780079dda")91    }92    @Test func ledgerAnnouncesEachMessageOnce() throws {93        var ledger = NotificationLedger(capacity: 3)94        let t0 = Date(timeIntervalSince1970: 1_800_000_000)95        let first = ledger.record("a/1", at: t0), again = ledger.record("a/1", at: t0.addingTimeInterval(5))96        #expect(first && !again && ledger.contains("a/1"))97        let others = [ledger.record("a/2", at: t0.addingTimeInterval(1)), ledger.record("a/3", at: t0.addingTimeInterval(2)), ledger.record("a/4", at: t0.addingTimeInterval(3))]98        #expect(others == [true, true, true])99        // capacity: the oldest entry left100        #expect(!ledger.contains("a/1") && ledger.contains("a/2") && ledger.entries.count == 3)101        let restored = try JSONDecoder().decode(NotificationLedger.self, from: try JSONEncoder().encode(ledger))102        #expect(restored == ledger)103        ledger.prune(olderThan: 60, now: t0.addingTimeInterval(62))104        #expect(!ledger.contains("a/2") && ledger.contains("a/3") && ledger.contains("a/4"))105        ledger.forget("a/3")106        #expect(!ledger.contains("a/3"))107    }108    @Test func localAndRemoteNeverBothSpeak() {109        func local(push: Bool, announced: Bool = false, active: Bool = false, paused: Bool = false, enabled: Bool = true, muted: Bool = false, quiet: Bool = false) -> Bool {110            LocalNotificationPolicy.shouldPostLocal(enabled: enabled, paused: paused, appActive: active, pushPipelineActive: push, alreadyAnnounced: announced, mailboxMuted: muted, inQuietHours: quiet)111        }112        // the push pipeline announces: the app stays silent, whatever it synced by itself113        #expect(!local(push: true) && !local(push: true, announced: true))114        // no push (server not configured, device not registered): the app announces, once115        #expect(local(push: false) && !local(push: false, announced: true))116        #expect(!local(push: false, active: true) && !local(push: false, paused: true) && !local(push: false, enabled: false) && !local(push: false, muted: true) && !local(push: false, quiet: true))117        // the scenario end to end: a remote notification is recorded, the event stream then reports the same message118        var ledger = NotificationLedger()119        let key = NotificationIdentity.key(mailboxId: mb, emailId: "Mabc")120        let remoteFirst = ledger.record(key)121        #expect(remoteFirst && !local(push: false, announced: ledger.contains(key)))122        // and the other way round: announced locally first, the late push finds it in the ledger (the app then removes its local copy)123        var second = NotificationLedger()124        let localSpeaks = local(push: false, announced: second.contains(key)), recorded = second.record(key), latePush = second.record(key)125        #expect(localSpeaks && recorded && !latePush)126    }127    @Test func refreshIntervalRespectsPushAndPowerModes() {128        #expect(LocalNotificationPolicy.refreshInterval(pushPipelineActive: false, lowPower: false, constrainedNetwork: false) == 900)129        #expect(LocalNotificationPolicy.refreshInterval(pushPipelineActive: true, lowPower: false, constrainedNetwork: false) == 14400)130        // Low Power Mode / Low Data Mode: no refresh at all when push already brings the news, a rare one otherwise131        #expect(LocalNotificationPolicy.refreshInterval(pushPipelineActive: true, lowPower: true, constrainedNetwork: false) == nil)132        #expect(LocalNotificationPolicy.refreshInterval(pushPipelineActive: true, lowPower: false, constrainedNetwork: true) == nil)133        #expect(LocalNotificationPolicy.refreshInterval(pushPipelineActive: false, lowPower: true, constrainedNetwork: false) == 3600)134    }135    @Test func foregroundPresentationDoesNotDuplicateWhatIsOnScreen() {136        let route = NotificationRoute.conversation(mailboxId: mb, emailId: "Mabc", threadId: "Tdef"), key = "\(mb):Tdef"137        func decide(active: Bool = true, conversations: Set<String> = [], inboxes: Set<String> = [], paused: Bool = false) -> ForegroundPresentation {138            .decide(appActive: active, route: route, threadKey: key, visibleConversations: conversations, visibleInboxes: inboxes, paused: paused)139        }140        #expect(decide(conversations: [key]) == .silent)141        #expect(decide(inboxes: [mb]) == ForegroundPresentation(banner: false, list: true, sound: false, badge: true))142        #expect(decide() == .full && decide(conversations: ["\(mb):Tother"], inboxes: ["other"]) == .full)143        #expect(decide(active: false, conversations: [key]) == .full)144        #expect(decide(paused: true) == .silent)145    }146}147148@Suite struct BadgeMathTests {149    @Test func badgeFollowsTheServerRule() {150        let unread = ["a": 3, "b": 4, "c": 0]151        #expect(BadgeMath.badge(inboxUnread: unread, prefs: nil) == 7 && BadgeMath.badge(inboxUnread: unread, prefs: PushPrefs()) == 7)152        #expect(BadgeMath.badge(inboxUnread: unread, prefs: PushPrefs(mailboxes: ["b": false])) == 3)153        #expect(BadgeMath.badge(inboxUnread: unread, prefs: PushPrefs(mailboxes: ["b": true])) == 7)154        #expect(BadgeMath.badge(inboxUnread: unread, prefs: PushPrefs(badge: .none)) == 0 && BadgeMath.badge(inboxUnread: unread, prefs: PushPrefs(badge: .unknown)) == 0)155        #expect(BadgeMath.badge(inboxUnread: ["a": -2, "b": 1], prefs: nil) == 1 && BadgeMath.badge(inboxUnread: [:], prefs: nil) == 0)156    }157    @Test func serverNumberAndLocalReads() {158        #expect(BadgeMath.reconcile(server: 5, local: 3, localIsFresher: false) == 5)159        #expect(BadgeMath.reconcile(server: 5, local: 3, localIsFresher: true) == 3)160        #expect(BadgeMath.reconcile(server: nil, local: 3, localIsFresher: false) == 3 && BadgeMath.reconcile(server: -1, local: 0, localIsFresher: false) == 0)161        #expect(BadgeMath.afterLocalRead(current: 5, unreadMessagesHandled: 2) == 3 && BadgeMath.afterLocalRead(current: 1, unreadMessagesHandled: 4) == 0 && BadgeMath.afterLocalRead(current: 2, unreadMessagesHandled: -3) == 2)162    }163}164
Files main
Menu

Theme