Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr SMS Gateway9// File : ios/MacLustrSMS/Tests/Build2Tests.swift10// Description : Suivi sans flux temps réel (cadence de sondage, accusé de11// livraison), bibliothèque de modèles (segments de TOUS les12// modèles de départ, migration sans doublon, import/export),13// variables typées, outils d'écriture.14// Module : ios15// Repository : https://git.spboucher.ai/maclustr-sms16// Project Website : https://sms.spboucher.ai17// Created : 2026-12-0118// Last Modified : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: admin@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import SwiftData94import Testing95@testable import MacLustrSMS9697@Suite struct PollingTests {98 @Test func cadence() {99 #expect(PollSchedule.nextDelay(status: .queued, elapsed: 0, sinceSubmitted: nil) == 1)100 #expect(PollSchedule.nextDelay(status: .dispatched, elapsed: 14.9, sinceSubmitted: nil) == 1)101 #expect(PollSchedule.nextDelay(status: .accepted, elapsed: 15, sinceSubmitted: nil) == 5)102 #expect(PollSchedule.nextDelay(status: .queued, elapsed: 600, sinceSubmitted: nil) == 5) // téléphone hors ligne : on continue, plus lentement103 #expect(PollSchedule.nextDelay(status: .queued, elapsed: 15 * 60, sinceSubmitted: nil) == nil)104 }105 @Test func stopsOnFinalStates() {106 for s in [MessageStatus.delivered, .failed, .expired, .cancelled, .unknown] { #expect(PollSchedule.nextDelay(status: s, elapsed: 2, sinceSubmitted: nil) == nil, "\(s)") }107 }108 @Test func submittedIsStableAfterAMinute() {109 #expect(PollSchedule.nextDelay(status: .submitted, elapsed: 1, sinceSubmitted: 0.5) == 1) // un accusé peut suivre de près110 #expect(PollSchedule.nextDelay(status: .submitted, elapsed: 30, sinceSubmitted: 29) == 5)111 #expect(PollSchedule.nextDelay(status: .submitted, elapsed: 61, sinceSubmitted: 60) == nil) // opérateur sans accusé : on n'attend pas indéfiniment112 #expect(PollSchedule.nextDelay(status: .submitted, elapsed: 5, sinceSubmitted: nil) == nil)113 }114 @Test func wholeRunWithoutDeliveryReportEnds() {115 // Simulation complète : en file 0,5 s, puis remis au réseau, jamais d'accusé. Le sondage doit s'arrêter seul, en moins de 30 rechargements.116 var t: TimeInterval = 0, loads = 0, submittedAt: TimeInterval? = nil117 while loads < 200 {118 loads += 1119 let status: MessageStatus = t < 0.5 ? .queued : .submitted120 if status == .submitted, submittedAt == nil { submittedAt = t }121 guard let d = PollSchedule.nextDelay(status: status, elapsed: t, sinceSubmitted: submittedAt.map { t - $0 }) else { break }122 t += d123 }124 #expect(loads < 30 && t >= 60 && t < 70, "\(loads) rechargements en \(t) s")125 }126 @Test func deliveryReceiptWording() {127 let now = Date(timeIntervalSince1970: 1_000_000)128 #expect(DeliveryReceipt.state(status: .queued, submittedAt: nil, deliveredAt: nil, now: now) == .notApplicable)129 #expect(DeliveryReceipt.state(status: .submitted, submittedAt: now.addingTimeInterval(-5), deliveredAt: nil, now: now) == .waiting)130 #expect(DeliveryReceipt.state(status: .submitted, submittedAt: now.addingTimeInterval(-30), deliveredAt: nil, now: now) == .notReceived)131 #expect(DeliveryReceipt.state(status: .delivered, submittedAt: now.addingTimeInterval(-90), deliveredAt: now, now: now) == .confirmed(now))132 #expect(DeliveryReceipt.notReceived.label.contains("non reçu") && !DeliveryReceipt.notReceived.label.lowercased().contains("livré ("))133 #expect(!DeliveryReceipt.waiting.label.lowercased().hasPrefix("livré")) // jamais « livré » sans rapport134 }135 @Test func listPolling() throws {136 func msg(_ status: String, age: TimeInterval, direction: String = "outbound") throws -> SMSMessage {137 let at = ISO8601DateFormatter().string(from: Date.now.addingTimeInterval(-age))138 return try API.decoder.decode(SMSMessage.self, from: Data(#"{"id":"m","direction":"\#(direction)","status":"\#(status)","to":"+14185550123","from":null,"text":"x","created_at":"\#(at)"}"#.utf8))139 }140 #expect(PollSchedule.listNeedsPolling([try msg("queued", age: 3)]))141 #expect(!PollSchedule.listNeedsPolling([try msg("submitted", age: 3), try msg("delivered", age: 3), try msg("received", age: 3, direction: "inbound")]))142 #expect(!PollSchedule.listNeedsPolling([try msg("queued", age: 3600)]))143 }144}145146@Suite struct StarterTemplateTests {147 @Test func everyStarterFitsAsDesigned() {148 #expect(StarterTemplates.all.count >= 40)149 #expect(Set(StarterTemplates.all.map(\.key)).count == StarterTemplates.all.count, "clés uniques")150 for t in StarterTemplates.all {151 for (lang, body) in [("fr", t.fr), ("en", t.en)] where !body.isEmpty {152 let filled = StarterTemplates.preview(body)153 #expect(TemplateEngine.unresolved(in: filled).isEmpty, "\(t.key) [\(lang)] : variable sans valeur d'exemple \(TemplateEngine.unresolved(in: filled))")154 let info = Segments.info(filled)155 #expect(info.segments == 1, "\(t.key) [\(lang)] : \(info.segments) segments (\(info.units) unités) — « \(filled) »")156 if t.gsm { #expect(info.encoding == .gsm7, "\(t.key) [\(lang)] : Unicode à cause de \(Segments.offenders(filled).map { String($0.character) })") }157 // Le texte du modèle lui-même (hors valeurs) ne doit contenir aucun caractère non GSM quand il est prévu GSM.158 let bare = body.replacing(try! Regex("\\{\\{[^}]*\\}\\}"), with: "")159 if t.gsm { #expect(Segments.offenders(bare).isEmpty, "\(t.key) [\(lang)]") }160 }161 }162 }163 @Test func categoriesAndEnglishVariants() {164 let cats = Set(StarterTemplates.all.map(\.category))165 for c in ["Rendez-vous", "Immobilier", "Codes et sécurité", "Livraison et service", "Facturation", "Relation", "Interne", "Urgent"] { #expect(cats.contains(c), "\(c)") }166 #expect(cats.isSubset(of: Set(TemplateCategory.order)))167 #expect(StarterTemplates.all.filter { !$0.en.isEmpty }.count >= 8)168 #expect(StarterTemplates.all.filter { !$0.gsm }.count <= 2)169 for t in StarterTemplates.all where !t.en.isEmpty { #expect(Set(TemplateEngine.variables(in: t.en)).isSubset(of: Set(TemplateEngine.variables(in: t.fr) + ["heure", "prénom", "marque"])), "\(t.key)") }170 }171 @MainActor @Test func migrationKeepsOwnerTemplatesAndAddsStartersOnce() throws {172 let container = try ModelContainer(for: MessageTemplate.self, RecentRecipient.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))173 let ctx = container.mainContext174 // État laissé par le build 1 : ses cinq modèles de départ, dont un modifié et un utilisé, plus un modèle créé par le propriétaire.175 let legacy = Array(StarterTemplates.legacyBodies).sorted()176 for (i, b) in legacy.enumerated() { ctx.insert(MessageTemplate(name: "Ancien \(i)", body: b, order: i)) }177 let edited = MessageTemplate(name: "Mon rappel", body: "Rappel : {{objet}} demain à {{heure}}. Merci !", order: 10); ctx.insert(edited)178 let used = try #require(try ctx.fetch(FetchDescriptor<MessageTemplate>()).first { $0.body == legacy[0] }); used.uses = 3179 let mine = MessageTemplate(name: "Clés prêtes", body: "Bonjour {{prénom}}, vos clés sont prêtes.", order: 11); ctx.insert(mine)180 try ctx.save()181182 let first = TemplateSeeder.sync(ctx)183 #expect(first.added == StarterTemplates.all.count && first.removedLegacy == 4) // 4 anciens intacts retirés, celui déjà utilisé gardé184 var all = try ctx.fetch(FetchDescriptor<MessageTemplate>())185 #expect(all.contains { $0.name == "Clés prêtes" && $0.category == TemplateCategory.mine && $0.starterKey == nil })186 #expect(all.contains { $0.name == "Mon rappel" } && all.contains { $0.uses == 3 })187 #expect(all.count == StarterTemplates.all.count + 3)188 // Relancer ne crée aucun doublon, et un modèle de départ modifié ou supprimé par l'utilisateur n'est pas réécrit ni recréé à l'identique.189 let conf = try #require(all.first { $0.starterKey == "rdv.confirmation" }); conf.body = "Version à moi {{prénom}}"190 let second = TemplateSeeder.sync(ctx)191 #expect(second.added == 0 && second.removedLegacy == 0)192 all = try ctx.fetch(FetchDescriptor<MessageTemplate>())193 #expect(all.first { $0.starterKey == "rdv.confirmation" }?.body == "Version à moi {{prénom}}")194 #expect(all.filter { $0.starterKey == "rdv.confirmation" }.count == 1)195 }196 @MainActor @Test func exportImportRoundTrip() throws {197 let a = try ModelContainer(for: MessageTemplate.self, RecentRecipient.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))198 TemplateSeeder.sync(a.mainContext)199 let mine = MessageTemplate(name: "À moi", body: "Texte {{prénom}}", order: 99, bodyEN: "Text {{prénom}}"); mine.favorite = true; a.mainContext.insert(mine)200 let data = try TemplateArchive.export(try a.mainContext.fetch(FetchDescriptor<MessageTemplate>()))201 #expect(try TemplateArchive.decode(data).templates.count == StarterTemplates.all.count + 1)202 // Import dans une bibliothèque déjà garnie : seul le modèle personnel est ajouté, une seule fois.203 let b = try ModelContainer(for: MessageTemplate.self, RecentRecipient.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))204 TemplateSeeder.sync(b.mainContext)205 let r1 = try TemplateArchive.importInto(b.mainContext, data: data)206 #expect(r1.added == 1 && r1.skipped == StarterTemplates.all.count)207 let r2 = try TemplateArchive.importInto(b.mainContext, data: data)208 #expect(r2.added == 0)209 let got = try #require(try b.mainContext.fetch(FetchDescriptor<MessageTemplate>()).first { $0.name == "À moi" })210 #expect(got.favorite && got.bodyEN == "Text {{prénom}}" && got.category == TemplateCategory.mine)211 #expect(throws: (any Error).self) { try TemplateArchive.importInto(b.mainContext, data: Data("{\"format\":\"autre\",\"version\":1,\"exportedAt\":\"2026-01-01T00:00:00Z\",\"templates\":[]}".utf8)) }212 #expect(throws: (any Error).self) { try TemplateArchive.importInto(b.mainContext, data: Data("pas du json".utf8)) }213 }214}215216@Suite struct VariableTests {217 var cal: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(identifier: "America/Toronto")!; return c }218 func date(_ y: Int, _ m: Int, _ d: Int, _ h: Int = 0, _ min: Int = 0) -> Date { cal.date(from: DateComponents(year: y, month: m, day: d, hour: h, minute: min))! }219 @Test func kindsFromNames() {220 #expect(VariableKind.of("heure") == .time && VariableKind.of("heure de fin") == .time && VariableKind.of("Heure") == .time)221 #expect(VariableKind.of("date") == .date && VariableKind.of("demain") == .date && VariableKind.of("aujourd'hui") == .date)222 #expect(VariableKind.of("montant") == .amount && VariableKind.of("lien") == .link && VariableKind.of("marque") == .brand && VariableKind.of("signature") == .signature)223 #expect(VariableKind.of("code") == .code && VariableKind.of("prénom") == .firstName && VariableKind.of("adresse") == .address && VariableKind.of("objet") == .text)224 #expect(VariableKind.brand.isRemembered && VariableKind.signature.isRemembered && !VariableKind.time.isRemembered)225 }226 @Test func quebecFormats() {227 #expect(VariableFormat.time(date(2026, 12, 3, 10, 30), calendar: cal) == "10 h 30")228 #expect(VariableFormat.time(date(2026, 12, 3, 10, 0), calendar: cal) == "10 h")229 #expect(VariableFormat.time(date(2026, 12, 3, 9, 5), calendar: cal) == "9 h 05")230 #expect(VariableFormat.date(date(2026, 12, 3), calendar: cal) == "jeudi 3 décembre")231 #expect(VariableFormat.date(date(2026, 12, 1), calendar: cal) == "mardi 1er décembre")232 #expect(VariableFormat.automatic("demain", now: date(2026, 11, 30, 23, 0), calendar: cal) == "mardi 1er décembre")233 #expect(VariableFormat.automatic("aujourd'hui", now: date(2026, 11, 30), calendar: cal) == "lundi 30 novembre")234 #expect(VariableFormat.automatic("heure") == nil)235 #expect(Segments.info(VariableFormat.date(date(2026, 12, 3), calendar: cal) + " " + VariableFormat.time(date(2026, 12, 3, 10, 30), calendar: cal)).encoding == .gsm7)236 }237 @Test func amountsAndLinks() {238 #expect(VariableFormat.amount("125.5") == "125,50 $" && VariableFormat.amount("125,50 $") == "125,50 $" && VariableFormat.amount("1250") == "1 250 $")239 #expect(VariableFormat.amount("1 250 000,00") == "1 250 000 $" && VariableFormat.amount("à discuter") == "à discuter")240 #expect(Segments.info(VariableFormat.amount("1250000")).encoding == .gsm7) // espace ordinaire, pas insécable241 #expect(VariableFormat.link("https://sms.spboucher.ai/x7/") == "sms.spboucher.ai/x7" && VariableFormat.link("exemple.ca") == "exemple.ca")242 #expect(VariableFormat.normalized(.amount, "40") == "40 $" && VariableFormat.normalized(.text, " a ") == " a ")243 }244 @Test func rememberedAndPrefill() throws {245 let d = try #require(UserDefaults(suiteName: "mlsms-tests-\(UUID().uuidString)"))246 #expect(RememberedValues.value(for: "marque", d) == nil)247 RememberedValues.set("Lou-Ka", for: "Marque", d)248 #expect(RememberedValues.value(for: "marque", d) == "Lou-Ka")249 let body = "{{marque}}: bonjour {{prénom}}, rendez-vous {{demain}} à {{heure}}. {{signature}}"250 let p = TemplateEngine.prefill(body, recipientName: "Marie Tremblay", now: date(2026, 11, 30), defaults: d)251 #expect(p["marque"] == "Lou-Ka" && p["prénom"] == "Marie" && p["demain"] != nil && p["heure"] == nil && p["signature"] == nil)252 RememberedValues.set(" ", for: "marque", d)253 #expect(RememberedValues.value(for: "marque", d) == nil)254 }255}256257@Suite struct WritingToolsTests {258 @Test func gsmCompatible() {259 let s = WritingTools.gsmCompatible("L’été — « bientôt »… 😀")260 #expect(s.text == "L'été - \" bientot \"... 😀")261 #expect(s.steps.count == 2 && s.steps[1].contains("😀")) // l'émoji est signalé, pas supprimé262 let clean = WritingTools.gsmCompatible("Voilà l’adresse : 123, rue Principale")263 #expect(clean.after.encoding == .gsm7 && clean.before.encoding == .ucs2 && clean.improves)264 #expect(WritingTools.gsmCompatible("Bonjour").steps.isEmpty)265 }266 @Test func shortenToOneSegment() {267 let long = "Bonjour Marie, votre rendez-vous est confirmé le jeudi 3 décembre à 10 h 30. Merci d'arriver 10 minutes avant et d'apporter votre carte. Au plaisir de vous voir!"268 #expect(Segments.info(long).segments == 2)269 let s = WritingTools.shortenToOneSegment(long)270 #expect(s.after.segments == 1 && s.after.encoding == .gsm7, "\(s.after.units) unités : \(s.text)")271 #expect(s.text.contains("RDV") && s.text.contains("jeudi 3 décembre") && s.text.contains("10 h 30") && s.text.contains("carte")) // aucune information perdue272 #expect(!s.steps.isEmpty && s.improves)273 // Déjà court : rien n'est abrégé inutilement.274 let short = WritingTools.shortenToOneSegment("Votre rendez-vous est à 10 h.")275 #expect(short.text == "Votre rendez-vous est à 10 h." && short.steps.isEmpty)276 // Typographie seule : les abréviations ne sont pas appliquées si le remplacement des caractères suffit.277 let typo = WritingTools.shortenToOneSegment(String(repeating: "a", count: 90) + " — votre rendez-vous")278 #expect(typo.after.segments == 1 && typo.text.contains("rendez-vous"))279 // Trop long pour un segment : on le dit (plus d'un segment), sans rien tronquer.280 let huge = WritingTools.shortenToOneSegment(String(repeating: "mot ", count: 80))281 #expect(huge.after.segments > 1 && huge.text.count >= 300)282 #expect(WritingTools.tidy("a b \n\n\n\nc ") == "a b\n\nc")283 }284}285