SPB Git

Repository Public

AccountLiveTests.swift 12.7 KB 224 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKaTests/AccountLiveTests.swift10// Description      : contrat réel de l'API de compte, contre la préproduction11//                    (aucun courriel n'y est envoyé, le code vaut toujours12//                    424242). Un compte jetable `…@example.org` est créé puis13//                    supprimé. Adresse : `LOUKA_ACCOUNT_BASE_URL`, sinon la14//                    préproduction.15// Module           : LouKaTests16// Repository       : https://git.spboucher.ai/lou-ka-ios-v317// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-3019// Last Modified    : 2026-11-3020//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import Testing95@testable import LouKa9697@Suite("API de compte : préproduction (réseau)", .serialized)98@MainActor99struct AccountLiveTests {100    nonisolated static let base = URL(string: ProcessInfo.processInfo.environment["LOUKA_ACCOUNT_BASE_URL"] ?? "https://louka-comptes.51-161-112-61.sslip.io")!101    nonisolated static let code = "424242"102103    private func account(_ library: Library, store: any SecretStore = MemoryStore()) -> Account {104        Account(library: library, store: store, base: { AccountLiveTests.base }, defaults: nil)105    }106    private func address(_ tag: String) -> String { "ios-\(tag)-\(Int(Date().timeIntervalSince1970))-\(UInt32.random(in: 0..<100_000))@example.org" }107    private func failure(_ call: () async throws -> Void) async -> AccountError? {108        do { try await call(); return nil } catch { return error as? AccountError }109    }110111    @Test("inscription → code → favori → déconnexion → reconnexion sur un autre appareil → favori retrouvé → suppression")112    func fullJourney() async throws {113        let email = address("parcours"), password = "Sapin-Bleu-\(UInt32.random(in: 1000..<9999))"114        // un vrai logement, pour un aperçu réel115        let listing = try #require(try await APIClient.shared.search(SearchFilters(), limit: 3).items.first)116117        // appareil A : un favori local avant tout compte118        let libA = Library(inMemory: true), storeA = MemoryStore()119        let a = account(libA, store: storeA)120        libA.toggleFavorite(listing)121        try await a.signUp(email: email, password: password, name: "Essai iOS")122        #expect(!a.isSignedIn, "l'inscription n'ouvre pas de session avant le code")123        let early = await failure { try await a.signIn(email: email, password: password) }124        #expect(early?.code == "courriel_non_verifie", "connexion avant vérification : 403 courriel_non_verifie")125        let wrongCode = await failure { try await a.verify(email: email, code: "000000") }126        #expect(wrongCode?.code == "code_invalide" && !(wrongCode?.errorDescription ?? "").isEmpty)127        try await a.resendCode(email: email)128        try await a.verify(email: email, code: AccountLiveTests.code)129        #expect(a.isSignedIn && a.user?.email == email && a.user?.name == "Essai iOS" && a.user?.verified == true)130        #expect((storeA.string("session.token") ?? "").count >= 32)131        #expect(a.sync.lastError == nil && libA.favoriteIDs == [listing.uid], "la mémoire locale est montée au compte")132133        // note, deuxième favori dont l'uid contient « / », recherche enregistrée134        libA.favorite(listing.uid)?.note = "à visiter"135        libA.noteChanged(listing.uid)136        let odd = try JSONDecoder().decode(Listing.self, from: Data(#"{"uid":"essai:ios/chemin-1","source":"essai","title":"Uid à barre oblique","city":"Québec","unit_type":"3½","price":1234}"#.utf8))137        libA.toggleFavorite(odd)138        var f = SearchFilters(); f.city = "Montréal"; f.rooms = [4]; f.priceMax = 1800; f.features = ["balcony"]139        libA.saveSearch(f, sort: .prix, total: 99)140        await a.sync.settle()141        let onServer = try await a.api.favorites()142        #expect(Set(onServer.items.map(\.uid)) == [listing.uid, "essai:ios/chemin-1"], "l'uid arrive tel quel, « / » compris")143        let kept = try #require(onServer.items.first { $0.uid == listing.uid })144        #expect(kept.note == "à visiter" && kept.snapshot?.title == listing.displayTitle && kept.snapshot?.source == listing.source)145        #expect(kept.savedAt > 1_700_000_000_000 && (kept.updatedAt ?? 0) >= kept.savedAt, "dates en millisecondes")146        let remoteSearch = try #require(try await a.api.searches().items.first)147        #expect(remoteSearch.origin == "ios" && remoteSearch.query == "city=Montr%C3%A9al&price_max=1800&rooms=4&sort=prix&with=balcony" && remoteSearch.lastTotal == 99)148149        // compte : nom, appareils150        try await a.rename("Essai renommé")151        #expect(a.user?.name == "Essai renommé")152        let me = try await a.api.me()153        #expect(me.user.name == "Essai renommé" && me.session?.client == "ios" && me.session?.token == nil)154155        // déconnexion : la mémoire reste, l'ancien jeton ne vaut plus rien156        let oldToken = try #require(storeA.string("session.token"))157        await a.signOut()158        #expect(!a.isSignedIn && storeA.string("session.token") == nil && libA.favoriteIDs.count == 2)159        let stale = AccountAPI(session: AccountAPI.defaultSession, base: { AccountLiveTests.base }, token: { oldToken })160        let afterSignOut = await failure { _ = try await stale.favorites() }161        #expect(afterSignOut?.isUnauthenticated == true, "401 non_authentifie après la déconnexion")162163        // appareil B, vide : la reconnexion ramène favoris (affichés par leur aperçu), note et recherche164        let libB = Library(inMemory: true)165        let b = account(libB)166        let badPassword = await failure { try await b.signIn(email: email, password: "pas-le-bon-mot") }167        #expect(badPassword?.code == "identifiants_invalides" && !b.isSignedIn)168        try await b.signIn(email: email, password: password)169        #expect(libB.favoriteIDs == [listing.uid, "essai:ios/chemin-1"])170        let back = try #require(libB.favorite(listing.uid))171        #expect(back.note == "à visiter" && back.displayTitle == listing.displayTitle && back.unitType == listing.unitType && back.image == listing.images.first)172        let search = try #require(libB.allSearches().first)173        #expect(search.filters == f && search.sort == .prix && search.lastTotal == 99 && search.origin == "ios")174175        // retrait sur B, puis A se reconnecte : le favori retiré ailleurs ne revient pas, même s'il est encore en mémoire sur A176        libB.removeFavorite("essai:ios/chemin-1")177        libB.delete(search)178        await b.sync.settle()179        #expect(b.sync.pending.isEmpty)180        try await a.signIn(email: email, password: password)181        #expect(libA.favoriteIDs == [listing.uid], "retiré sur un autre appareil après la dernière modification locale : reste retiré")182        #expect(libA.allSearches().isEmpty)183        let devices = try await a.devices()184        #expect(devices.count == 2 && devices.filter(\.current).count == 1 && devices.allSatisfy { $0.client == "ios" })185        #expect(try await a.signOutEverywhereElse() == 1)186        await b.sync.sync()187        #expect(!b.isSignedIn && b.sessionEnded && libB.favoriteIDs == [listing.uid], "B, déconnecté à distance, repasse à l'état déconnecté sans rien perdre")188189        // mot de passe : changement, puis oubli et réinitialisation par code190        let wrongCurrent = await failure { try await a.changePassword(current: "pas-le-bon-mot", new: password + "-b") }191        #expect(wrongCurrent?.code == "mot_de_passe_incorrect" && a.isSignedIn)192        let tooShort = await failure { try await a.changePassword(current: password, new: "court") }193        #expect(tooShort?.code == "mot_de_passe_trop_court" && tooShort?.param != nil)194        try await a.changePassword(current: password, new: password + "-b")195        await a.signOut()196        try await a.forgotPassword(email: email)197        try await a.resetPassword(email: email, code: AccountLiveTests.code, password: password + "-c")198        #expect(a.isSignedIn && libA.favoriteIDs == [listing.uid])199200        // suppression du compte : mot de passe exigé ; ensuite plus de connexion possible, la mémoire locale reste201        let refused = await failure { try await a.deleteAccount(password: "pas-le-bon-mot") }202        #expect(refused?.code == "mot_de_passe_incorrect" && a.isSignedIn)203        try await a.deleteAccount(password: password + "-c")204        #expect(!a.isSignedIn && libA.favoriteIDs == [listing.uid])205        let gone = await failure { try await a.signIn(email: email, password: password + "-c") }206        #expect(gone?.code == "identifiants_invalides")207    }208209    @Test("validation du serveur : messages en français prêts à afficher, champ fautif")210    func validation() async throws {211        let a = account(Library(inMemory: true))212        let short = await failure { try await a.signUp(email: address("court"), password: "court", name: "") }213        #expect(short?.code == "mot_de_passe_trop_court" && short?.param == "password" && (short?.errorDescription ?? "").contains("8"))214        let simple = await failure { try await a.signUp(email: address("simple"), password: "password", name: "") }215        #expect(simple?.code == "mot_de_passe_trop_simple")216        let mail = await failure { try await a.signUp(email: "pas-une-adresse", password: "Sapin-Bleu-4812", name: "") }217        #expect(mail?.code == "courriel_invalide" && mail?.param == "email")218        // adresse inconnue : même réponse 202 que pour une adresse connue (pas d'énumération)219        try await a.forgotPassword(email: address("inconnu"))220        let anonymous = await failure { _ = try await a.api.favorites() }221        #expect(anonymous?.isUnauthenticated == true)222    }223}224
Files main
Menu

Theme