Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Identity9// File : sdk/swift/Tests/MacLustrIdentityCoreTests/TestSupport.swift10// Module : MacLustrIdentityCoreTests11// Repository : https://git.spboucher.ai/maclustr-identity12// Project Website : https://identity.spboucher.ai13// Created : 2026-12-0114// Last Modified : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import XCTest90@testable import MacLustrIdentityCore9192enum Fixture {93 /// Raw JSON captured from a local backend (see Fixtures/).94 static func data(_ name: String) -> Data {95 let url = Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures")!96 return try! Data(contentsOf: url)97 }9899 /// A captured JSON object with some top-level keys replaced.100 static func data(_ name: String, patch: [String: Any]) -> Data {101 var obj = try! JSONSerialization.jsonObject(with: data(name)) as! [String: Any]102 for (k, v) in patch { obj[k] = v }103 return try! JSONSerialization.data(withJSONObject: obj)104 }105106 static func decode<T: Decodable>(_ type: T.Type, _ name: String) throws -> T {107 try JSONDecoder().decode(T.self, from: data(name))108 }109}110111/// Scripted transport: each "METHOD /path-suffix" has a queue of responses; the last one repeats until a new112/// response is scripted for the same key.113final class MockTransport: IdentityTransport, @unchecked Sendable {114 struct Response { var status: Int; var body: Data; var error: Error?; var headers: [String: String] = [:] }115116 private let lock = NSLock()117 private var queues: [String: [Response]] = [:]118 private var servedLast: Set<String> = []119 private(set) var requests: [URLRequest] = []120121 private func append(_ key: String, _ r: Response) {122 lock.lock(); defer { lock.unlock() }123 if servedLast.remove(key) != nil { queues[key] = [] }124 queues[key, default: []].append(r)125 }126127 func on(_ method: String, _ suffix: String, status: Int = 200, headers: [String: String] = [:], _ body: Data) {128 append("\(method) \(suffix)", Response(status: status, body: body, error: nil, headers: headers))129 }130131 func on(_ method: String, _ suffix: String, fixture: String, status: Int = 200, headers: [String: String] = [:]) {132 on(method, suffix, status: status, headers: headers, Fixture.data(fixture))133 }134135 func fail(_ method: String, _ suffix: String, _ error: Error) {136 append("\(method) \(suffix)", Response(status: 0, body: Data(), error: error))137 }138139 var log: [String] {140 lock.lock(); defer { lock.unlock() }141 return requests.map { "\($0.httpMethod ?? "") \(Self.suffix(of: $0))" }142 }143144 func count(_ key: String) -> Int { log.filter { $0 == key }.count }145146 private static func suffix(of request: URLRequest) -> String {147 let parts = request.url!.path.split(separator: "/").dropFirst(3) // v1 / sessions / {id}148 return "/" + parts.joined(separator: "/")149 }150151 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {152 let response: Response = try {153 lock.lock(); defer { lock.unlock() }154 requests.append(request)155 let key = "\(request.httpMethod ?? "") \(Self.suffix(of: request))"156 guard var q = queues[key], !q.isEmpty else { throw URLError(.unsupportedURL) }157 let r = q[0]158 if q.count > 1 { q.removeFirst(); queues[key] = q } else { servedLast.insert(key) }159 return r160 }()161 if let error = response.error { throw error }162 return (response.body, HTTPURLResponse(url: request.url!, statusCode: response.status, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": "application/json"].merging(response.headers) { $1 })!)163 }164}165166let testSession = try! IdentitySession(baseURL: URL(string: "https://identity.example")!, sessionID: "vs_test123", clientSecret: "vsc_secret456")167168/// Records the waits requested from a sleeper without waiting.169final class Waits: @unchecked Sendable {170 private var stored: [TimeInterval] = []171 private let lock = NSLock()172 func add(_ d: TimeInterval) { lock.lock(); stored.append(d); lock.unlock() }173 var values: [TimeInterval] { lock.lock(); defer { lock.unlock() }; return stored }174}175176/// Body of an API error envelope.177func errorBody(_ code: String, type: String = "api_error") -> Data {178 Data("{\"error\":{\"type\":\"\(type)\",\"code\":\"\(code)\",\"message\":\"m\",\"request_id\":\"req_test\"}}".utf8)179}180