Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka iOS9// File : ImmoKaTests/AccountTests.swift10// Description : comptes (3.1.0) — client d'API de compte contre un serveur11// simulé (`URLProtocol`), session et trousseau,12// synchronisation des favoris et des recherches (fusion,13// retraits en attente), chaîne de requête des recherches14// enregistrées.15// Module : ImmoKaTests16// Repository : https://git.spboucher.ai/immo-ka-ios-v317// Project Website : https://www.immo-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 Security95import Testing96@testable import ImmoKa9798// MARK: - Serveur simulé99100/// Requête vue par le serveur simulé.101struct SeenRequest: Sendable {102 var method: String103 var url: String104 var path: String105 var headers: [String: String]106 var body: Data107 var json: [String: Any] { (try? JSONSerialization.jsonObject(with: body) as? [String: Any]) ?? [:] }108}109110struct StubResponse: Sendable {111 var status = 200112 var headers: [String: String] = [:]113 var body = Data()114 /// échec de transport (hors ligne)115 var offline = false116 static func json(_ s: String, status: Int = 200, headers: [String: String] = [:]) -> StubResponse {117 StubResponse(status: status, headers: headers, body: Data(s.utf8))118 }119 static let noContent = StubResponse(status: 204)120 static let down = StubResponse(offline: true)121 static func error(_ status: Int, _ code: String, _ message: String, headers: [String: String] = [:]) -> StubResponse {122 .json(#"{"error":{"code":"\#(code)","message":"\#(message)","request_id":"r1"}}"#, status: status, headers: headers)123 }124}125126final class StubServer: URLProtocol, @unchecked Sendable {127 private static let lock = NSLock()128 nonisolated(unsafe) private static var handler: (@Sendable (SeenRequest) -> StubResponse)?129 nonisolated(unsafe) private static var log: [SeenRequest] = []130131 static func install(_ h: @escaping @Sendable (SeenRequest) -> StubResponse) {132 lock.withLock { handler = h; log = [] }133 }134 static var seen: [SeenRequest] { lock.withLock { log } }135 static func seen(_ method: String, _ suffix: String) -> [SeenRequest] { seen.filter { $0.method == method && $0.path.hasSuffix(suffix) } }136137 static func session() -> URLSession {138 let cfg = URLSessionConfiguration.ephemeral139 cfg.protocolClasses = [StubServer.self]140 return URLSession(configuration: cfg)141 }142143 override class func canInit(with request: URLRequest) -> Bool { true }144 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }145 override func stopLoading() {}146147 override func startLoading() {148 var body = request.httpBody ?? Data()149 if let stream = request.httpBodyStream {150 stream.open()151 var buf = [UInt8](repeating: 0, count: 4096)152 while stream.hasBytesAvailable {153 let n = stream.read(&buf, maxLength: buf.count)154 if n <= 0 { break }155 body.append(buf, count: n)156 }157 stream.close()158 }159 let seen = SeenRequest(method: request.httpMethod ?? "GET", url: request.url?.absoluteString ?? "",160 path: request.url?.path(percentEncoded: true) ?? "", headers: request.allHTTPHeaderFields ?? [:], body: body)161 let h = StubServer.lock.withLock { () -> (@Sendable (SeenRequest) -> StubResponse)? in162 StubServer.log.append(seen)163 return StubServer.handler164 }165 let r = h?(seen) ?? StubResponse(status: 500)166 if r.offline {167 client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet))168 return169 }170 let resp = HTTPURLResponse(url: request.url!, statusCode: r.status, httpVersion: "HTTP/1.1", headerFields: r.headers)!171 client?.urlProtocol(self, didReceive: resp, cacheStoragePolicy: .notAllowed)172 client?.urlProtocol(self, didLoad: r.body)173 client?.urlProtocolDidFinishLoading(self)174 }175}176177final class Counter: @unchecked Sendable {178 private let lock = NSLock(); private var n = 0179 func next() -> Int { lock.withLock { n += 1; return n } }180}181182private let stubBase = URL(string: "https://compte.test")!183private let sessionJSON = #"{"user":{"id":"u1","email":"lea@example.org","name":"Léa","verified":true,"created_at":1796000000,"role":"acheteur","futur":{"x":1}},"session":{"expires_at":1803776000,"token":"jeton-secret-1"}}"#184185private func sampleListing(_ uid: String = "duproprio:abc/123", price: Int = 450_000) throws -> Listing {186 let json = #"{"uid":"\#(uid)","source":"duproprio","title":"123, rue des Érables, Gatineau","address":"123, rue des Érables","city":"Gatineau","sector":"Aylmer","ptype":"Maison","price":\#(price),"images":["https://img.example.org/a.jpg"],"lat":45.39,"lng":-75.84,"area_sqft":1820}"#187 return try JSONDecoder().decode(Listing.self, from: Data(json.utf8))188}189190@MainActor191private func makeAccount(_ library: Library, store: any SecretStore = MemoryStore()) -> Account {192 Account(library: library, store: store, session: StubServer.session(), base: { stubBase }, defaults: nil)193}194195// MARK: - Client d'API196197/// Les deux suites partagent le serveur simulé : elles s'exécutent l'une après l'autre.198@Suite("Compte (serveur simulé)", .serialized)199enum StubbedAccountTests {}200201extension StubbedAccountTests {202@Suite("Compte : client d'API")203struct AccountAPITests {204 private func api(token: String? = nil) -> AccountAPI {205 AccountAPI(session: StubServer.session(), base: { stubBase }, token: { token })206 }207208 @Test("connexion : en-têtes, corps, session décodée, champs inconnus tolérés")209 func signIn() async throws {210 StubServer.install { _ in .json(sessionJSON) }211 let s = try await api(token: "ancien").signIn(email: "lea@example.org", password: "Sapin-Bleu-4812")212 #expect(s.session?.token == "jeton-secret-1" && s.user.email == "lea@example.org" && s.user.name == "Léa")213 #expect(s.user.role == "acheteur", "le rôle à venir est déjà lu")214 let r = try #require(StubServer.seen.first)215 #expect(r.method == "POST" && r.url == "https://compte.test/api/v3/compte/connexion")216 #expect(r.headers["X-ImmoKa-Client"] == "ios" && r.headers["Content-Type"] == "application/json")217 #expect(r.headers["Authorization"] == nil, "la connexion ne porte aucun jeton")218 #expect(r.json["email"] as? String == "lea@example.org" && r.json["password"] as? String == "Sapin-Bleu-4812")219 #expect(r.json["name"] == nil && r.json["code"] == nil, "les champs absents ne sont pas envoyés")220 }221222 @Test("utilisateur minimal : seuls id et courriel sont exigés")223 func minimalUser() throws {224 let u = try JSONDecoder().decode(AccountUser.self, from: Data(#"{"id":"u2","email":"a@example.org"}"#.utf8))225 #expect(u.name.isEmpty && u.verified && u.role == nil && u.displayName == "a@example.org")226 }227228 @Test("routes authentifiées : jeton Bearer, écriture sans corps envoyée avec {}")229 func bearer() async throws {230 StubServer.install { r in r.path.hasSuffix("/sessions") ? .json(#"{"items":[{"id":"s1","client":"ios","agent":"ImmoKa","created_at":1,"seen_at":2,"current":true},{"id":"s2","client":"web","current":false}]}"#) : .json(#"{"revoked":1}"#) }231 let a = api(token: "jeton-secret-1")232 let devices = try await a.sessions()233 #expect(devices.count == 2 && devices[0].current && devices[1].clientLabel == "Site web")234 #expect(try await a.signOutEverywhereElse() == 1)235 #expect(StubServer.seen.allSatisfy { $0.headers["Authorization"] == "Bearer jeton-secret-1" && $0.headers["X-ImmoKa-Client"] == "ios" })236 let post = try #require(StubServer.seen("POST", "/deconnexion-partout").first)237 #expect(String(data: post.body, encoding: .utf8) == "{}" && post.headers["Content-Type"] == "application/json")238 }239240 @Test("favoris : l'uid s'écrit tel quel dans le chemin (« : » et « / » non encodés)")241 func favoritePaths() async throws {242 StubServer.install { r in r.method == "DELETE" ? .noContent : .json(#"{"uid":"x","saved_at":1796000000000,"note":"","snapshot":{},"updated_at":1796000000001}"#) }243 let a = api(token: "t")244 try await a.putFavorite(RemoteFavorite(uid: "duproprio:abc/123", savedAt: 1_796_000_000_000, note: "près du métro",245 snapshot: FavoriteSnapshot(title: "Maison", price: 450_000, areaSqft: 1820)))246 try await a.deleteFavorite("centris:9 a?b#c")247 let put = try #require(StubServer.seen.first)248 #expect(put.method == "PUT" && put.url == "https://compte.test/api/v3/compte/favoris/duproprio:abc/123")249 #expect(!put.url.contains("%2F") && !put.url.contains("%3A"))250 #expect(put.json["saved_at"] as? Int == 1_796_000_000_000 && put.json["note"] as? String == "près du métro")251 let snap = try #require(put.json["snapshot"] as? [String: Any])252 #expect(snap["title"] as? String == "Maison" && snap["price"] as? Double == 450_000 && snap["area_sqft"] as? Double == 1820)253 #expect(snap["city"] == nil, "un champ d'aperçu absent n'est pas envoyé")254 let del = try #require(StubServer.seen.last)255 #expect(del.method == "DELETE" && del.url == "https://compte.test/api/v3/compte/favoris/centris:9%20a%3Fb%23c",256 "seuls les caractères interdits dans un chemin sont encodés")257 }258259 @Test("synchronisation : items et removed, dates en millisecondes, liste fusionnée décodée")260 func syncBody() async throws {261 StubServer.install { _ in .json(#"{"items":[{"uid":"a:1","saved_at":1796000000000.0,"note":"n","snapshot":{"title":"T","price":"1299","ptype":"3½"},"updated_at":1796000000500}],"limit":2000,"server_time":1796000001000,"skipped":0}"#) }262 let out = try await api(token: "t").syncFavorites(items: [RemoteFavorite(uid: "a:1", savedAt: 1_796_000_000_000, note: "n", snapshot: FavoriteSnapshot(title: "T"), updatedAt: 1_796_000_000_500)],263 removed: [RemovedFavorite(uid: "b:2", at: 1_796_000_000_700)])264 let r = try #require(StubServer.seen.first)265 #expect(r.method == "POST" && r.path == "/api/v3/compte/favoris/synchronisation")266 let items = try #require(r.json["items"] as? [[String: Any]]), removed = try #require(r.json["removed"] as? [[String: Any]])267 #expect(items[0]["uid"] as? String == "a:1" && items[0]["updated_at"] as? Int == 1_796_000_000_500)268 #expect(removed[0]["uid"] as? String == "b:2" && removed[0]["at"] as? Int == 1_796_000_000_700)269 #expect(out.items[0].savedAt == 1_796_000_000_000 && out.items[0].snapshot?.price == 1299 && out.items[0].snapshot?.propertyType == "3½",270 "date en nombre à virgule et prix en chaîne sont tolérés")271 #expect(out.serverTime == 1_796_000_001_000)272 }273274 @Test("recherches : origin ios, identifiant dans le chemin")275 func searches() async throws {276 StubServer.install { _ in .json(#"{"id":"A-1","label":"L","query":"city=Laval","origin":"ios","saved_at":5,"last_total":null,"last_visit":null,"updated_at":6}"#) }277 let s = try await api(token: "t").putSearch(RemoteSearch(id: "A-1", label: "L", query: "city=Laval", savedAt: 5, lastTotal: 12))278 #expect(s.origin == "ios" && s.lastTotal == nil && s.updatedAt == 6)279 let r = try #require(StubServer.seen.first)280 #expect(r.url == "https://compte.test/api/v3/compte/recherches/A-1" && r.json["origin"] as? String == "ios" && r.json["last_total"] as? Int == 12)281 }282283 @Test("erreurs structurées : message du serveur, champ, 429 et Retry-After, 401, serveur sans comptes, hors ligne")284 func errors() async throws {285 let a = api(token: "t")286 func failure(_ r: StubResponse) async -> AccountError? {287 StubServer.install { _ in r }288 do { _ = try await a.signIn(email: "a@example.org", password: "x"); return nil } catch { return error as? AccountError }289 }290 let invalid = await failure(.json(#"{"error":{"code":"mot_de_passe_trop_court","message":"Le mot de passe doit compter au moins 8 caractères.","param":"password","request_id":"r"}}"#, status: 422))291 #expect(invalid?.code == "mot_de_passe_trop_court" && invalid?.param == "password")292 #expect(invalid?.errorDescription == "Le mot de passe doit compter au moins 8 caractères.")293 let unverified = await failure(.error(403, "courriel_non_verifie", "Confirmez d'abord votre adresse courriel."))294 #expect(unverified?.code == "courriel_non_verifie")295 let limited = await failure(.error(429, "trop_de_tentatives", "Trop de tentatives.", headers: ["Retry-After": "45"]))296 #expect(limited?.retryAfter == 45 && limited?.errorDescription == "Trop de tentatives. Délai d'attente : 45 s.")297 let long = await failure(.error(429, "trop_de_tentatives", "Trop de tentatives.", headers: ["Retry-After": "600"]))298 #expect(long?.errorDescription == "Trop de tentatives. Délai d'attente : 10 min.")299 let bare = await failure(StubResponse(status: 429, headers: ["Retry-After": "30"], body: Data("<html>".utf8)))300 #expect(bare?.code == "trop_de_tentatives" && bare?.retryAfter == 30)301 let expired = await failure(.error(401, "non_authentifie", "Connectez-vous pour continuer."))302 #expect(expired?.isUnauthenticated == true)303 let wrong = await failure(.error(401, "identifiants_invalides", "Adresse courriel ou mot de passe incorrect."))304 #expect(wrong?.isUnauthenticated == false, "un mauvais mot de passe ne ferme pas une session")305 #expect(await failure(.error(405, "method_not_allowed", "Method Not Allowed")) == .unavailable, "production sans les routes de compte")306 #expect(await failure(StubResponse(status: 404, body: Data("<html>".utf8))) == .unavailable)307 #expect(await failure(StubResponse(status: 502, body: Data("<html>".utf8))) == .http(502))308 #expect(await failure(.down) == .offline)309 #expect(await failure(.json("pas du json")) == .decoding)310 }311312 @Test("limiteur général (rate_limited, délai court) : la requête est rejouée d'elle-même ; trop_de_tentatives ne l'est jamais")313 func autoRetry() async throws {314 let counter = Counter()315 StubServer.install { _ in counter.next() == 1 ? .error(429, "rate_limited", "Trop de requêtes.", headers: ["Retry-After": "1"]) : .json(sessionJSON) }316 let s = try await api().signIn(email: "a@example.org", password: "x")317 #expect(s.user.id == "u1" && StubServer.seen.count == 2)318 StubServer.install { _ in .error(429, "rate_limited", "Trop de requêtes.", headers: ["Retry-After": "120"]) }319 await #expect(throws: AccountError.self) { _ = try await api().signIn(email: "a@example.org", password: "x") }320 #expect(StubServer.seen.count == 1, "un long délai n'est pas attendu en silence")321 StubServer.install { _ in .error(429, "trop_de_tentatives", "Trop de tentatives.", headers: ["Retry-After": "1"]) }322 await #expect(throws: AccountError.self) { _ = try await api().signIn(email: "a@example.org", password: "x") }323 #expect(StubServer.seen.count == 1)324 }325}326327}328329// MARK: - Session et synchronisation330331extension StubbedAccountTests {332@Suite("Compte : session et synchronisation")333@MainActor334struct AccountSessionTests {335 /// Serveur simulé minimal : garde les favoris comme le vrai (la liste fusionnée fait foi).336 final class FakeServer: @unchecked Sendable {337 private let lock = NSLock()338 private var favorites: [String: String] = [:] // uid → JSON de l'élément339 var offline = false340 var expired = false341 func seed(_ uid: String, json: String) { lock.withLock { favorites[uid] = json } }342 var uids: Set<String> { lock.withLock { Set(favorites.keys) } }343344 func handle(_ r: SeenRequest) -> StubResponse {345 lock.withLock { () -> StubResponse in346 if offline { return .down }347 if r.path.hasSuffix("/connexion") || r.path.hasSuffix("/verification") { return .json(sessionJSON) }348 if expired { return .error(401, "non_authentifie", "Connectez-vous pour continuer.") }349 if r.path.hasSuffix("/deconnexion") || r.path.hasSuffix("/suppression") { return .noContent }350 if r.path.hasSuffix("/recherches/synchronisation") { return .json(#"{"items":[],"limit":100,"skipped":0}"#) }351 if r.path.hasSuffix("/favoris/synchronisation") {352 for it in (r.json["items"] as? [[String: Any]]) ?? [] {353 guard let uid = it["uid"] as? String, favorites[uid] == nil, let d = try? JSONSerialization.data(withJSONObject: it) else { continue }354 favorites[uid] = String(data: d, encoding: .utf8)355 }356 for rm in (r.json["removed"] as? [[String: Any]]) ?? [] { if let uid = rm["uid"] as? String { favorites[uid] = nil } }357 return .json(#"{"items":[\#(favorites.values.sorted().joined(separator: ","))],"limit":2000,"server_time":1,"skipped":0}"#)358 }359 if let range = r.path.range(of: "/favoris/") {360 let uid = String(r.path[range.upperBound...]).removingPercentEncoding ?? ""361 if r.method == "DELETE" { favorites[uid] = nil; return .noContent }362 var it = r.json; it["uid"] = uid363 let d = (try? JSONSerialization.data(withJSONObject: it)) ?? Data()364 favorites[uid] = String(data: d, encoding: .utf8)365 return StubResponse(status: 200, body: d)366 }367 return .json("{}")368 }369 }370 }371372 private func server() -> FakeServer {373 let s = FakeServer()374 StubServer.install { s.handle($0) }375 return s376 }377378 @Test("connexion : jeton au coffre, mémoire locale envoyée, liste fusionnée appliquée (favori d'un autre appareil affiché par son aperçu)")379 func signInSyncs() async throws {380 let srv = server()381 srv.seed("web:42", json: #"{"uid":"web:42","saved_at":1795000000000,"note":"vu sur le site","snapshot":{"title":"Condo du canal","city":"Montréal","sector":"Sud-Ouest","ptype":"Condo","price":389000,"image":"https://img.example.org/l.jpg","source":"web","lat":45.48,"lng":-73.57},"updated_at":1795000000001}"#)382 let library = Library(inMemory: true), store = MemoryStore()383 library.toggleFavorite(try sampleListing())384 let account = makeAccount(library, store: store)385 #expect(!account.isSignedIn && StubServer.seen.isEmpty, "sans compte, l'ajout d'un favori n'envoie rien")386387 try await account.signIn(email: " Lea@Example.org ", password: "Sapin-Bleu-4812")388 #expect(account.isSignedIn && account.user?.name == "Léa")389 #expect(store.string("session.token") == "jeton-secret-1", "le jeton est rangé dans le coffre")390 #expect(StubServer.seen.first?.json["email"] as? String == "lea@example.org", "courriel nettoyé")391 let sync = try #require(StubServer.seen("POST", "/favoris/synchronisation").first)392 let sent = try #require((sync.json["items"] as? [[String: Any]])?.first)393 #expect(sent["uid"] as? String == "duproprio:abc/123" && (sent["snapshot"] as? [String: Any])?["title"] as? String == "123, rue des Érables")394 #expect(((sent["snapshot"] as? [String: Any])?["area_sqft"] as? Double) == 1820 && (sent["saved_at"] as? Int ?? 0) > 1_700_000_000_000)395 #expect(sync.headers["Authorization"] == "Bearer jeton-secret-1")396397 #expect(library.favoriteIDs == ["duproprio:abc/123", "web:42"])398 let other = try #require(library.favorite("web:42"))399 #expect(other.displayTitle == "Condo du canal" && other.place == "Sud-Ouest · Montréal" && other.price == 389_000 && other.note == "vu sur le site")400 #expect(other.image == "https://img.example.org/l.jpg" && other.lat == 45.48 && other.propertyType == "Condo")401 #expect(account.sync.lastSync != nil && account.sync.lastError == nil)402 }403404 @Test("connecté : ajout, note et retrait partent aussitôt ; déconnecté : plus rien ne part, la mémoire reste")405 func immediatePushes() async throws {406 let srv = server()407 let library = Library(inMemory: true)408 let account = makeAccount(library)409 try await account.signIn(email: "lea@example.org", password: "x")410 let l = try sampleListing("centris:7")411 library.toggleFavorite(l)412 await account.sync.settle()413 #expect(srv.uids == ["centris:7"] && StubServer.seen("PUT", "/favoris/centris:7").count == 1)414 library.favorite("centris:7")?.note = "visite samedi"415 library.noteChanged("centris:7")416 await account.sync.settle()417 #expect(StubServer.seen("PUT", "/favoris/centris:7").last?.json["note"] as? String == "visite samedi")418 library.toggleFavorite(l)419 await account.sync.settle()420 #expect(srv.uids.isEmpty && account.sync.pending.isEmpty, "retrait confirmé : rien en attente")421422 library.toggleFavorite(l)423 await account.signOut()424 #expect(!account.isSignedIn && library.favoriteIDs == ["centris:7"], "la mémoire locale reste sur l'appareil")425 let before = StubServer.seen.count426 library.toggleFavorite(try sampleListing("centris:8"))427 library.removeFavorite("centris:7")428 await account.sync.settle()429 await account.sync.sync()430 #expect(StubServer.seen.count == before, "après la déconnexion, plus rien n'est envoyé")431 #expect(account.sync.pending.isEmpty)432 }433434 @Test("hors ligne : le retrait est gardé avec sa date, rejoué à la synchronisation suivante ; un rajout l'annule")435 func offlineRemovals() async throws {436 let srv = server()437 let library = Library(inMemory: true)438 let account = makeAccount(library)439 let a = try sampleListing("a:1"), b = try sampleListing("b:2")440 library.toggleFavorite(a); library.toggleFavorite(b)441 try await account.signIn(email: "lea@example.org", password: "x")442 #expect(srv.uids == ["a:1", "b:2"])443444 srv.offline = true445 let t0 = Ms.now446 library.removeFavorite("a:1")447 library.removeFavorite("b:2")448 await account.sync.settle()449 #expect(Set(account.sync.pending.favorites.keys) == ["a:1", "b:2"])450 #expect(account.sync.pending.favorites.values.allSatisfy { $0 >= t0 && $0 <= Ms.now }, "le moment du retrait est gardé")451 await account.sync.sync()452 #expect(account.sync.lastError != nil && !account.sync.pending.isEmpty, "échec : rien n'est perdu")453 library.toggleFavorite(b) // rajouté avant le retour du réseau454 await account.sync.settle()455 #expect(Set(account.sync.pending.favorites.keys) == ["a:1"])456457 srv.offline = false458 await account.sync.sync()459 let replay = try #require(StubServer.seen("POST", "/favoris/synchronisation").last)460 let removed = try #require(replay.json["removed"] as? [[String: Any]])461 #expect(removed.count == 1 && removed[0]["uid"] as? String == "a:1" && (removed[0]["at"] as? Int ?? 0) >= Int(t0))462 #expect(srv.uids == ["b:2"] && library.favoriteIDs == ["b:2"] && account.sync.pending.isEmpty && account.sync.lastError == nil)463 }464465 @Test("favori retiré sur un autre appareil : la liste fusionnée le retire d'ici aussi")466 func removedElsewhere() async throws {467 let srv = server()468 let library = Library(inMemory: true)469 let account = makeAccount(library)470 library.toggleFavorite(try sampleListing("a:1"))471 try await account.signIn(email: "lea@example.org", password: "x")472 StubServer.install { r in r.path.hasSuffix("/favoris/synchronisation") ? .json(#"{"items":[],"limit":2000,"skipped":0}"#) : srv.handle(r) }473 await account.sync.sync()474 #expect(library.favoriteIDs.isEmpty)475 }476477 @Test("401 non_authentifie : état déconnecté, jeton effacé, mémoire locale intacte")478 func unauthenticated() async throws {479 let srv = server()480 let library = Library(inMemory: true), store = MemoryStore()481 let account = makeAccount(library, store: store)482 library.toggleFavorite(try sampleListing("a:1"))483 try await account.signIn(email: "lea@example.org", password: "x")484 srv.expired = true485 library.toggleFavorite(try sampleListing("c:3"))486 await account.sync.settle()487 #expect(!account.isSignedIn && account.sessionEnded && store.string("session.token") == nil && store.read("session.user") == nil)488 #expect(library.favoriteIDs == ["a:1", "c:3"], "rien d'autre que la session n'est effacé")489 let before = StubServer.seen.count490 library.removeFavorite("a:1")491 await account.sync.settle()492 #expect(StubServer.seen.count == before)493494 // même chose pendant une synchronisation complète, et pendant un appel du compte495 srv.expired = false496 try await account.signIn(email: "lea@example.org", password: "x")497 #expect(account.isSignedIn && !account.sessionEnded)498 srv.expired = true499 await account.sync.sync()500 #expect(!account.isSignedIn)501 srv.expired = false502 try await account.signIn(email: "lea@example.org", password: "x")503 srv.expired = true504 await #expect(throws: AccountError.self) { try await account.rename("Léa B.") }505 // « a:1 », retiré pendant que l'appareil était déconnecté, est resté dans le compte : il revient506 #expect(!account.isSignedIn && library.favoriteIDs == ["a:1", "c:3"])507 }508509 @Test("relance : la session est relue du coffre ; suppression du compte : session oubliée, mémoire gardée")510 func relaunchAndDelete() async throws {511 _ = server()512 let library = Library(inMemory: true), store = MemoryStore()513 library.toggleFavorite(try sampleListing("a:1"))514 try await makeAccount(library, store: store).signIn(email: "lea@example.org", password: "x")515 let again = makeAccount(library, store: store)516 #expect(again.isSignedIn && again.user?.email == "lea@example.org")517 try await again.deleteAccount(password: "x")518 #expect(StubServer.seen("POST", "/suppression").first?.json["password"] as? String == "x")519 #expect(!again.isSignedIn && !again.sessionEnded && store.string("session.token") == nil && library.favoriteIDs == ["a:1"])520 #expect(!makeAccount(library, store: store).isSignedIn)521 }522523 @Test("mauvais mot de passe à la suppression : le compte et la session restent")524 func deleteWrongPassword() async throws {525 let srv = server()526 let account = makeAccount(Library(inMemory: true))527 try await account.signIn(email: "lea@example.org", password: "x")528 StubServer.install { r in r.path.hasSuffix("/suppression") ? .error(403, "mot_de_passe_incorrect", "Mot de passe incorrect.") : srv.handle(r) }529 do { try await account.deleteAccount(password: "faux"); Issue.record("la suppression aurait dû échouer") } catch let e as AccountError {530 #expect(e.code == "mot_de_passe_incorrect" && e.errorDescription == "Mot de passe incorrect.")531 }532 #expect(account.isSignedIn)533 }534535 @Test("recherches : envoyées avec origin ios ; celles du compte ne sont gardées que si leur requête se relit")536 func searches() async throws {537 let srv = server()538 let library = Library(inMemory: true)539 let account = makeAccount(library)540 var f = SearchFilters(); f.city = "Gatineau"; f.bedroomsMin = 3; f.priceMax = 500_000541 library.saveSearch(f, sort: .prix, total: 120)542 let localID = try #require(library.allSearches().first?.syncID)543 StubServer.install { r in544 guard r.path.hasSuffix("/recherches/synchronisation") else { return srv.handle(r) }545 let mine = ((r.json["items"] as? [[String: Any]]) ?? []).compactMap { try? JSONSerialization.data(withJSONObject: $0) }.compactMap { String(data: $0, encoding: .utf8) }546 let others = [#"{"id":"web-1","label":"Québec · Condo","query":"city=Qu%C3%A9bec&type=Condo&with=garage&sort=recent","origin":"web","saved_at":1795000000000,"last_total":40,"updated_at":1795000000000}"#,547 #"{"id":"web-2","label":"Zone dessinée","query":"polygon=1,2,3&city=Laval","origin":"web","saved_at":1795000000000,"updated_at":1795000000000}"#,548 #"{"id":"web-3","label":"","query":"nl=maison%20pr%C3%A8s%20du%20m%C3%A9tro","origin":"web","saved_at":1795000000000,"updated_at":1795000000000}"#]549 return .json(#"{"items":[\#((mine + others).joined(separator: ","))],"limit":100,"skipped":0}"#)550 }551 try await account.signIn(email: "lea@example.org", password: "x")552 let sent = try #require((StubServer.seen("POST", "/recherches/synchronisation").first?.json["items"] as? [[String: Any]])?.first)553 #expect(sent["id"] as? String == localID && sent["origin"] as? String == "ios" && sent["last_total"] as? Int == 120)554 #expect(sent["query"] as? String == "bedrooms_min=3&city=Gatineau&price_max=500000&sort=prix")555 let all = library.allSearches()556 #expect(Set(all.map(\.syncID)) == [localID, "web-1", "web-3"], "la recherche à paramètre inconnu (polygon) n'est pas affichée")557 let web = try #require(all.first { $0.syncID == "web-1" })558 #expect(web.filters.city == "Québec" && web.filters.propertyType == "Condo" && web.filters.with == ["garage"] && web.sort == .recent && web.origin == "web")559 let nl = try #require(all.first { $0.syncID == "web-3" })560 #expect(nl.filters.nl == "maison près du métro" && nl.label == "« maison près du métro »")561 #expect(web.remote.query == "city=Qu%C3%A9bec&sort=recent&type=Condo&with=garage" && web.remote.origin == "web", "renvoyée sans changer d'auteur")562563 // retrait : part aussitôt, par l'identifiant du compte564 library.delete(web)565 await account.sync.settle()566 #expect(StubServer.seen("DELETE", "/recherches/web-1").count == 1)567 }568}569570}571572// MARK: - Logique pure573574@Suite("Compte : fusion, file d'attente, requêtes, trousseau")575struct AccountLogicTests {576 @Test("requête de synchronisation : un retrait en attente n'est pas envoyé si l'élément est revenu")577 func request() {578 var p = PendingRemovals()579 p.favorites = ["a:1": 10, "b:2": 20]580 let r = SyncLogic.favoriteRequest(local: [RemoteFavorite(uid: "b:2", savedAt: 30)], pending: p)581 #expect(r.items.map(\.uid) == ["b:2"] && r.removed == [RemovedFavorite(uid: "a:1", at: 10)])582 p.searches = ["s1": 5]583 #expect(SyncLogic.searchRequest(local: [], pending: p).removed == [RemovedSearch(id: "s1", at: 5)])584 }585586 @Test("réponse : ce qui a changé ici pendant l'aller-retour n'est ni écrasé ni ressuscité")587 func settle() {588 let server = [RemoteFavorite(uid: "a:1", savedAt: 1), RemoteFavorite(uid: "b:2", savedAt: 2), RemoteFavorite(uid: "c:3", savedAt: 3)]589 let calm = SyncLogic.settle(server: server, id: \.uid, changed: [], removed: [])590 #expect(calm.apply.count == 3 && calm.keep.isEmpty && !calm.again)591 let busy = SyncLogic.settle(server: server, id: \.uid, changed: ["b:2", "d:4"], removed: ["c:3"])592 #expect(busy.apply.map(\.uid) == ["a:1", "b:2"], "le favori retiré pendant l'envoi ne revient pas")593 #expect(busy.keep == ["b:2", "d:4"] && busy.again, "le favori ajouté pendant l'envoi est gardé, et une synchronisation suit")594 }595596 @Test("éléments refusés par le serveur (skipped) : jamais supprimés de l'appareil")597 func refused() {598 #expect(SyncLogic.refused(sent: ["a", "b", "c"], server: ["a"], skipped: 0).isEmpty, "absents sans refus = retirés ailleurs")599 #expect(SyncLogic.refused(sent: ["a", "b", "c"], server: ["a"], skipped: nil).isEmpty)600 #expect(SyncLogic.refused(sent: ["a", "b", "c"], server: ["a", "z"], skipped: 2) == ["b", "c"])601 }602603 @Test("retraits en attente : gardés d'un lancement à l'autre, effacés quand la file est vide")604 func pendingPersistence() throws {605 let name = "immoka.tests.\(UUID().uuidString)"606 let d = try #require(UserDefaults(suiteName: name))607 defer { d.removePersistentDomain(forName: name) }608 #expect(PendingRemovals.load(d).isEmpty)609 var p = PendingRemovals(); p.favorites["a:1"] = 1_796_000_000_000; p.searches["s"] = 7610 p.save(d)611 #expect(PendingRemovals.load(d) == p)612 PendingRemovals().save(d)613 #expect(d.data(forKey: PendingRemovals.storeKey) == nil)614 }615616 @Test("chaîne de requête d'une recherche : aller-retour sans perte, tri, phrase, paramètre inconnu refusé")617 func searchQuery() throws {618 var f = SearchFilters()619 f.city = "Montréal"; f.sector = "Rosemont–La Petite-Patrie"; f.propertyType = "Condo"; f.priceMin = 300_000; f.priceMax = 650_000620 f.with = ["garage", "pool"]; f.deal = .sous; f.areaMin = 900; f.lotMin = 4000; f.bedroomsMin = 2; f.bathroomsMin = 1621 f.priceDrop = true; f.newDays = 7; f.yearMin = 1990; f.yearMax = 2020; f.taxMax = 5000; f.condoFeeMax = 400622 f.text = "métro + parc"; f.broker = "Tremblay"; f.region = "Montréal"623 let q = SearchQuery.string(f, sort: .deal)624 #expect(q.contains("sort=ecart") && q.contains("with=garage,pool") && q.contains("position=sous") && q.contains("area=Rosemont") && q.contains("%2B") && !q.contains(" "))625 let back = try #require(SearchQuery.read(q))626 #expect(back.filters == f && back.sort == .deal)627 #expect(SearchQuery.string(SearchFilters(), sort: .pertinence).isEmpty)628 #expect(SearchQuery.read("")?.filters == SearchFilters())629 #expect(SearchQuery.read("?city=Qu%C3%A9bec&price_max=450000")?.filters.priceMax == 450_000)630 #expect(SearchQuery.read("q=bord+de+l%27eau")?.filters.text == "bord de l'eau", "« + » d'un formulaire web = espace")631 #expect(SearchQuery.read("nl=maison%20avec%20garage")?.filters.nl == "maison avec garage")632 #expect(SearchQuery.read("position=dans")?.filters.deal == .marche && SearchQuery.read("position=ailleurs") == nil && SearchQuery.read("price_max=cher") == nil)633 #expect(SearchQuery.read("city=Laval&bbox=1,2,3,4") == nil && SearchQuery.read("sort=inconnu") == nil && SearchQuery.read("city=a&city=b") == nil)634 }635636 @Test("aperçu d'un favori : champs partagés, rien d'inventé")637 func snapshot() throws {638 let item = FavoriteItem(listing: try sampleListing())639 let s = item.snapshot640 #expect(s.title == "123, rue des Érables" && s.address == "123, rue des Érables" && s.city == "Gatineau" && s.sector == "Aylmer" && s.propertyType == "Maison")641 #expect(s.price == 450_000 && s.image == "https://img.example.org/a.jpg" && s.source == "duproprio" && s.areaSqft == 1820 && s.lat == 45.39 && s.lng == -75.84)642 let json = try #require(try JSONSerialization.jsonObject(with: JSONEncoder().encode(s)) as? [String: Any])643 #expect(Set(json.keys) == ["title", "address", "city", "sector", "ptype", "price", "image", "source", "area_sqft", "lat", "lng"])644 #expect(try JSONEncoder().encode(s).count < 4096)645 let empty = FavoriteItem(remote: RemoteFavorite(uid: "duproprio:9", savedAt: 1_796_000_000_000))646 #expect(empty.displayTitle == "Propriété à vendre" && empty.needsFill && empty.source == "duproprio" && empty.price == nil && empty.snapshot.title == nil)647 #expect(empty.remote.savedAt == 1_796_000_000_000 && empty.remote.updatedAt == 1_796_000_000_000)648 empty.fill(from: try sampleListing("duproprio:9", price: 475_000))649 #expect(empty.title == "123, rue des Érables" && empty.price == 475_000 && empty.lat == 45.39 && !empty.needsFill)650 #expect(try JSONDecoder().decode(FavoriteSnapshot.self, from: Data("[]".utf8)).isEmpty, "un aperçu qui n'est pas un objet est ignoré")651 }652653 @Test("dates en millisecondes")654 func ms() {655 #expect(Ms.from(Date(timeIntervalSince1970: 1_796_000_000.25)) == 1_796_000_000_250)656 #expect(Ms.date(1_796_000_000_250).timeIntervalSince1970 == 1_796_000_000.25)657 }658659 @Test("saisie : courriel plausible, code à six chiffres, délais lisibles")660 func input() {661 #expect(Account.emailLooksValid(" Lea@Example.org ") && Account.clean(" Lea@Example.org ") == "lea@example.org")662 for bad in ["", "lea", "lea@", "@example.org", "lea@example", "lea@@example.org", "lea @example.org", "lea@.org"] {663 #expect(!Account.emailLooksValid(bad), "\(bad)")664 }665 #expect(Account.codeDigits("42 42-42 9") == "424242" && Account.codeDigits("abc") == "")666 #expect(AccountError.delay(45) == "45 s" && AccountError.delay(90) == "2 min" && AccountError.delay(3600) == "60 min")667 }668669 @Test("trousseau : écriture, relecture, remplacement, effacement ; protection « après le premier déverrouillage », sans iCloud")670 func keychain() throws {671 let k = KeychainStore(service: "com.spboucher.immoka.v2.tests.\(UUID().uuidString)")672 defer { k.delete("session.token") }673 #expect(k.read("session.token") == nil)674 #expect(k.set("session.token", "jeton-A"))675 #expect(k.string("session.token") == "jeton-A")676 #expect(k.accessibility("session.token") == (kSecAttrAccessibleAfterFirstUnlock as String))677 #expect(k.set("session.token", "jeton-B") && k.string("session.token") == "jeton-B", "une seule entrée, remplacée")678 #expect(KeychainStore(service: "autre.service").string("session.token") == nil)679 k.delete("session.token")680 #expect(k.read("session.token") == nil)681 #expect(UserDefaults.standard.dictionaryRepresentation().values.contains { ($0 as? String)?.contains("jeton-") == true } == false,682 "le jeton n'est jamais dans UserDefaults")683 }684685 @Test("adresse des routes de compte : la production par défaut")686 func base() {687 if UserDefaults.standard.string(forKey: "IKBaseURL") == nil, ProcessInfo.processInfo.environment["IMMOKA_BASE_URL"] == nil {688 #expect(Account.baseURL().absoluteString == "https://www.immo-ka.com")689 }690 #expect(AccountAPI.url(base: URL(string: "https://x.test/")!, path: "favoris/a:1/b")?.absoluteString == "https://x.test/api/v3/compte/favoris/a:1/b")691 #expect(AccountAPI.url(base: URL(string: "https://x.test")!, path: "")?.absoluteString == "https://x.test/api/v3/compte")692 }693}694