SPB Git

Repository Public

CoreTests.swift 16.7 KB 263 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/Tests/CoreTests.swift10// Description      : Logique pure : segments (parité avec le serveur), numéros,11//                    modèles, frise des états, décodage des réponses réelles du12//                    serveur.13// Module           : ios14// Repository       : https://git.spboucher.ai/maclustr-sms15// Project Website  : https://sms.spboucher.ai16// Created          : 2026-11-3017// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import Testing93@testable import MacLustrSMS9495@Suite struct SegmentsTests {96    @Test func gsmSingleAndMultipart() {97        #expect(Segments.info("") == SegmentInfo(encoding: .gsm7, characters: 0, units: 0, segments: 1, perSegment: 160))98        #expect(Segments.info(String(repeating: "a", count: 160)).segments == 1)99        let s161 = Segments.info(String(repeating: "a", count: 161))100        #expect(s161.segments == 2 && s161.perSegment == 153)101        #expect(Segments.info(String(repeating: "a", count: 306)).segments == 2)102        #expect(Segments.info(String(repeating: "a", count: 307)).segments == 3)103        #expect(Segments.info(String(repeating: "a", count: 200)).segments == 2)          // même cas que le test serveur104    }105    @Test func gsmAccentsAndExtensionTable() {106        #expect(Segments.info("Ça va ? é è ù à").encoding == .gsm7)                          // Ç majuscule est dans l'alphabet GSM…107        #expect(Segments.info("ça va ?").encoding == .ucs2)                                  // …mais pas « ç » minuscule108        #expect(Segments.info("Çé è ù à ñ ü ö ä").encoding == .gsm7)109        let euro = Segments.info(String(repeating: "€", count: 81))                         // extension : 2 septets chacun (cas du test serveur)110        #expect(euro.encoding == .gsm7 && euro.units == 162 && euro.segments == 2)111        #expect(Segments.info("[test] {a} ~ | \\ ^").encoding == .gsm7)112    }113    @Test func unicodeThresholds() {114        #expect(Segments.info(String(repeating: "ê", count: 70)).segments == 1)115        let u71 = Segments.info(String(repeating: "ê", count: 71))116        #expect(u71.encoding == .ucs2 && u71.segments == 2 && u71.perSegment == 67)117        let emoji = Segments.info("Ça va ? 😀 " + String(repeating: "é", count: 70))        // cas du test serveur : 2 segments UCS-2118        #expect(emoji.encoding == .ucs2 && emoji.segments == 2)119        #expect(Segments.info("😀").units == 2)                                              // un émoji = 2 unités UTF-16120        #expect(Segments.info(String(repeating: "😀", count: 400)).segments > Segments.maxSegments)121    }122    @Test func offendersAndSimplification() {123        let t = "L’été — « bientôt »… 😀"124        let off = Segments.offenders(t)125        #expect(off.map(\.character) == ["’", "—", "«", "ô", "»", "…", "😀"])126        #expect(off.first?.replacement == "'" && off.last?.replacement == nil)127        #expect(Segments.simplified("L’été — « bientôt »…") == "L'été - \" bientot \"...")128        #expect(Segments.info(Segments.simplified("L’été — « bientôt »…")).encoding == .gsm7)129        let long = String(repeating: "a", count: 100) + "’"130        #expect(Segments.savings(long)?.now == 2 && Segments.savings(long)?.simplified == 1)131        #expect(Segments.savings("abc 😀") == nil)                                           // un émoji n'a pas d'équivalent132        #expect(Segments.savings("abc") == nil)133        #expect(Segments.offenders("espace\u{00A0}insécable").first?.replacement == " ")134    }135}136137@Suite struct PhoneTests {138    @Test func normalisation() {139        #expect(PhoneNumber.e164("418 555-0123") == "+14185550123")140        #expect(PhoneNumber.e164("(418) 555-0123") == "+14185550123")141        #expect(PhoneNumber.e164("1 418 555 0123") == "+14185550123")142        #expect(PhoneNumber.e164("+1 418-555-0123") == "+14185550123")143        #expect(PhoneNumber.e164("+33 6 12 34 56 78") == "+33612345678")144        for bad in ["", "12345", "418 555-012", "018 555-0123", "418 155-0123", "+1 418 555", "+0123456789", "abc"] { #expect(PhoneNumber.e164(bad) == nil, "\(bad)") }145    }146    @Test func affichage() {147        #expect(PhoneNumber.pretty("+14185550123") == "+1 418 555-0123")148        #expect(PhoneNumber.pretty("+33612345678") == "+33612345678")149        #expect(PhoneNumber.pretty(nil) == "—")150        #expect(PhoneNumber.pretty("Videotron") == "Videotron")151        #expect(PhoneNumber.formatWhileTyping("4185") == "418 5")152        #expect(PhoneNumber.formatWhileTyping("4185550123") == "418 555-0123")153        #expect(PhoneNumber.formatWhileTyping("14185550123") == "1 418 555-0123")154        #expect(PhoneNumber.e164(PhoneNumber.formatWhileTyping("4185550123")) == "+14185550123")155    }156}157158@Suite struct TemplateTests {159    @Test func variables() {160        let body = "Bonjour {{prénom}}, rendez-vous le {{ date }} à {{heure}}. Merci {{Prénom}} !"161        #expect(TemplateEngine.variables(in: body) == ["prénom", "date", "heure"])162        let filled = TemplateEngine.fill(body, values: ["prénom": "Marie", "date": "3 décembre"])163        #expect(filled == "Bonjour Marie, rendez-vous le 3 décembre à {{heure}}. Merci Marie !")164        #expect(TemplateEngine.unresolved(in: filled) == ["heure"])                           // une variable vide reste visible : l'envoi est bloqué165        #expect(TemplateEngine.fill("{{a}}", values: ["a": "   "]) == "{{a}}")166        #expect(TemplateEngine.variables(in: "pas de variable {x} { {y} }") == [])167    }168    @Test func signature() {169        #expect(TemplateEngine.withSignature("Bonjour", signature: "— SP") == "Bonjour\n— SP")170        #expect(TemplateEngine.withSignature("Bonjour\n— SP", signature: "— SP") == "Bonjour\n— SP")171        #expect(TemplateEngine.withSignature("Bonjour", signature: "  ") == "Bonjour")172    }173    @Test func enrollmentLink() {174        let tok = "qWee23BPLS4v9zg8ujKZZCVZ30WfOY99n5Lpa1MjBug"175        #expect(EnrollmentLink.token(from: "https://sms.spboucher.ai/enroll#\(tok)") == tok)176        #expect(EnrollmentLink.token(from: "  \(tok)\n") == tok)177        #expect(EnrollmentLink.token(from: "https://sms.spboucher.ai/enroll") == nil)178        #expect(EnrollmentLink.token(from: "https://x/enroll#<script>") == nil)179    }180}181182@Suite struct TimelineTests {183    func events(_ pairs: [(String, String)]) -> [MessageEvent] {184        let json = "[" + pairs.enumerated().map { i, p in "{\"type\":\"\(p.0)\",\"from\":null,\"to\":\"\(p.1)\",\"source\":\"device\",\"detail\":{},\"at\":\"2026-11-30T22:00:0\(i).000Z\"}" }.joined(separator: ",") + "]"185        return try! API.decoder.decode([MessageEvent].self, from: Data(json.utf8))186    }187    @Test func nominalPath() {188        let e = events([("message.created", "queued"), ("command.dispatched", "dispatched"), ("sms.send.accepted", "accepted")])189        let s = SendTimeline.steps(status: .accepted, events: e)190        #expect(s.map(\.status) == SendTimeline.path)191        #expect(s.map(\.state) == [.done, .done, .current, .pending, .pending, .pending])192        #expect(s[0].at != nil && s[3].at == nil)193        let done = SendTimeline.steps(status: .delivered, events: e)194        #expect(done.allSatisfy { $0.state == .done })195        #expect(SendTimeline.steps(status: .submitted, events: e)[4].state == .done)         // « remis au réseau » est une issue : étape franchie…196        #expect(SendTimeline.steps(status: .submitted, events: e)[5].state == .pending)      // …mais « livré » n'est jamais coché sans rapport197        #expect(SendTimeline.headline(.submitted) == "Envoyé — remis au réseau" && MessageStatus.submitted.tone == .ok)198    }199    @Test func problemOutcomes() {200        let e = events([("message.created", "queued"), ("command.dispatched", "dispatched"), ("sms.send.accepted", "accepted"), ("sms.send.submitting", "submitting"), ("sms.send.unknown", "unknown")])201        let s = SendTimeline.steps(status: .unknown, events: e)202        #expect(s.last?.status == .unknown && s.last?.state == .problem)203        #expect(s.prefix(4).allSatisfy { $0.state == .done })204        #expect(s[4].state == .skipped && s[5].state == .skipped)205        let cancelled = SendTimeline.steps(status: .cancelled, events: events([("message.created", "queued"), ("message.cancelled", "cancelled")]))206        #expect(cancelled.map(\.state) == [.done, .skipped, .skipped, .skipped, .skipped, .skipped, .problem])207        let held = SendTimeline.steps(status: .held, events: events([("message.created", "held")]))208        #expect(held.first?.status == .held && held.first?.state == .current && held.dropFirst().allSatisfy { $0.state == .pending })209    }210    @Test func ignoredEventsDoNotCount() {211        let json = #"[{"type":"message.created","from":null,"to":"queued","source":"api","detail":{},"at":"2026-11-30T22:00:00.000Z"},{"type":"sms.send.accepted","from":"queued","to":"queued","source":"device","detail":{"ignored":true,"wanted":"ACCEPTED"},"at":"2026-11-30T22:00:01.000Z"}]"#212        let e = try! API.decoder.decode([MessageEvent].self, from: Data(json.utf8))213        #expect(e[1].ignored && !e[0].ignored)214        #expect(SendTimeline.steps(status: .queued, events: e).map(\.state) == [.current, .pending, .pending, .pending, .pending, .pending])215    }216    @Test func honestWording() {217        #expect(MessageStatus.submitted.label == "Remis au réseau" && MessageStatus.delivered.label == "Livré")218        #expect(MessageStatus.submitted.explanation.contains("pas encore une preuve de livraison"))219        #expect(MessageStatus.unknown.explanation.contains("jamais renvoyé automatiquement"))220        #expect(MessageStatus.queued.isCancellable && MessageStatus.held.isCancellable && !MessageStatus.dispatched.isCancellable)221    }222}223224@Suite struct DecodingTests {225    func fixture(_ name: String) throws -> Data {226        let url = try #require(Bundle(for: Marker.self).url(forResource: name, withExtension: "json"))227        return try Data(contentsOf: url)228    }229    final class Marker {}230    @Test func realServerPayloads() throws {231        let o = try API.decoder.decode(Overview.self, from: fixture("overview"))232        #expect(o.devices.online == 1 && o.sendMode == "allowlist" && !o.killSwitch && o.messages.failed24H == 0)233        let d = try API.decoder.decode(ListOf<Device>.self, from: fixture("devices")).data234        #expect(d.first?.id == "android-01" && d.first?.available == true && d.first?.batteryPct == 87 && d.first?.stateLabel == "Disponible")235        #expect(d.first?.sims?.first?.id == "sim-1")236        let s = try API.decoder.decode(SimList.self, from: fixture("sims"))237        #expect(s.data.first?.usable == true && s.data.first?.number == "+14185550124" && s.data.first?.title == "Opérateur Essai · +1 418 555-0124")238        #expect(try API.decoder.decode(ListOf<AllowedRecipient>.self, from: fixture("allowed-recipients")).data.map(\.number) == ["+14185550123"])239        #expect(try API.decoder.decode(Me.self, from: fixture("me")).user.displayName == "Essai iOS")240    }241    @Test func messageAndErrors() throws {242        let json = #"{"id":"sms_1","direction":"outbound","status":"submitted","to":"+14185550123","from":"+14185550124","text":"Bonjour","text_purged":false,"sensitive":false,"device_id":"android-01","sim_id":"sim-1","application_id":null,"conversation_id":"conv_1","encoding":"gsm7","segments":1,"characters":7,"error":null,"created_at":"2026-11-30T22:00:00.123Z","expires_at":"2026-11-30T23:00:00Z","dispatched_at":null,"accepted_at":null,"submitted_at":"2026-11-30T22:00:01.300Z","delivered_at":null,"finalized_at":null,"received_at":null,"events":[]}"#243        let m = try API.decoder.decode(SMSMessage.self, from: Data(json.utf8))244        #expect(m.status == .submitted && m.peer == "+14185550123" && m.isOutbound && m.submittedAt != nil && m.displayText == "Bonjour")245        let odd = try API.decoder.decode(SMSMessage.self, from: Data(json.replacingOccurrences(of: "\"submitted\"", with: "\"etat_futur\"").utf8))246        #expect(odd.status == .unknown)                                                      // un état inconnu de cette version ne fait pas planter le décodage247        let e = API.error(status: 403, data: Data(#"{"error":{"code":"recipient_not_allowed","message":"mode liste autorisée : ce destinataire n'est pas dans la liste"}}"#.utf8))248        #expect(e.code == "recipient_not_allowed" && e.message.hasPrefix("Mode liste autorisée") && e.message.hasSuffix("."))249        #expect(API.error(status: 429, data: Data(#"{"error":{"code":"rate_limited","message":"trop de requêtes"}}"#.utf8), retryAfter: "15").retryAfter == 15)250        #expect(API.error(status: 502, data: Data("<html>".utf8)).code == "http_502")251        #expect(API.parseDate("2026-11-30T22:00:00Z") != nil && API.parseDate("2026-11-30T22:00:00.123Z") != nil && API.parseDate("hier") == nil)252    }253    @Test func releaseBuildHasNoDebugInjection() throws {254        // Le code d'injection de session (-serverURL / -sessionToken) est entouré de #if DEBUG dans AppModel.swift.255        let src = try String(contentsOfFile: #filePath.replacingOccurrences(of: "Tests/CoreTests.swift", with: "Core/AppModel.swift"), encoding: .utf8)256        let before = try #require(src.range(of: "\"sessionToken\""))257        let head = src[..<before.lowerBound], tail = src[before.upperBound...]258        #expect(head.components(separatedBy: "#if DEBUG").count - 1 == head.components(separatedBy: "#endif").count)   // on est à l'intérieur d'un bloc ouvert259        #expect(tail.contains("#endif"))260        #expect(src.components(separatedBy: "\"sessionToken\"").count == 2 && src.components(separatedBy: "\"serverURL\"").count == 2)261    }262}263
Files main
Menu

Theme