SPB Git

Repository Public

MessagingLiveTests.swift 13.3 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKaTests/MessagingLiveTests.swift10// Description      : contrat réel de la messagerie et des gestionnaires11//                    vérifiés, contre la préproduction. Un chercheur jetable12//                    `…@example.org` est créé puis supprimé ; le gestionnaire13//                    d'essai (entreprise « cogir », créé par14//                    Scripts/gestionnaire-essai.sh) répond par l'API. Sans ses15//                    identifiants (LOUKA_MANAGER_EMAIL,16//                    LOUKA_MANAGER_PASSWORD), le test n'est pas lancé.17// Module           : LouKaTests18// Repository       : https://git.spboucher.ai/lou-ka-ios-v319// Project Website  : https://www.lou-ka.com20// Created          : 2026-11-3021// Last Modified    : 2026-11-3022//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation96import Testing97@testable import LouKa9899@Suite("Messagerie : préproduction (réseau)", .serialized)100@MainActor101struct MessagingLiveTests {102    nonisolated static let managerEmail = ProcessInfo.processInfo.environment["LOUKA_MANAGER_EMAIL"] ?? ""103    nonisolated static let managerPassword = ProcessInfo.processInfo.environment["LOUKA_MANAGER_PASSWORD"] ?? ""104    nonisolated static var hasManager: Bool { !managerEmail.isEmpty && !managerPassword.isEmpty }105106    private func failure(_ call: () async throws -> Void) async -> AccountError? {107        do { try await call(); return nil } catch { return error as? AccountError }108    }109110    @Test("gestionnaire vérifié, mot du gestionnaire, fiche publique")111    func publicRoutes() async throws {112        let api = AccountAPI(session: AccountAPI.defaultSession, base: { AccountLiveTests.base }, token: { nil })113        let listing = try #require(try await searchPreprod(source: "cogir").first, "aucun logement cogir en préproduction")114        let info = try await api.listingManager(uid: listing)115        let m = try #require(info.manager)116        #expect(m.sourceID == "cogir" && m.verified && !m.name.isEmpty, "un compte approuvé de cogir rend ses logements « vérifiés »")117        let other = try await api.listingManager(uid: "inconnu:0")118        #expect(other.manager == nil && other.note == nil, "logement sans gestionnaire vérifié : rien à montrer")119        let fiche = try await api.managerFiche(sourceID: "cogir", countView: false)120        #expect(fiche.sourceID == "cogir" && fiche.verified)121        if let c = fiche.content {122            #expect(c.gallery.allSatisfy { $0.image.isSafe } && (c.logo?.isSafe ?? true) && (c.cover?.isSafe ?? true), "les images d'une fiche viennent de /media/pro/")123        }124        let missing = await failure { _ = try await api.managerFiche(sourceID: "gestionnaire-qui-n-existe-pas", countView: false) }125        #expect(missing?.isNotFound == true)126    }127128    /// Logements d'une source en préproduction (l'index de la préproduction n'est pas celui de la production).129    private func searchPreprod(source: String) async throws -> [String] {130        let url = URL(string: AccountLiveTests.base.absoluteString + "/api/v3/search?source=\(source)&limit=5")!131        let (data, _) = try await URLSession.shared.data(from: url)132        let o = try JSONSerialization.jsonObject(with: data) as? [String: Any]133        return ((o?["items"] as? [[String: Any]]) ?? []).compactMap { $0["uid"] as? String }134    }135136    @Test("chercheur écrit → réponse automatique → le gestionnaire répond → non-lus, relève → signalement → archives → fermeture → effacement",137          .enabled(if: MessagingLiveTests.hasManager, "identifiants du gestionnaire d'essai absents : Scripts/gestionnaire-essai.sh"))138    func conversation() async throws {139        let email = "ios-msg-\(Int(Date().timeIntervalSince1970))-\(UInt32.random(in: 0..<100_000))@example.org"140        let password = "Sapin-Bleu-\(UInt32.random(in: 1000..<9999))"141        let name = "Léa Essai \(UInt32.random(in: 1000..<9999))"142        let uid = try #require(try await searchPreprod(source: "cogir").first)143144        // le gestionnaire d'essai, par l'API, comme le ferait le portail145        let mgrSession = try await AccountAPI(session: AccountAPI.defaultSession, base: { AccountLiveTests.base }, token: { nil })146            .signIn(email: MessagingLiveTests.managerEmail, password: MessagingLiveTests.managerPassword)147        let mgrToken = try #require(mgrSession.session?.token)148        #expect(mgrSession.user.isManager && mgrSession.user.manager?.state == .approved && mgrSession.user.manager?.sourceID == "cogir")149        let mgr = AccountAPI(session: AccountAPI.defaultSession, base: { AccountLiveTests.base }, token: { mgrToken })150151        // le chercheur152        let account = Account(library: Library(inMemory: true), store: MemoryStore(), base: { AccountLiveTests.base }, defaults: nil)153        try await account.signUp(email: email, password: password, name: name)154        try await account.verify(email: email, code: AccountLiveTests.code)155        #expect(account.user?.role == "locataire" && account.user?.canStartConversation == true && account.messaging.unread == 0)156        let msg = account.messaging157158        let target = ComposeTarget(uid: uid, sourceID: "cogir", managerName: "Cogir", listing: FavoriteSnapshot(title: "Logement d'essai", city: "Montréal", unitType: "Studio", price: 1200, source: "cogir"))159        let opened = try await msg.open(target, text: "Bonjour, ce logement est-il libre ? **gras** <b>balise</b>")160        let id = opened.conversation.id161        #expect(opened.created == true && opened.conversation.sourceID == "cogir" && opened.conversation.uid == uid && opened.conversation.acceptsReplies)162        #expect(opened.conversation.listing?.title == "Logement d'essai" && opened.conversation.listing?.price == 1200, "l'aperçu envoyé est gardé avec la conversation")163        let mine = try #require(opened.messages.first)164        #expect(mine.mine && mine.role == "locataire" && mine.text == "Bonjour, ce logement est-il libre ? **gras** <b>balise</b>" && mine.createdAt > 1_700_000_000_000,165                "le texte revient tel quel, dates en millisecondes")166        // reprendre la même conversation ne la recrée pas167        let again = try await msg.open(target, text: "Deuxième message")168        #expect(again.created == false && again.conversation.id == id)169170        // côté gestionnaire : la boîte partagée montre le chercheur par son nom, jamais son courriel171        let inbox = try await mgr.conversations()172        let seen = try #require(inbox.items.first { $0.id == id })173        #expect(seen.tenantName == name && seen.unread)174        let asManager = await failure { _ = try await mgr.openConversation(uid: nil, sourceID: "cogir", text: "x", listing: nil) }175        #expect(asManager?.code == "reserve_aux_locataires", "le serveur refuse aussi qu'un gestionnaire ouvre une conversation")176        let reply = try await mgr.reply(id, text: "Oui, il est libre. Visite jeudi ?")177178        // le chercheur : pastille, boîte, relève des seuls nouveaux messages, lecture179        #expect(try await account.api.unreadCount() == 1)180        let list = try await msg.conversations(archived: false)181        #expect(list.first { $0.id == id }?.unread == true && msg.unread == 1 && list.first { $0.id == id }?.lastMessage == "Oui, il est libre. Visite jeudi ?")182        let model = ThreadModel(id: id, messaging: msg)183        await model.load()184        #expect(model.messages.last?.id == reply.id && model.messages.last?.mine == false && model.messages.last?.role == "gestionnaire")185        #expect(try await account.api.unreadCount() == 0, "lire le fil le marque comme lu")186        let second = try await mgr.reply(id, text: "Ou vendredi.")187        await model.poll(active: true)188        #expect(model.messages.last?.id == second.id && Set(model.messages.map(\.id)).count == model.messages.count, "la relève n'ajoute que le nouveau message")189        #expect(await model.send("Jeudi, parfait.") == nil && model.messages.last?.mine == true)190        let tooLong = await failure { _ = try await account.api.reply(id, text: String(repeating: "a", count: 4001)) }191        #expect(tooLong?.code == "message_trop_long")192193        // signaler, archiver (chacun pour soi), fermer, effacer194        try await msg.report(id, reason: "Autre : essai automatisé de l'app iOS", messageID: reply.id)195        let archived = try await msg.setArchived(id, true)196        #expect(archived.archived)197        #expect(try await msg.conversations(archived: false).contains { $0.id == id } == false)198        #expect(try await msg.conversations(archived: true).contains { $0.id == id })199        #expect(try await mgr.conversations().items.contains { $0.id == id }, "l'archive d'un côté ne retire rien de l'autre")200        let closed = try await msg.close(id)201        #expect(closed.isClosed && !closed.acceptsReplies)202        #expect(await model.send("Encore ?") != nil && model.conversation?.acceptsReplies == false)203        let mgrClosed = await failure { _ = try await mgr.reply(id, text: "Encore ?") }204        #expect(mgrClosed?.code == "conversation_fermee")205        try await msg.delete(id)206        let gone = await failure { _ = try await account.api.thread(id) }207        #expect(gone?.isNotFound == true, "conversation effacée : 404")208        let leftInbox = try await mgr.conversations().items.contains { $0.id == id }209        let leftArchives = try await mgr.conversations(archived: true).items.contains { $0.id == id }210        #expect(!leftInbox && !leftArchives, "effacée pour tout le monde")211212        // un logement sans gestionnaire joignable213        let unreachable = await failure { _ = try await msg.open(ComposeTarget(uid: "inconnu:0", sourceID: "", managerName: "", listing: nil), text: "Bonjour") }214        // constaté le 2026-11-30 : 404 `gestionnaire_inconnu` (le contrat annonce 409 `gestionnaire_non_joignable`) ;215        // l'app affiche le message du serveur dans les deux cas216        #expect(["gestionnaire_non_joignable", "gestionnaire_inconnu"].contains(unreachable?.code ?? "") && !(unreachable?.errorDescription ?? "").isEmpty)217218        try await mgr.signOut()219        try await account.deleteAccount(password: password)220        #expect(!account.isSignedIn && account.messaging.unread == 0)221    }222}223
Files main
Menu

Theme