SPB Git

Repository Public

PhoneAccountTests.swift 22.1 KB 343 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKaTests/PhoneAccountTests.swift10// Description      : comptes par numéro de cellulaire (3.1.1) — normalisation11//                    et mise en forme du numéro, client par téléphone contre un12//                    serveur simulé (`URLProtocol`), compte sans adresse13//                    courriel, bascule des modes, options du serveur ; contrat14//                    réel contre la préproduction (textos simulés, code 424242)15//                    et lecture seule des options de la production.16// Module           : ImmoKaTests17// Repository       : https://git.spboucher.ai/immo-ka-ios-v318// Project Website  : https://www.immo-ka.com19// Created          : 2026-11-3020// Last Modified    : 2026-11-3021//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation95import Testing96@testable import ImmoKa9798private let base = URL(string: "https://compte.test")!99private func api(token: String? = nil) -> AccountAPI { AccountAPI(session: StubServer.session(), base: { base }, token: { token }) }100private let phoneSession = #"{"user":{"id":"p1","email":null,"phone":"+14185550123","name":"Léa","verified":true,"created_at":1796000000,"role":"acheteur"},"session":{"expires_at":1803776000,"token":"jeton-tel"}}"#101102@Suite("Cellulaire : numéro, identifiant, options")103struct PhoneNumberTests {104    @Test("normalisation : toute écriture usuelle devient +1 et dix chiffres")105    func normalize() {106        for ok in ["418 555-0123", "(418) 555-0123", "4185550123", "418.555.0123", "+1 418 555 0123", "1 418 555 0123", "+14185550123", "  418-555-0123 "] {107            #expect(PhoneNumber.normalize(ok) == "+14185550123", "\(ok)")108        }109        #expect(PhoneNumber.normalize("212 555 0199") == "+12125550199", "États-Unis")110    }111112    @Test("refus : trop court, trop long, autre pays, indicatif impossible, sans frais, surtaxé, lettres")113    func refuse() {114        for bad in ["", "418 555 012", "418 555 01234", "+33 6 12 34 56 78", "+44 20 7946 0958", "018 555 0123", "118 555 0123", "418 055 0123", "418 155 0123",115                    "800 555 0123", "888 555 0123", "877 555 0123", "900 555 0123", "418 555 O123", "lea@example.org", "418 555 0123 poste 4", "++1 418 555 0123", "2 418 555 0123"] {116            #expect(PhoneNumber.normalize(bad) == nil, "\(bad)")117            #expect(!AccountIdentifier.phone(bad).looksValid, "\(bad)")118        }119    }120121    @Test("mise en forme : « 418 555-0123 », douce pendant la frappe, sans rien inventer")122    func format() {123        #expect(PhoneNumber.display("+14185550123") == "418 555-0123" && PhoneNumber.display("(418) 555-0123") == "418 555-0123")124        #expect(PhoneNumber.display(nil) == "" && PhoneNumber.display("") == "" && PhoneNumber.display("pas un numéro") == "pas un numéro")125        let typed = ["4": "4", "418": "418", "4185": "418 5", "418555": "418 555", "4185550": "418 555-0", "4185550123": "418 555-0123",126                     "418 555-0123": "418 555-0123", "41855501239": "418 555-0123", "(418) 555": "418 555", "": "",127                     "14185550123": "1 418 555-0123", "+14185550123": "+1 418 555-0123", "+1418": "+1 418", "+33612": "+33612"]128        for (input, expected) in typed { #expect(PhoneNumber.formatTyping(input) == expected, "\(input)") }129        // mettre en forme deux fois ne change plus rien : la saisie ne « saute » pas130        for input in typed.keys { let once = PhoneNumber.formatTyping(input); #expect(PhoneNumber.formatTyping(once) == once, "\(input)") }131        #expect(PhoneNumber.normalize(PhoneNumber.formatTyping("+14185550123")) == "+14185550123")132    }133134    @Test("identifiant : valeur envoyée, affichage, champ fautif")135    func identifier() {136        let p = AccountIdentifier.phone("(418) 555-0123"), e = AccountIdentifier.email("  Lea@Example.org ")137        #expect(p.value == "+14185550123" && p.display == "418 555-0123" && p.mode == .phone && p.param == "phone" && p.looksValid)138        #expect(e.value == "lea@example.org" && e.display == "lea@example.org" && e.mode == .email && e.param == "email" && e.looksValid)139        #expect(AccountIdentifier.phone("418 555").value == "418 555", "un numéro incomplet part tel quel : le serveur répondra telephone_invalide")140    }141142    @Test("options : le cellulaire n'est offert que si le serveur le dit")143    func options() throws {144        let on = try JSONDecoder().decode(AccountOptions.self, from: Data(#"{"email_signup":true,"phone_signup":true,"phone_countries":["CA","US"],"code_length":6,"futur":1}"#.utf8))145        #expect(on.phoneSignup && on.emailSignup && on.phoneCountries == ["CA", "US"] && on.codeLength == 6)146        let off = try JSONDecoder().decode(AccountOptions.self, from: Data(#"{"email_signup":true,"phone_signup":false}"#.utf8))147        #expect(!off.phoneSignup)148        let old = try JSONDecoder().decode(AccountOptions.self, from: Data("{}".utf8))149        #expect(!old.phoneSignup && old.emailSignup, "champ absent : pas de cellulaire")150        #expect(!AccountOptions.fallback.phoneSignup && AccountOptions.fallback.emailSignup)151    }152153    @Test("compte sans adresse courriel : rien ne casse, rien n'affiche « nil »")154    func userWithoutEmail() throws {155        let u = try JSONDecoder().decode(AccountSession.self, from: Data(phoneSession.utf8)).user156        #expect(u.email == nil && u.phone == "+14185550123" && u.isPhoneAccount && u.contact == "418 555-0123" && u.displayName == "Léa")157        #expect(u.canUseMessaging && u.canStartConversation && !u.isBroker)158        let nameless = try JSONDecoder().decode(AccountUser.self, from: Data(#"{"id":"p2","email":null,"phone":"+12125550199"}"#.utf8))159        #expect(nameless.displayName == "212 555-0199" && nameless.contact == "212 555-0199")160        let empty = try JSONDecoder().decode(AccountUser.self, from: Data(#"{"id":"p3","email":"","phone":""}"#.utf8))161        #expect(empty.email == nil && empty.phone == nil && empty.contact == "" && empty.displayName == "Mon compte" && !empty.isPhoneAccount)162        let mail = try JSONDecoder().decode(AccountUser.self, from: Data(#"{"id":"u","email":"lea@example.org","phone":null}"#.utf8))163        #expect(!mail.isPhoneAccount && mail.contact == "lea@example.org")164        for user in [u, nameless, empty, mail] {165            #expect(!"\(user.displayName) \(user.contact)".contains("nil") && !"\(user.displayName)".contains("Optional"))166            #expect(try JSONDecoder().decode(AccountUser.self, from: JSONEncoder().encode(user)) == user, "la fiche gardée au trousseau se relit")167        }168    }169}170171extension StubbedAccountTests {172@Suite("Cellulaire : client d'API et session")173@MainActor174struct PhoneAPITests {175    @Test("options : route publique sans jeton")176    func options() async throws {177        StubServer.install { _ in .json(#"{"email_signup":true,"phone_signup":true,"phone_countries":["CA","US"],"code_length":6}"#) }178        let o = try await api(token: "jeton").options()179        #expect(o.phoneSignup)180        let r = try #require(StubServer.seen.first)181        #expect(r.method == "GET" && r.url == "https://compte.test/api/v3/compte/options" && r.headers["Authorization"] == nil && r.headers["X-ImmoKa-Client"] == "ios")182    }183184    @Test("mêmes routes que le courriel, avec phone à la place de email (jamais les deux), numéro normalisé")185    func routes() async throws {186        StubServer.install { r in187            if r.path.hasSuffix("/inscription") || r.path.hasSuffix("/renvoi") { return .json(#"{"status":"verification_envoyee","channel":"sms","phone":"+14185550123","phone_display":"418 555-0123","code_length":6,"expires_in_min":10}"#, status: 202) }188            if r.path.hasSuffix("/oubli") { return .json(#"{"status":"code_envoye","channel":"sms","phone":"+14185550123","phone_display":"418 555-0123"}"#, status: 202) }189            return .json(phoneSession)190        }191        let a = api(), id = AccountIdentifier.phone("(418) 555-0123")192        let sent = try await a.signUp(id, password: "Sapin-Bleu-4812", name: "Léa")193        #expect(sent.channel == "sms" && sent.phoneDisplay == "418 555-0123" && sent.phone == "+14185550123" && sent.expiresInMin == 10)194        _ = try await a.verify(id, code: "424242")195        _ = try await a.resendVerification(id)196        let s = try await a.signIn(id, password: "Sapin-Bleu-4812")197        #expect(s.session?.token == "jeton-tel" && s.user.email == nil && s.user.phone == "+14185550123")198        #expect(try await a.forgotPassword(id).status == "code_envoye")199        _ = try await a.resetPassword(id, code: "424242", password: "Sapin-Bleu-4812-b")200        #expect(StubServer.seen.map(\.path) == ["inscription", "verification", "verification/renvoi", "connexion", "mot-de-passe/oubli", "mot-de-passe/reinitialisation"].map { "/api/v3/compte/" + $0 })201        #expect(StubServer.seen.allSatisfy { $0.json["phone"] as? String == "+14185550123" && $0.json["email"] == nil && $0.headers["X-ImmoKa-Client"] == "ios" && $0.headers["Authorization"] == nil })202        #expect(StubServer.seen[0].json["name"] as? String == "Léa" && StubServer.seen[1].json["code"] as? String == "424242" && StubServer.seen[5].json["password"] as? String == "Sapin-Bleu-4812-b")203        // par courriel, rien ne change : email, jamais phone204        _ = try await a.signIn(.email(" Lea@Example.org"), password: "x")205        #expect(StubServer.seen.last?.json["email"] as? String == "lea@example.org" && StubServer.seen.last?.json["phone"] == nil)206    }207208    @Test("erreurs du téléphone : telephone_invalide et son champ, telephone_non_verifie, sms_indisponible, 429 et son attente")209    func errors() async throws {210        func failure(_ r: StubResponse) async -> AccountError? {211            StubServer.install { _ in r }212            do { _ = try await api().signUp(.phone("418 555-0123"), password: "x", name: nil); return nil } catch { return error as? AccountError }213        }214        let invalid = await failure(.json(#"{"error":{"code":"telephone_invalide","message":"Entrez un numéro de cellulaire du Canada ou des États-Unis.","param":"phone"}}"#, status: 422))215        #expect(invalid?.code == "telephone_invalide" && invalid?.param == "phone" && AccountFailure(invalid!).on("phone") != nil)216        let unverified = await failure(.error(403, "telephone_non_verifie", "Confirmez d'abord votre numéro."))217        #expect(unverified?.code == "telephone_non_verifie" && unverified?.isUnauthenticated == false)218        let down = await failure(.error(503, "sms_indisponible", "L'envoi de textos n'est pas disponible pour le moment."))219        #expect(down?.code == "sms_indisponible" && down?.errorDescription == "L'envoi de textos n'est pas disponible pour le moment.")220        let limited = await failure(.error(429, "trop_de_tentatives", "Trop de codes demandés.", headers: ["Retry-After": "1800"]))221        #expect(limited?.retryAfter == 1800 && limited?.errorDescription == "Trop de codes demandés. Délai d'attente : 30 min.")222    }223224    @Test("session par téléphone : jeton au coffre, compte sans courriel, seul le mode est mémorisé (jamais le numéro)")225    func session() async throws {226        let name = "immoka.tests.\(UUID().uuidString)"227        let prefs = try #require(UserDefaults(suiteName: name))228        defer { prefs.removePersistentDomain(forName: name) }229        StubServer.install { r in230            if r.path.hasSuffix("/options") { return .json(#"{"email_signup":true,"phone_signup":true}"#) }231            if r.path.hasSuffix("/connexion") { return .json(phoneSession) }232            if r.path.hasSuffix("/synchronisation") { return .json(#"{"items":[],"limit":2000,"skipped":0}"#) }233            if r.path.hasSuffix("/non-lus") { return .json(#"{"unread":0}"#) }234            return .noContent235        }236        let store = MemoryStore()237        let account = Account(library: Library(inMemory: true), store: store, session: StubServer.session(), base: { base }, defaults: prefs)238        #expect(account.lastMode == .email && !account.options.phoneSignup, "avant toute réponse du serveur : courriel seulement")239        await account.loadOptions()240        #expect(account.options.phoneSignup)241        try await account.signIn(.phone("418 555-0123"), password: "Sapin-Bleu-4812")242        #expect(account.isSignedIn && account.user?.isPhoneAccount == true && account.user?.contact == "418 555-0123" && store.string("session.token") == "jeton-tel")243        #expect(account.lastMode == .phone && prefs.string(forKey: Account.modeKey) == "phone")244        #expect(!prefs.dictionaryRepresentation().values.contains { "\($0)".contains("5550123") }, "le numéro n'est jamais gardé dans les préférences")245        #expect(StubServer.seen("POST", "/favoris/synchronisation").count == 1, "un compte par téléphone synchronise ses favoris comme un autre")246        // relance : la session et le compte sans courriel se relisent du coffre247        let again = Account(library: Library(inMemory: true), store: store, session: StubServer.session(), base: { base }, defaults: prefs)248        #expect(again.user?.phone == "+14185550123" && again.user?.email == nil && again.lastMode == .phone)249        await account.signOut()250        #expect(account.lastMode == .phone, "le mode reste mémorisé après la déconnexion")251        try await account.signIn(.email("lea@example.org"), password: "x")252        #expect(account.lastMode == .email)253254        // options : si la requête échoue, le cellulaire n'est plus offert255        StubServer.install { _ in .down }256        await account.loadOptions()257        #expect(!account.options.phoneSignup, "jamais de cellulaire si la requête des options échoue")258        StubServer.install { _ in StubResponse(status: 404, body: Data("<!doctype html>".utf8)) }259        await account.loadOptions()260        #expect(!account.options.phoneSignup, "serveur sans la route : courriel seulement")261    }262}263}264265@Suite("Cellulaire : préproduction et production (réseau)", .serialized)266@MainActor267struct PhoneLiveTests {268    private func failure(_ call: () async throws -> Void) async -> AccountError? {269        do { try await call(); return nil } catch { return error as? AccountError }270    }271    /// Numéro fictif de la plage 418 555-01xx.272    private func number() -> String { String(format: "418 555-01%02d", Int.random(in: 0...99)) }273274    @Test("production, lecture seule : les options du compte répondent, ou les comptes n'y sont pas encore en ligne (aucun compte créé)")275    func productionOptions() async throws {276        let prod = AccountAPI(session: AccountAPI.defaultSession, base: { APIClient.primary }, token: { nil })277        do {278            let o = try await prod.options()279            #expect(o.emailSignup && o.codeLength == 6)280            #expect(!o.phoneSignup || o.phoneCountries.contains("CA"), "si le cellulaire est offert, le Canada l'est")281        } catch let e as AccountError {282            // avant la mise en ligne des comptes : « Route inconnue » devient « comptes pas offerts », jamais un message brut283            #expect(e == .unavailable, "production sans les routes de compte : \(e)")284            let account = Account(library: Library(inMemory: true), store: MemoryStore(), base: { APIClient.primary }, defaults: nil)285            await account.loadOptions()286            #expect(account.options == .fallback && !account.options.phoneSignup, "sans réponse du serveur, le cellulaire n'est pas offert à l'inscription")287        }288    }289290    @Test("préproduction : inscription par texto (424242) → favori → déconnexion → connexion par numéro → mot de passe oublié par texto → suppression")291    func journey() async throws {292        let phone = number(), password = "Sapin-Bleu-\(UInt32.random(in: 1000..<9999))"293        let id = AccountIdentifier.phone(phone)294        let listing = try #require(try await APIClient.shared.search(SearchFilters(), pageSize: 3).listings.first)295        let library = Library(inMemory: true), store = MemoryStore()296        let account = Account(library: library, store: store, base: { AccountLiveTests.base }, defaults: nil)297        await account.loadOptions()298        #expect(account.options.phoneSignup && account.options.phoneCountries == ["CA", "US"])299300        let invalid = await failure { try await account.signUp(.phone("+33 6 12 34 56 78"), password: password, name: "") }301        #expect(invalid?.code == "telephone_invalide" && invalid?.param == "phone" && !(invalid?.errorDescription ?? "").isEmpty)302        let tollFree = await failure { try await account.signUp(.phone("800 555 0123"), password: password, name: "") }303        #expect(tollFree?.code == "telephone_invalide", "numéro sans frais refusé par le serveur")304305        library.toggleFavorite(listing)306        let sent = try await account.signUp(id, password: password, name: "Essai texto iOS")307        #expect(sent.channel == "sms" && sent.phone == id.value && sent.phoneDisplay == id.display && sent.expiresInMin == 10)308        let early = await failure { try await account.signIn(id, password: password) }309        #expect(early?.code == "telephone_non_verifie", "connexion avant vérification : 403 telephone_non_verifie")310        let wrong = await failure { try await account.verify(id, code: "000000") }311        #expect(wrong?.code == "code_invalide")312        try await account.verify(id, code: AccountLiveTests.code)313        let user = try #require(account.user)314        #expect(user.email == nil && user.phone == id.value && user.isPhoneAccount && user.contact == id.display && user.name == "Essai texto iOS" && user.verified)315        #expect(user.role == "acheteur" && user.canUseMessaging, "un compte par téléphone a droit à la messagerie")316        #expect(library.favoriteIDs == [listing.uid] && account.sync.lastError == nil)317        let me = try await account.api.me()318        #expect(me.user.phone == id.value && me.user.email == nil)319320        // déconnexion, puis connexion par numéro + mot de passe (aucun texto), sur un appareil vide321        await account.signOut()322        let libB = Library(inMemory: true)323        let b = Account(library: libB, store: MemoryStore(), base: { AccountLiveTests.base }, defaults: nil)324        let bad = await failure { try await b.signIn(id, password: "pas-le-bon-mot") }325        #expect(bad?.code == "identifiants_invalides" && (bad?.errorDescription ?? "").localizedCaseInsensitiveContains("numéro"))326        try await b.signIn(.phone("+1 (418) 555-01" + phone.suffix(2)), password: password)327        #expect(b.isSignedIn && libB.favoriteIDs == [listing.uid], "autre écriture du même numéro : même compte, favori retrouvé")328329        // mot de passe oublié par texto330        await b.signOut()331        try await b.forgotPassword(id)332        try await b.resetPassword(id, code: AccountLiveTests.code, password: password + "-b")333        #expect(b.isSignedIn && b.user?.phone == id.value)334        let old = await failure { try await account.signIn(id, password: password) }335        #expect(old?.code == "identifiants_invalides", "l'ancien mot de passe ne vaut plus")336337        // suppression338        try await b.deleteAccount(password: password + "-b")339        let gone = await failure { try await b.signIn(id, password: password + "-b") }340        #expect(gone?.code == "identifiants_invalides" && !b.isSignedIn && libB.favoriteIDs == [listing.uid])341    }342}343
Files main
Menu

Theme