Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailCore/Tests/SPMailCoreTests/NextHelperTests.swift3// Description: Unit tests of the pure Next helpers: missing-attachment detection (French and English, quoted text and signatures ignored), snooze4// presets with fixed calendars and time zones (midnight, weekends, daylight-saving changes), query chips, label palette, avatars, APNs payloads.5import Foundation6import Testing7@testable import SPMailCore89private func cal(_ tz: String = "America/Toronto") -> Calendar {10 var c = Calendar(identifier: .gregorian)11 c.timeZone = TimeZone(identifier: tz)!12 c.locale = Locale(identifier: "fr_CA")13 return c14}15/// A wall-clock instant in the given zone.16private func at(_ y: Int, _ mo: Int, _ d: Int, _ h: Int, _ mi: Int = 0, _ s: Int = 0, tz: String = "America/Toronto") -> Date {17 cal(tz).date(from: DateComponents(year: y, month: mo, day: d, hour: h, minute: mi, second: s))!18}19private func utc(_ y: Int, _ mo: Int, _ d: Int, _ h: Int, _ mi: Int = 0) -> Date { at(y, mo, d, h, mi, tz: "UTC") }2021@Suite struct MissingAttachmentTests {22 @Test func frenchAndEnglishPhrasesAreFound() {23 let positives = [24 "Bonjour, vous trouverez ci-joint le devis.", "Voir la pièce jointe.", "Le contrat est en pièce jointe", "Les PIÈCES JOINTES suivent", "Ci-jointes les photos", "Je vous joins le rapport.",25 "Document en annexe.", "Le fichier joint contient tout", "Voir PJ", "cf. p.j. pour le détail", "J’ai joint la facture",26 "Please see the attached file.", "I've attached the report", "The attachment is a PDF", "Enclosed you will find the form", "Attaching the slides now", "Please find the invoice below",27 ]28 for p in positives { #expect(!MissingAttachmentDetector.mentions(text: p).isEmpty, "\(p)") }29 #expect(MissingAttachmentDetector.mentions(subject: "Devis en pièce jointe", text: "Bonjour") == ["piece jointe", "en piece jointe"])30 #expect(MissingAttachmentDetector.shouldWarn(subject: "", text: "Voici le devis ci-joint.", attachmentCount: 0))31 #expect(!MissingAttachmentDetector.shouldWarn(subject: "", text: "Voici le devis ci-joint.", attachmentCount: 1))32 }3334 @Test func ordinaryTextAndLookalikesAreNotFlagged() {35 let negatives = [36 "Bonjour, on se voit demain à 10 h.", "Thanks, talk soon.", "Je rejoins l'équipe lundi", "Il est très attachant", "unattached strings", "Le conjoint de Marie", "Les pjx sont des fichiers", "", "Merci pour la jointure",37 "I am attaché to the embassy",38 ]39 for n in negatives { #expect(MissingAttachmentDetector.mentions(text: n).isEmpty, "\(n)") }40 #expect(!MissingAttachmentDetector.shouldWarn(text: "Bonjour", attachmentCount: 0))41 }4243 @Test func quotedTextAndSignaturesAreIgnored() {44 let reply = """45 Parfait, merci !4647 Le 18 nov. 2026 à 10 h 12, Jeanne Tremblay <jeanne@example.com> a écrit :48 > Vous trouverez ci-joint le devis.49 > See attached.50 """51 #expect(MissingAttachmentDetector.mentions(text: reply).isEmpty && MissingAttachmentDetector.authoredText(reply).trimmingCharacters(in: .whitespacesAndNewlines) == "Parfait, merci !")52 let english = "Sounds good.\n\nOn Wed, Nov 18, 2026 at 10:12 AM Jeanne Tremblay <jeanne@example.com> wrote:\n> Please find attached the quote.\n"53 #expect(MissingAttachmentDetector.mentions(text: english).isEmpty)54 let wrapped = "OK.\n\nOn Wed, Nov 18, 2026 at 10:12 AM Jeanne Tremblay\n<jeanne@example.com> wrote:\nthe attachment is there\n"55 #expect(MissingAttachmentDetector.mentions(text: wrapped).isEmpty)56 let interleaved = "> As attached before\nNon, rien à ajouter.\n> see attachment\nMerci"57 #expect(MissingAttachmentDetector.mentions(text: interleaved).isEmpty && MissingAttachmentDetector.authoredText(interleaved) == "Non, rien à ajouter.\nMerci")58 let signature = "À demain.\n-- \nSimon-Pierre\nPièce jointe : aucune\n"59 #expect(MissingAttachmentDetector.mentions(text: signature).isEmpty)60 let outlook = "Reçu.\n\nDe : Jeanne Tremblay\nEnvoyé : 18 novembre 2026 10:12\nÀ : SP\nObjet : Devis\n\nCi-joint le devis."61 #expect(MissingAttachmentDetector.mentions(text: outlook).isEmpty)62 let forwarded = "Pour info.\n\n---------- Forwarded message ---------\nFrom: x\nSee attached."63 #expect(MissingAttachmentDetector.mentions(text: forwarded).isEmpty)64 // what the person wrote above the quote still counts65 let own = "Je vous envoie le devis en pièce jointe.\n\nLe 18 nov. 2026, Jeanne <j@example.com> a écrit :\n> merci"66 #expect(MissingAttachmentDetector.mentions(text: own) == ["piece jointe", "en piece jointe"])67 // a sentence that merely starts with "Le" or "On" is not a reply header68 #expect(!MissingAttachmentDetector.mentions(text: "Le devis est en annexe.\nBonne journée").isEmpty)69 #expect(!MissingAttachmentDetector.mentions(text: "On Monday I will send it.\nSee attached.").isEmpty)70 }7172 @Test func theComposerMessageCountsOnlyRealAttachments() {73 var m = OutgoingMessage(from: EmailAddress(email: "a@stg.spboucher.ai"), subject: "Devis", text: "Ci-joint le devis.")74 #expect(MissingAttachmentDetector.shouldWarn(m))75 m.attachments = [OutgoingAttachment(name: "logo.png", type: "image/png", size: 10, cid: "logo", inline: true)]76 #expect(MissingAttachmentDetector.shouldWarn(m))77 m.attachments.append(OutgoingAttachment(name: "devis.pdf", type: "application/pdf", size: 10))78 #expect(!MissingAttachmentDetector.shouldWarn(m))79 // the quoted original of a reply is kept apart by the composer and never scanned80 var reply = OutgoingMessage(from: EmailAddress(email: "a@stg.spboucher.ai"), subject: "Re: Devis", text: "Merci !")81 reply.quotedText = "> ci-joint le devis"82 #expect(!MissingAttachmentDetector.shouldWarn(reply))83 }84}8586@Suite struct SnoozePresetTests {87 let presets = SnoozePresets(calendar: cal())8889 @Test func anOrdinaryWednesdayMorning() {90 let now = at(2026, 11, 18, 10, 15)91 #expect(presets.date(.laterToday, now: now) == at(2026, 11, 18, 13, 30))92 #expect(presets.date(.tonight, now: now) == at(2026, 11, 18, 18))93 #expect(presets.date(.tomorrowMorning, now: now) == at(2026, 11, 19, 8))94 #expect(presets.date(.thisWeekend, now: now) == at(2026, 11, 21, 8))95 #expect(presets.date(.nextWeek, now: now) == at(2026, 11, 23, 8))96 #expect(presets.date(.inAWeek, now: now) == at(2026, 11, 25, 8))97 #expect(presets.available(now: now).map(\.preset) == SnoozePreset.allCases)98 // exact half hours are not pushed further; anything past is rounded up99 #expect(presets.date(.laterToday, now: at(2026, 11, 18, 10, 0)) == at(2026, 11, 18, 13, 0))100 #expect(presets.date(.laterToday, now: at(2026, 11, 18, 10, 0, 1)) == at(2026, 11, 18, 13, 30))101 #expect(presets.date(.laterToday, now: at(2026, 11, 18, 10, 31)) == at(2026, 11, 18, 14, 0))102 }103104 @Test func aroundMidnight() {105 // late evening: nothing left of today106 let late = at(2026, 11, 18, 23, 50)107 #expect(presets.date(.laterToday, now: late) == nil && presets.date(.tonight, now: late) == nil)108 #expect(presets.date(.tomorrowMorning, now: late) == at(2026, 11, 19, 8))109 #expect(presets.date(.laterToday, now: at(2026, 11, 18, 20, 59)) == nil)110 #expect(presets.date(.laterToday, now: at(2026, 11, 18, 20, 30)) == at(2026, 11, 18, 23, 30))111 #expect(presets.date(.laterToday, now: at(2026, 11, 18, 20, 31)) == nil)112 // just after midnight: « tomorrow morning » is the morning about to come, « in a week » counts from the new day113 let small = at(2026, 11, 19, 0, 30)114 #expect(presets.date(.tomorrowMorning, now: small) == at(2026, 11, 19, 8))115 #expect(presets.date(.laterToday, now: small) == at(2026, 11, 19, 3, 30) && presets.date(.tonight, now: small) == at(2026, 11, 19, 18))116 #expect(presets.date(.inAWeek, now: small) == at(2026, 11, 26, 8))117 // from 4:00 on, tomorrow is tomorrow118 #expect(presets.date(.tomorrowMorning, now: at(2026, 11, 19, 3, 59)) == at(2026, 11, 19, 8))119 #expect(presets.date(.tomorrowMorning, now: at(2026, 11, 19, 4, 0)) == at(2026, 11, 20, 8))120 // the last second of a day and the first of the next121 #expect(presets.date(.tomorrowMorning, now: at(2026, 11, 18, 23, 59, 59)) == at(2026, 11, 19, 8))122 #expect(presets.date(.tomorrowMorning, now: at(2026, 11, 19, 0, 0, 0)) == at(2026, 11, 19, 8))123 // tonight needs at least an hour124 #expect(presets.date(.tonight, now: at(2026, 11, 18, 17, 0)) == at(2026, 11, 18, 18) && presets.date(.tonight, now: at(2026, 11, 18, 17, 1)) == nil)125 }126127 @Test func weekends() {128 // Friday evening: the weekend preset is tomorrow morning — offered once129 let friday = at(2026, 11, 20, 17, 30)130 #expect(presets.date(.thisWeekend, now: friday) == at(2026, 11, 21, 8) && presets.date(.tomorrowMorning, now: friday) == at(2026, 11, 21, 8))131 #expect(presets.available(now: friday).map(\.preset) == [.laterToday, .tomorrowMorning, .nextWeek, .inAWeek])132 // during the weekend there is no « this weekend »133 let saturday = at(2026, 11, 21, 9), sunday = at(2026, 11, 22, 21)134 #expect(presets.date(.thisWeekend, now: saturday) == nil && presets.date(.thisWeekend, now: sunday) == nil)135 #expect(presets.date(.nextWeek, now: saturday) == at(2026, 11, 23, 8) && presets.date(.nextWeek, now: sunday) == at(2026, 11, 23, 8))136 // Sunday evening: next week is tomorrow morning — offered once137 #expect(presets.available(now: sunday).map(\.preset) == [.tomorrowMorning, .inAWeek])138 // Monday: next week is the following Monday, which is also « in a week »139 let monday = at(2026, 11, 23, 7)140 #expect(presets.date(.nextWeek, now: monday) == at(2026, 11, 30, 8) && presets.date(.inAWeek, now: monday) == at(2026, 11, 30, 8))141 #expect(presets.available(now: monday).map(\.preset) == [.laterToday, .tonight, .tomorrowMorning, .thisWeekend, .nextWeek])142 // across a month and a year end143 #expect(presets.date(.thisWeekend, now: at(2026, 12, 30, 12)) == at(2027, 1, 2, 8) && presets.date(.nextWeek, now: at(2026, 12, 30, 12)) == at(2027, 1, 4, 8))144 }145146 @Test func daylightSavingChangesKeepWallClockHours() {147 // Toronto falls back on 2026-11-01 at 02:00 EDT → 01:00 EST148 let before = at(2026, 10, 31, 22, 0)149 let morning = presets.date(.tomorrowMorning, now: before)150 #expect(morning == utc(2026, 11, 1, 13) && morning!.timeIntervalSince(before) == 11 * 3600)151 #expect(presets.date(.inAWeek, now: at(2026, 10, 28, 9)) == utc(2026, 11, 4, 13))152 #expect(presets.date(.nextWeek, now: at(2026, 10, 30, 9)) == utc(2026, 11, 2, 13))153 // « later today » is elapsed time: three real hours, across the repeated hour154 let night = utc(2026, 11, 1, 4, 30) // 00:30 EDT155 #expect(presets.date(.laterToday, now: night) == utc(2026, 11, 1, 7, 30)) // 02:30 EST156 // Toronto springs forward on 2027-03-14 at 02:00 EST → 03:00 EDT157 let eve = at(2027, 3, 13, 20, 0)158 #expect(presets.date(.tomorrowMorning, now: eve) == utc(2027, 3, 14, 12) && presets.date(.tomorrowMorning, now: eve)!.timeIntervalSince(eve) == 11 * 3600)159 #expect(presets.date(.inAWeek, now: at(2027, 3, 10, 9)) == utc(2027, 3, 17, 12))160 #expect(presets.date(.thisWeekend, now: at(2027, 3, 12, 9)) == utc(2027, 3, 13, 13) && presets.date(.nextWeek, now: at(2027, 3, 12, 9)) == utc(2027, 3, 15, 12))161 let springNight = utc(2027, 3, 14, 5, 30) // 00:30 EST162 #expect(presets.date(.laterToday, now: springNight) == utc(2027, 3, 14, 8, 30)) // 04:30 EDT163 // a morning hour that does not exist that day resolves to a real, later instant164 let odd = SnoozePresets(calendar: cal(), morningHour: 2)165 let skipped = odd.date(.tomorrowMorning, now: eve)166 #expect(skipped != nil && skipped! > eve && skipped! <= utc(2027, 3, 14, 7, 0).addingTimeInterval(3600))167 }168169 @Test func theSameInstantInAnotherTimeZoneGivesThatZonesDates() {170 let now = utc(2026, 11, 18, 15, 15) // 10:15 in Toronto, 00:15 Thursday in Tokyo171 let tokyo = SnoozePresets(calendar: cal("Asia/Tokyo"))172 #expect(tokyo.date(.tomorrowMorning, now: now) == at(2026, 11, 19, 8, tz: "Asia/Tokyo"))173 #expect(tokyo.date(.thisWeekend, now: now) == at(2026, 11, 21, 8, tz: "Asia/Tokyo") && tokyo.date(.nextWeek, now: now) == at(2026, 11, 23, 8, tz: "Asia/Tokyo"))174 #expect(presets.date(.tomorrowMorning, now: now) == at(2026, 11, 19, 8) && presets.date(.tomorrowMorning, now: now) != tokyo.date(.tomorrowMorning, now: now))175 // a zone without daylight saving and with a half-hour offset176 let kolkata = SnoozePresets(calendar: cal("Asia/Kolkata"))177 #expect(kolkata.date(.laterToday, now: at(2026, 11, 18, 10, 10, tz: "Asia/Kolkata")) == at(2026, 11, 18, 13, 30, tz: "Asia/Kolkata"))178 // every preset is always strictly in the future179 var t = at(2026, 10, 25, 0, 0)180 for _ in 0..<(24 * 4 * 12) {181 for (p, d) in presets.available(now: t) { #expect(d > t, "\(p) at \(t)") }182 #expect(presets.date(.tomorrowMorning, now: t) != nil && presets.date(.inAWeek, now: t) != nil && presets.date(.nextWeek, now: t) != nil)183 t = t.addingTimeInterval(900)184 }185 }186187 @Test func customHoursAndCustomDates() {188 let p = SnoozePresets(calendar: cal(), morningHour: 9, eveningHour: 20, laterHours: 1)189 let now = at(2026, 11, 18, 10, 15)190 #expect(p.date(.laterToday, now: now) == at(2026, 11, 18, 11, 30) && p.date(.tonight, now: now) == at(2026, 11, 18, 20) && p.date(.tomorrowMorning, now: now) == at(2026, 11, 19, 9))191 #expect(p.isValidCustom(now.addingTimeInterval(3600), now: now) && !p.isValidCustom(now, now: now) && !p.isValidCustom(now.addingTimeInterval(-60), now: now) && !p.isValidCustom(now.addingTimeInterval(400 * 86400), now: now))192 }193}194195@Suite struct QueryBuilderTests {196 @Test func tokens() {197 #expect(QueryChip.from("jeanne@example.com").token == "from:jeanne@example.com")198 #expect(QueryChip.from("Jeanne Tremblay").token == "from:\"Jeanne Tremblay\"")199 #expect(QueryChip.from("Jeanne Tremblay").negate().token == "-from:\"Jeanne Tremblay\"")200 #expect(QueryChip.text("budget").token == "budget" && QueryChip.text("budget 2027").token == "\"budget 2027\"" && QueryChip.text("budget", phrase: true).token == "\"budget\"")201 // free text that would be read as an operator, a negation or OR is quoted202 #expect(QueryChip.text("OR").token == "\"OR\"" && QueryChip.text("-x").token == "\"-x\"" && QueryChip.text("note:x").token == "\"note:x\"")203 // the language has no escape for a quote204 #expect(QueryChip.subject("le \"grand\" jour").token == "subject:\"le grand jour\"")205 #expect(QueryChip.hasAttachment.token == "has:attachment" && QueryChip.unread.token == "is:unread" && QueryChip.place("inbox").token == "in:inbox" && QueryChip.label("Clients VIP").token == "label:\"Clients VIP\"")206 #expect(QueryChip.before(at(2026, 12, 1, 23, 30), calendar: cal()).token == "before:2026-12-01" && QueryChip.after(at(2026, 1, 5, 0, 0), calendar: cal()).token == "after:2026-01-05")207 // the calendar day is the user's, not UTC's208 #expect(QueryChip.before(utc(2026, 12, 2, 3), calendar: cal()).token == "before:2026-12-01")209 #expect(QueryChip.larger(bytes: 5 * 1024 * 1024).token == "larger:5m" && QueryChip.smaller(bytes: 10 * 1024).token == "smaller:10k" && QueryChip.larger(bytes: 1 << 30).token == "larger:1g" && QueryChip.larger(bytes: 1500).token == "larger:1500")210 #expect(QueryChip(op: nil, rawOp: "near", value: "x").token == "near:x")211 #expect(QueryOperator.is.suggestedValues?.contains("followup") == true && QueryOperator.in.suggestedValues?.contains("snoozed") == true && QueryOperator.from.suggestedValues == nil && QueryOperator.text.prefix == "" && QueryOperator.in.prefix == "in:")212 #expect(QueryOperator.allCases.count == 16)213 }214215 @Test func buildingToggleAndAlternatives() {216 var b = QueryBuilder()217 #expect(b.isEmpty && b.query == "")218 b.add(.from("jeanne"))219 b.add(.hasAttachment)220 b.addAlternative(.label("Factures"))221 b.add(.text("devis toiture"))222 #expect(b.query == "from:jeanne has:attachment OR label:Factures \"devis toiture\"" && b.chips.map(\.group) == [0, 1, 1, 2])223 b.toggle(.unread)224 #expect(b.contains(.unread) && b.query.hasSuffix(" is:unread"))225 b.toggle(QueryChip.state("UNREAD"))226 #expect(!b.contains(.unread) && b.chips.count == 4)227 b.remove(b.chips[0])228 #expect(b.query == "has:attachment OR label:Factures \"devis toiture\"")229 var alone = QueryBuilder()230 alone.addAlternative(.starred)231 #expect(alone.query == "is:starred" && alone.isWithinLimits)232 var long = QueryBuilder((0..<51).map { QueryChip(op: .text, value: "t\($0)", group: $0) })233 #expect(!long.isWithinLimits)234 long.chips = [QueryChip.text(String(repeating: "x", count: 1001))]235 #expect(!long.isWithinLimits)236 // chips of a server parse rebuild the same query237 let parsed = ParsedQuery(json: ["terms": [["op": "from", "value": "a b", "negated": true, "start": 0, "end": 9, "group": 0], ["op": "is", "value": "unread", "start": 10, "end": 19, "group": 1], ["op": "is", "value": "starred", "start": 23, "end": 33, "group": 1]]])238 #expect(QueryBuilder(parsed.chips).query == "-from:\"a b\" is:unread OR is:starred")239 }240}241242@Suite struct LabelPaletteAndAvatarTests {243 @Test func theTenHuesOfTheDesignSystem() {244 #expect(LabelPalette.light == ["#b3261e", "#a14a00", "#7a5c00", "#2e6b2e", "#00695c", "#1d5fa8", "#4a4fb5", "#7a3fa0", "#a8327a", "#5c5f66"])245 #expect(LabelPalette.count == 10 && LabelPalette.dark.count == 10 && Set(LabelPalette.light).count == 10 && Set(LabelPalette.dark).count == 10)246 #expect((LabelPalette.light + LabelPalette.dark).allSatisfy(LabelPalette.isValidHex) && LabelPalette.fallback == LabelPalette.light[9])247 #expect(LabelPalette.hex(0) == "#b3261e" && LabelPalette.hex(12) == "#7a5c00" && LabelPalette.hex(-1) == "#5c5f66" && LabelPalette.hex(5, dark: true) == "#8fbcf5")248 #expect(!LabelPalette.isValidHex("#12345") && !LabelPalette.isValidHex("1d5fa8") && !LabelPalette.isValidHex("#12345g"))249 }250251 @Test func storedColoursLandOnThePalette() {252 #expect(LabelPalette.index(forHex: "#1d5fa8") == 5 && LabelPalette.index(forHex: "#1D5FA8") == 5 && LabelPalette.index(forHex: "1d5fa8") == 5)253 // colours of other clients (the server's default label palette) fall on the nearest hue254 #expect(LabelPalette.index(forHex: "#ef4444") == 0 && LabelPalette.index(forHex: "#6b7280") == 9 && LabelPalette.index(forHex: "#1e60a9") == 5 && LabelPalette.index(forHex: "#000000") == 3)255 #expect(LabelPalette.index(forHex: "nope") == 9 && LabelPalette.index(forHex: "") == 9)256 #expect(LabelPalette.darkVariant(of: "#b3261e") == "#ff8a80" && LabelPalette.darkVariant(of: "garbage") == "#b9bcc4")257 #expect(LabelPalette.suggestion(existing: []) == "#b3261e" && LabelPalette.suggestion(existing: ["#b3261e", "#a14a00"]) == "#7a5c00")258 #expect(LabelPalette.suggestion(existing: LabelPalette.light) == "#b3261e" && LabelPalette.suggestion(existing: LabelPalette.light + ["#b3261e"]) == "#a14a00")259 }260261 @Test func stableIndexAndAvatars() {262 // FNV-1a 32-bit over the lower-cased UTF-8, modulo 10 — fixed values, the same on every device and at every launch263 #expect(LabelPalette.index(for: "jeanne@example.com") == 9 && LabelPalette.index(for: "JEANNE@example.com") == 9 && LabelPalette.index(for: "contact@spboucher.ai") == 6)264 #expect(LabelPalette.index(for: "a") == 0 && LabelPalette.index(for: "") == 1 && LabelPalette.index(for: "Clients") == 5)265 let a = AvatarStyle(name: "Jeanne Tremblay", address: " jeanne@example.com ")266 #expect(a.initials == "JT" && a.hueIndex == 9 && a.lightHex == "#5c5f66" && a.darkHex == "#b9bcc4")267 #expect(AvatarStyle(EmailAddress(name: nil, email: "contact@spboucher.ai")).initials == "C" && AvatarStyle(EmailAddress(email: "contact@spboucher.ai")).hueIndex == 6)268 #expect(AvatarStyle.initials(name: "simon-pierre boucher", address: "x@y.z") == "SP" && AvatarStyle.initials(name: nil, address: "jean.tremblay@example.com") == "JT")269 #expect(AvatarStyle.initials(name: " ", address: "no_reply@example.com") == "NR" && AvatarStyle.initials(name: "Élodie", address: "") == "É" && AvatarStyle.initials(name: "«»", address: "") == "?")270 #expect(AvatarStyle.initials(name: "3M Canada", address: "") == "3C" && AvatarStyle.initials(name: nil, address: "") == "?")271 }272273 @Test func labelsOfAMessageSnippetsQuietHoursAndOfflineSuggestions() {274 let all = [MailLabel(id: "1", name: "Zèbre", color: "#b3261e", keyword: "lbl_00000001", position: 1), MailLabel(id: "2", name: "Clients", color: "#1d5fa8", keyword: "lbl_00000002", position: 0),275 MailLabel(id: "3", name: "Vide", color: "#1d5fa8", keyword: "", position: 0)]276 #expect(MailLabel.labels(for: ["$seen", "lbl_00000001", "lbl_00000002", "lbl_deadbeef"], in: all).map(\.name) == ["Clients", "Zèbre"])277 #expect(MailLabel.isLabelKeyword("lbl_0a1b2c3d") && !MailLabel.isLabelKeyword("lbl_XYZ") && !MailLabel.isLabelKeyword("$flagged") && !MailLabel.isLabelKeyword("lbl_0a1b2c3d4"))278279 let snippets = [Snippet(json: ["id": "s1", "name": "Merci", "shortcut": "merci", "text": "Merci beaucoup !"])!, Snippet(json: ["id": "s2", "name": "Sans"])!]280 let typed = "Bonjour ;merci"281 let m = Snippet.match(typed: typed, in: snippets)282 #expect(m?.snippet.id == "s1" && m.map { String(typed[$0.trigger]) } == ";merci")283 #expect(Snippet.match(typed: "Bonjour ;MERCI", in: snippets)?.snippet.id == "s1")284 #expect(Snippet.match(typed: "Bonjour ;merc", in: snippets) == nil && Snippet.match(typed: "a;merci", in: snippets) == nil && Snippet.match(typed: ";merci ", in: snippets) == nil && Snippet.match(typed: "rien", in: snippets) == nil)285 #expect(Snippet.isValidShortcut("merci_2") && !Snippet.isValidShortcut("Merci") && !Snippet.isValidShortcut("") && !Snippet.isValidShortcut(String(repeating: "a", count: 25)))286287 let q = QuietHours(start: "22:00", end: "07:00", timeZone: "America/Toronto")288 #expect(q.isValid && q.contains(at(2026, 11, 18, 23, 0)) && q.contains(at(2026, 11, 18, 6, 59)) && !q.contains(at(2026, 11, 18, 7, 0)) && !q.contains(at(2026, 11, 18, 12, 0)) && q.contains(at(2026, 11, 18, 22, 0)))289 let day = QuietHours(start: "09:00", end: "17:00", timeZone: "Asia/Tokyo")290 #expect(day.contains(at(2026, 11, 18, 9, 0, tz: "Asia/Tokyo")) && !day.contains(at(2026, 11, 18, 17, 0, tz: "Asia/Tokyo")) && !day.contains(at(2026, 11, 18, 9, 0)))291 #expect(!QuietHours(start: "25:00", end: "07:00", timeZone: "America/Toronto").isValid && !QuietHours(start: "22:00", end: "07:00", timeZone: "Mars/Olympus").isValid && !QuietHours(start: "08:00", end: "08:00", timeZone: "UTC").contains(Date()))292293 let pool = [ContactSuggestion(name: "Jeanne Tremblay", email: "jeanne@example.com", favorite: false, score: 5), ContactSuggestion(name: "Éric Jean", email: "eric@uqo.ca", favorite: true, score: 1),294 ContactSuggestion(name: "", email: "jean@hydro.qc.ca", score: 9), ContactSuggestion(name: "Marc", email: "marc@example.com", score: 20)]295 #expect(ContactSuggestion.filter(pool, matching: "jea").map(\.email) == ["eric@uqo.ca", "jean@hydro.qc.ca", "jeanne@example.com"])296 #expect(ContactSuggestion.filter(pool, matching: "ERIC").map(\.email) == ["eric@uqo.ca"] && ContactSuggestion.filter(pool, matching: "hydro").map(\.email) == ["jean@hydro.qc.ca"])297 #expect(ContactSuggestion.filter(pool, matching: "", limit: 2).map(\.email) == ["eric@uqo.ca", "marc@example.com"] && ContactSuggestion.filter(pool, matching: "zzz").isEmpty)298 }299}300301@Suite struct NotificationPayloadTests {302 @Test func newMailAlert() throws {303 let info: [AnyHashable: Any] = [304 "aps": ["alert": ["title": "Jeanne Tremblay", "subtitle": "Devis", "body": "Bonjour, voici…"], "badge": 7, "sound": "default", "thread-id": "\(uuidA):T1", "category": "MAIL_NEW", "mutable-content": 1, "interruption-level": "time-sensitive"] as [String: Any],305 "mb": uuidA, "email": "M1", "thread": "T1", "kind": "new", "extra": ["x": true] as [String: Any],306 ]307 let p = try #require(NotificationPayload(userInfo: info))308 #expect(p.kind == .new && p.mailboxId == uuidA && p.emailId == "M1" && p.threadId == "T1" && p.badge == 7 && p.category == NotificationPayload.categoryNew)309 #expect(p.title == "Jeanne Tremblay" && p.subtitle == "Devis" && p.body == "Bonjour, voici…" && !p.isSilent && p.isTimeSensitive && p.needsSync && p.target?.mailboxId == uuidA && p.target?.emailId == "M1")310 }311312 @Test func silentBadgeSnoozeReminderAndOthers() throws {313 let badge = try #require(NotificationPayload(userInfo: ["aps": ["content-available": 1, "badge": 3] as [String: Any], "kind": "badge"]))314 #expect(badge.kind == .badge && badge.isSilent && badge.badge == 3 && badge.target == nil && !badge.needsSync && badge.title == nil)315 let noBadge = try #require(NotificationPayload(json: ["aps": ["content-available": 1], "kind": "badge"]))316 #expect(noBadge.isSilent && noBadge.badge == nil)317 let snooze = try #require(NotificationPayload(json: ["aps": ["alert": ["title": "SP Mail", "body": "Un message est de retour"], "category": "MAIL_REMINDER", "interruption-level": "active", "thread-id": .string("\(uuidB):T9")], "mb": .string(uuidB), "email": "M9", "thread": "T9", "kind": "snooze"]))318 #expect(snooze.kind == .snooze && snooze.category == NotificationPayload.categoryReminder && !snooze.isTimeSensitive && snooze.needsSync && snooze.subtitle == nil)319 let reminder = try #require(NotificationPayload(json: ["aps": ["alert": "Relance", "category": "MAIL_REMINDER"], "mb": .string(uuidB), "email": "M9", "kind": "reminder"]))320 #expect(reminder.kind == .reminder && reminder.body == "Relance" && reminder.title == nil && reminder.threadId == nil && reminder.target?.emailId == "M9")321 // ids recovered from thread-id when the top-level ones are missing322 let fallback = try #require(NotificationPayload(json: ["aps": ["alert": ["title": "t", "body": "b"], "thread-id": .string("\(uuidA):T:7")], "kind": "new"]))323 #expect(fallback.mailboxId == uuidA && fallback.threadId == "T:7" && fallback.emailId == nil && fallback.target == nil)324 #expect(NotificationPayload(json: ["aps": ["alert": ["title": "Disque", "body": "12 %"], "category": "MAIL_ALERT"], "kind": "alert"])?.kind == .alert)325 #expect(NotificationPayload(json: ["aps": ["alert": ["title": "SP Mail", "body": ""]], "kind": "test"])?.kind == .test)326 // a kind from a newer server, and a payload without kind327 let future = try #require(NotificationPayload(json: ["aps": ["alert": ["title": "x", "body": "y"]], "kind": "digest", "mb": "m"]))328 #expect(future.kind == .unknown && !future.needsSync && future.mailboxId == "m")329 #expect(NotificationPayload(json: ["aps": ["alert": "x"]])?.kind == .unknown)330 // not ours331 #expect(NotificationPayload(userInfo: [:]) == nil && NotificationPayload(userInfo: ["google.c.a.e": "1"]) == nil && NotificationPayload(json: "text") == nil && NotificationPayload(userInfo: [1: "x"]) == nil)332 // booleans and numbers of a bridged dictionary are told apart333 #expect(NotificationPayload.jsonValue(["a": true, "b": 1, "c": 1.5, "d": NSNull(), "e": [1, "x"]] as [String: Any]) == ["a": true, "b": 1, "c": 1.5, "d": nil, "e": [1, "x"]])334 }335}336