SPB Git

Repository Public

MessagingLiveTests.swift 14.5 KB 235 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKaTests/MessagingLiveTests.swift10// Description      : contrat réel de la messagerie et des courtiers vérifiés,11//                    contre la préproduction. Un acheteur jetable12//                    `…@example.org` est créé puis supprimé ; le courtier13//                    d'essai (courtier 64215753413768 de l'annuaire, créé par14//                    Scripts/courtier-essai.sh) répond par l'API. Sans ses15//                    identifiants (IMMOKA_BROKER_EMAIL,16//                    IMMOKA_BROKER_PASSWORD), le test n'est pas lancé.17// Module           : ImmoKaTests18// Repository       : https://git.spboucher.ai/immo-ka-ios-v319// Project Website  : https://www.immo-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 ImmoKa9899@Suite("Messagerie : préproduction (réseau)", .serialized)100@MainActor101struct MessagingLiveTests {102    nonisolated static let brokerEmail = ProcessInfo.processInfo.environment["IMMOKA_BROKER_EMAIL"] ?? ""103    nonisolated static let brokerPassword = ProcessInfo.processInfo.environment["IMMOKA_BROKER_PASSWORD"] ?? ""104    /// courtier de l'annuaire auquel le compte d'essai est rattaché105    nonisolated static let brokerID = ProcessInfo.processInfo.environment["IMMOKA_BROKER_ID"] ?? "64215753413768"106    nonisolated static var hasBroker: Bool { !brokerEmail.isEmpty && !brokerPassword.isEmpty }107108    private func failure(_ call: () async throws -> Void) async -> AccountError? {109        do { try await call(); return nil } catch { return error as? AccountError }110    }111112    @Test("courtier vérifié, mot du courtier, fiche publique")113    func publicRoutes() async throws {114        let api = AccountAPI(session: AccountAPI.defaultSession, base: { AccountLiveTests.base }, token: { nil })115        let listing = try #require(try await brokerListings().first, "aucune propriété du courtier d'essai en préproduction")116        let info = try await api.listingBroker(uid: listing)117        let m = try #require(info.broker)118        #expect(m.brokerID == MessagingLiveTests.brokerID && m.verified && !m.name.isEmpty && !(m.agency ?? "").isEmpty, "un compte approuvé rend les propriétés du courtier « vérifiées »")119        let other = try await api.listingBroker(uid: "inconnu:0")120        #expect(other.broker == nil && other.note == nil, "propriété inconnue : rien à montrer")121        let fiche = try await api.brokerFiche(brokerID: MessagingLiveTests.brokerID, countView: false)122        #expect(fiche.brokerID == MessagingLiveTests.brokerID && fiche.verified)123        if let c = fiche.content {124            #expect(c.gallery.allSatisfy { $0.image.isSafe } && (c.logo?.isSafe ?? true) && (c.cover?.isSafe ?? true), "les images d'une fiche viennent de /media/pro/")125        }126        let missing = await failure { _ = try await api.brokerFiche(brokerID: "999", countView: false) }127        #expect(missing?.isNotFound == true)128    }129130    /// Propriétés du courtier d'essai en préproduction, d'après l'annuaire (`/api/v3/brokers/{id}`). L'annuaire nomme131    /// aussi des inscriptions regroupées avec une autre (404 `duplicate`, en-tête Location) : la fiche gardée est suivie.132    private func brokerListings() async throws -> [String] {133        let url = URL(string: AccountLiveTests.base.absoluteString + "/api/v3/brokers/\(MessagingLiveTests.brokerID)")!134        let (data, _) = try await URLSession.shared.data(from: url)135        let d = try JSONDecoder().decode(BrokerDetail.self, from: data)136        #expect(d.id == MessagingLiveTests.brokerID, "l'identifiant de l'annuaire est celui des comptes de courtier (broker_id)")137        for l in d.listings.prefix(12) {138            let u = URL(string: AccountLiveTests.base.absoluteString + "/api/v3/listings/" + AccountAPI.pathComponent(l.uid))!139            guard let (_, r) = try? await URLSession.shared.data(from: u), let http = r as? HTTPURLResponse else { continue }140            if http.statusCode == 200 { return [l.uid] }141            var headers: [String: String] = [:]142            for (k, v) in http.allHeaderFields { if let k = k as? String, let v = v as? String { headers[k] = v } }143            if let kept = APIClient.regroupedUID(headers: headers) { return [kept] }144        }145        return []146    }147148    @Test("acheteur écrit → réponse automatique → le courtier répond → non-lus, relève → signalement → archives → fermeture → effacement",149          .enabled(if: MessagingLiveTests.hasBroker, "identifiants du courtier d'essai absents : Scripts/courtier-essai.sh"))150    func conversation() async throws {151        let email = "ios-msg-\(Int(Date().timeIntervalSince1970))-\(UInt32.random(in: 0..<100_000))@example.org"152        let password = "Sapin-Bleu-\(UInt32.random(in: 1000..<9999))"153        let name = "Léa Essai \(UInt32.random(in: 1000..<9999))"154        let uid = try #require(try await brokerListings().first)155156        // le courtier d'essai, par l'API, comme le ferait le portail157        let mgrSession = try await AccountAPI(session: AccountAPI.defaultSession, base: { AccountLiveTests.base }, token: { nil })158            .signIn(email: MessagingLiveTests.brokerEmail, password: MessagingLiveTests.brokerPassword)159        let mgrToken = try #require(mgrSession.session?.token)160        #expect(mgrSession.user.isBroker && mgrSession.user.broker?.state == .approved && mgrSession.user.broker?.brokerID == MessagingLiveTests.brokerID && !(mgrSession.user.broker?.agency ?? "").isEmpty)161        let mgr = AccountAPI(session: AccountAPI.defaultSession, base: { AccountLiveTests.base }, token: { mgrToken })162163        // l'acheteur164        let account = Account(library: Library(inMemory: true), store: MemoryStore(), base: { AccountLiveTests.base }, defaults: nil)165        try await account.signUp(email: email, password: password, name: name)166        try await account.verify(email: email, code: AccountLiveTests.code)167        #expect(account.user?.role == "acheteur" && account.user?.canStartConversation == true && account.messaging.unread == 0)168        let msg = account.messaging169170        let target = ComposeTarget(uid: uid, brokerID: MessagingLiveTests.brokerID, brokerName: "Simon Lacasse", listing: FavoriteSnapshot(title: "Propriété d'essai", city: "Amherst", propertyType: "Maison", price: 749_900, source: "remax_quebec"))171        let opened = try await msg.open(target, text: "Bonjour, cette propriété est-elle toujours à vendre ? **gras** <b>balise</b>")172        let id = opened.conversation.id173        #expect(opened.created == true && opened.conversation.brokerID == MessagingLiveTests.brokerID && opened.conversation.uid == uid && opened.conversation.acceptsReplies)174        #expect(opened.conversation.listing?.title == "Propriété d'essai" && opened.conversation.listing?.propertyType == "Maison" && opened.conversation.listing?.price == 749_900, "l'aperçu envoyé est gardé avec la conversation")175        let mine = try #require(opened.messages.first)176        #expect(mine.mine && mine.role == "acheteur" && mine.text == "Bonjour, cette propriété est-elle toujours à vendre ? **gras** <b>balise</b>" && mine.createdAt > 1_700_000_000_000,177                "le texte revient tel quel, dates en millisecondes")178        // reprendre la même conversation ne la recrée pas179        let again = try await msg.open(target, text: "Deuxième message")180        #expect(again.created == false && again.conversation.id == id)181182        // côté courtier : la boîte partagée montre l'acheteur par son nom, jamais son courriel183        let inbox = try await mgr.conversations()184        let seen = try #require(inbox.items.first { $0.id == id })185        #expect(seen.tenantName == name && seen.unread)186        let asBroker = await failure { _ = try await mgr.openConversation(uid: nil, brokerID: MessagingLiveTests.brokerID, text: "x", listing: nil) }187        #expect(asBroker?.code == "reserve_aux_acheteurs", "le serveur refuse aussi qu'un courtier ouvre une conversation")188        let reply = try await mgr.reply(id, text: "Oui, elle est toujours à vendre. Visite jeudi ?")189190        // l'acheteur : pastille, boîte, relève des seuls nouveaux messages, lecture191        #expect(try await account.api.unreadCount() == 1)192        let list = try await msg.conversations(archived: false)193        #expect(list.first { $0.id == id }?.unread == true && msg.unread == 1 && list.first { $0.id == id }?.lastMessage == "Oui, elle est toujours à vendre. Visite jeudi ?")194        let model = ThreadModel(id: id, messaging: msg)195        await model.load()196        #expect(model.messages.last?.id == reply.id && model.messages.last?.mine == false && model.messages.last?.role == "courtier")197        #expect(try await account.api.unreadCount() == 0, "lire le fil le marque comme lu")198        let second = try await mgr.reply(id, text: "Ou vendredi.")199        await model.poll(active: true)200        #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")201        #expect(await model.send("Jeudi, parfait.") == nil && model.messages.last?.mine == true)202        let tooLong = await failure { _ = try await account.api.reply(id, text: String(repeating: "a", count: 4001)) }203        #expect(tooLong?.code == "message_trop_long")204205        // signaler, archiver (chacun pour soi), fermer, effacer206        try await msg.report(id, reason: "Autre : essai automatisé de l'app iOS", messageID: reply.id)207        let archived = try await msg.setArchived(id, true)208        #expect(archived.archived)209        #expect(try await msg.conversations(archived: false).contains { $0.id == id } == false)210        #expect(try await msg.conversations(archived: true).contains { $0.id == id })211        #expect(try await mgr.conversations().items.contains { $0.id == id }, "l'archive d'un côté ne retire rien de l'autre")212        let closed = try await msg.close(id)213        #expect(closed.isClosed && !closed.acceptsReplies)214        #expect(await model.send("Encore ?") != nil && model.conversation?.acceptsReplies == false)215        let mgrClosed = await failure { _ = try await mgr.reply(id, text: "Encore ?") }216        #expect(mgrClosed?.code == "conversation_fermee")217        try await msg.delete(id)218        let gone = await failure { _ = try await account.api.thread(id) }219        #expect(gone?.isNotFound == true, "conversation effacée : 404")220        let leftInbox = try await mgr.conversations().items.contains { $0.id == id }221        let leftArchives = try await mgr.conversations(archived: true).items.contains { $0.id == id }222        #expect(!leftInbox && !leftArchives, "effacée pour tout le monde")223224        // une propriété sans courtier joignable225        let unreachable = await failure { _ = try await msg.open(ComposeTarget(uid: "inconnu:0", brokerID: "", brokerName: "", listing: nil), text: "Bonjour") }226        // constaté le 2026-11-30 : 404 `courtier_inconnu` (le contrat annonce 409 `courtier_non_joignable`) ;227        // l'app affiche le message du serveur dans les deux cas228        #expect(["courtier_non_joignable", "courtier_inconnu"].contains(unreachable?.code ?? "") && !(unreachable?.errorDescription ?? "").isEmpty)229230        try await mgr.signOut()231        try await account.deleteAccount(password: password)232        #expect(!account.isSignedIn && account.messaging.unread == 0)233    }234}235
Files main
Menu

Theme