Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Immo-Ka Admin iOS9// File : ImmoKaAdminTests/StubServer.swift10// Description : serveur simulé pour les tests (`URLProtocol`) : garde les11// requêtes vues, rend les réponses voulues.12// Module : ImmoKaAdminTests13// Repository : https://git.spboucher.ai/immo-ka-admin-ios14// Project Website : https://www.immo-ka.com15// Created : 2026-11-3016// Last Modified : 2026-11-3017//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Testing92@testable import ImmoKaAdmin9394// MARK: - Serveur simulé9596/// Requête vue par le serveur simulé.97struct SeenRequest: Sendable {98 var method: String99 var url: String100 var path: String101 var headers: [String: String]102 var body: Data103 var json: [String: Any] { (try? JSONSerialization.jsonObject(with: body) as? [String: Any]) ?? [:] }104}105106struct StubResponse: Sendable {107 var status = 200108 var headers: [String: String] = [:]109 var body = Data()110 /// échec de transport (hors ligne)111 var offline = false112 static func json(_ s: String, status: Int = 200, headers: [String: String] = [:]) -> StubResponse {113 StubResponse(status: status, headers: headers, body: Data(s.utf8))114 }115 static let noContent = StubResponse(status: 204)116 static let down = StubResponse(offline: true)117 static func error(_ status: Int, _ code: String, _ message: String, headers: [String: String] = [:]) -> StubResponse {118 .json(#"{"error":{"code":"\#(code)","message":"\#(message)","request_id":"r1"}}"#, status: status, headers: headers)119 }120}121122final class StubServer: URLProtocol, @unchecked Sendable {123 private static let lock = NSLock()124 nonisolated(unsafe) private static var handler: (@Sendable (SeenRequest) -> StubResponse)?125 nonisolated(unsafe) private static var log: [SeenRequest] = []126127 static func install(_ h: @escaping @Sendable (SeenRequest) -> StubResponse) {128 lock.withLock { handler = h; log = [] }129 }130 static var seen: [SeenRequest] { lock.withLock { log } }131 static func seen(_ method: String, _ suffix: String) -> [SeenRequest] { seen.filter { $0.method == method && $0.path.hasSuffix(suffix) } }132133 static func session() -> URLSession {134 let cfg = URLSessionConfiguration.ephemeral135 cfg.protocolClasses = [StubServer.self]136 return URLSession(configuration: cfg)137 }138139 override class func canInit(with request: URLRequest) -> Bool { true }140 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }141 override func stopLoading() {}142143 override func startLoading() {144 var body = request.httpBody ?? Data()145 if let stream = request.httpBodyStream {146 stream.open()147 var buf = [UInt8](repeating: 0, count: 4096)148 while stream.hasBytesAvailable {149 let n = stream.read(&buf, maxLength: buf.count)150 if n <= 0 { break }151 body.append(buf, count: n)152 }153 stream.close()154 }155 let seen = SeenRequest(method: request.httpMethod ?? "GET", url: request.url?.absoluteString ?? "",156 path: request.url?.path(percentEncoded: true) ?? "", headers: request.allHTTPHeaderFields ?? [:], body: body)157 let h = StubServer.lock.withLock { () -> (@Sendable (SeenRequest) -> StubResponse)? in158 StubServer.log.append(seen)159 return StubServer.handler160 }161 let r = h?(seen) ?? StubResponse(status: 500)162 if r.offline {163 client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet))164 return165 }166 let resp = HTTPURLResponse(url: request.url!, statusCode: r.status, httpVersion: "HTTP/1.1", headerFields: r.headers)!167 client?.urlProtocol(self, didReceive: resp, cacheStoragePolicy: .notAllowed)168 client?.urlProtocol(self, didLoad: r.body)169 client?.urlProtocolDidFinishLoading(self)170 }171}172173final class Counter: @unchecked Sendable {174 private let lock = NSLock(); private var n = 0175 func next() -> Int { lock.withLock { n += 1; return n } }176}177178/// Toutes les suites qui utilisent le serveur simulé s'exécutent l'une après l'autre.179@Suite("Serveur simulé", .serialized)180enum Stubbed {}181