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/ModelsTests.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 XCTest89@testable import MacLustrIdentityCore9091/// Decoding of real JSON captured from the backend.92final class ModelsTests: XCTestCase {93 func testFlowStateCreated() throws {94 let s = try Fixture.decode(FlowState.self, "flow_created")95 XCTAssertEqual(s.status, .created)96 XCTAssertFalse(s.livemode)97 XCTAssertEqual(s.locale, "fr-CA")98 XCTAssertEqual(s.application.name, "Native Demo")99 XCTAssertNil(s.application.accent)100 XCTAssertNil(s.method)101 XCTAssertEqual(s.methods.map(\.id), ["document_selfie", "document_review"])102 XCTAssertTrue(s.methods[0].biometric)103 XCTAssertTrue(s.methods[0].requiresSelfie)104 XCTAssertFalse(s.methods[1].biometric)105 XCTAssertEqual(s.methods[0].label.fr, "Pièce d'identité et égoportrait")106 XCTAssertEqual(s.methods[0].label[.en], "ID document and selfie")107 let consent = try XCTUnwrap(s.methods[0].consentText(.fr))108 XCTAssertEqual(consent.version, "2026-12-01.2")109 XCTAssertEqual(consent.points.count, 5)110 XCTAssertTrue(consent.checkbox.contains("mesures de mon visage"))111 XCTAssertEqual(consent.controller?.contact, "privacy@spboucher.ai")112 XCTAssertEqual(s.controller?.name, "MacLustr Identity — SP Boucher")113 XCTAssertEqual(s.sandbox?.scenarios.map(\.id), ["verified", "manual_review", "inconclusive", "rejected"])114 XCTAssertEqual(s.attemptsLeft, 3)115 XCTAssertFalse(s.selfieDone)116 XCTAssertNil(s.result)117 XCTAssertNotNil(s.expiresAt)118 }119120 func testFlowStateLive() throws {121 let s = try Fixture.decode(FlowState.self, "flow_live_awaiting_selfie")122 XCTAssertTrue(s.livemode)123 XCTAssertNil(s.sandbox)124 XCTAssertEqual(s.status, .awaitingSelfie)125 XCTAssertTrue(s.hasUploaded(.front))126 XCTAssertTrue(s.hasUploaded(.back))127 XCTAssertEqual(s.chosenMethod?.id, "document_selfie")128 let p = try Fixture.decode(FlowState.self, "flow_live_processing")129 XCTAssertEqual(p.status, .processing)130 XCTAssertTrue(p.selfieDone)131 XCTAssertEqual(p.attemptsLeft, 2)132 }133134 func testFlowStateResults() throws {135 let v = try Fixture.decode(FlowState.self, "flow_sandbox_verified")136 XCTAssertEqual(v.status, .verified)137 XCTAssertEqual(v.result?.status, .verified)138 XCTAssertEqual(v.result?.reasons.map(\.code), ["simulated"])139 XCTAssertNotNil(v.result?.verifiedAt)140 let r = try Fixture.decode(FlowState.self, "flow_sandbox_rejected")141 XCTAssertEqual(r.status, .rejected)142 XCTAssertEqual(r.result?.reasons.map(\.code), ["simulated", "document_expired"])143 XCTAssertEqual(r.result?.reasons[1].message.fr, "Le document est expiré.")144 XCTAssertNil(r.result?.verifiedAt)145 XCTAssertEqual(try Fixture.decode(FlowState.self, "flow_sandbox_manual_review").status, .manualReview)146 XCTAssertEqual(try Fixture.decode(FlowState.self, "flow_sandbox_inconclusive").status, .inconclusive)147 XCTAssertEqual(try Fixture.decode(FlowState.self, "flow_cancelled").status, .cancelled)148 }149150 func testEveryCapturedFlowStateDecodes() throws {151 let dir = Bundle.module.url(forResource: "Fixtures", withExtension: nil)!152 let names = try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasPrefix("flow_") }153 XCTAssertGreaterThanOrEqual(names.count, 10)154 for n in names {155 XCTAssertNoThrow(try Fixture.decode(FlowState.self, String(n.dropLast(5))), n)156 }157 }158159 func testUnknownStatusIsTolerated() throws {160 let s = try JSONDecoder().decode(FlowState.self, from: Fixture.data("flow_created", patch: ["status": "on_hold"]))161 XCTAssertEqual(s.status, .unknown("on_hold"))162 XCTAssertEqual(s.status.rawValue, "on_hold")163 XCTAssertFalse(s.status.isFinal)164 }165166 func testStatusRawValuesRoundTrip() {167 for raw in ["created", "awaiting_consent", "awaiting_document", "awaiting_selfie", "processing", "manual_review", "verified", "inconclusive", "rejected", "expired", "cancelled", "revoked"] {168 XCTAssertEqual(SessionStatus(rawValue: raw).rawValue, raw)169 if case .unknown = SessionStatus(rawValue: raw) { XCTFail(raw) }170 }171 XCTAssertTrue(SessionStatus.expired.isFinal)172 XCTAssertFalse(SessionStatus.manualReview.isFinal)173 XCTAssertTrue(SessionStatus.awaitingSelfie.isInteractive)174 }175176 func testDocumentUploadResults() throws {177 let ok = try Fixture.decode(DocumentUploadResult.self, "document_accepted_front")178 XCTAssertTrue(ok.accepted)179 XCTAssertEqual(ok.side, "front")180 XCTAssertEqual(ok.status, .awaitingSelfie)181 let ko = try Fixture.decode(DocumentUploadResult.self, "document_rejected_quality")182 XCTAssertFalse(ko.accepted)183 XCTAssertEqual(ko.issues, ["image_blurry", "image_too_dark", "low_contrast"])184 XCTAssertNil(ko.status)185 }186187 func testChallenge() throws {188 let c = try Fixture.decode(LivenessChallenge.self, "challenge")189 XCTAssertTrue(c.challengeID.hasPrefix("chl_"))190 XCTAssertEqual(c.steps.count, 2)191 XCTAssertTrue(c.steps.allSatisfy { $0 == .turnLeft || $0 == .turnRight })192 XCTAssertFalse(c.accessible)193 XCTAssertEqual(c.expiresIn, 120)194 XCTAssertEqual(c.frames, .init(min: 8, max: 24, intervalMS: 250))195 let a = try Fixture.decode(LivenessChallenge.self, "challenge_accessible")196 XCTAssertTrue(a.accessible)197 XCTAssertTrue(a.steps.isEmpty)198 XCTAssertEqual(a.frames.min, 3) // the accessible alternative needs three frames only199 }200201 func testSmallAnswers() throws {202 let selfie = try Fixture.decode(SelfieUploadResult.self, "selfie_accepted")203 XCTAssertTrue(selfie.accepted)204 XCTAssertEqual(selfie.frames, 8)205 let w = try Fixture.decode(WithdrawResult.self, "withdraw")206 XCTAssertEqual(w.status, .cancelled)207 XCTAssertTrue(w.destroyed)208 let d = try Fixture.decode(DisputeResult.self, "dispute_created")209 XCTAssertTrue(d.id.hasPrefix("dsp_"))210 XCTAssertEqual(d.status, "open")211 }212213 func testTimestamps() {214 let d = Timestamp.parse("2026-12-01T10:01:52.002100-05:00")215 XCTAssertNotNil(d)216 XCTAssertEqual(d!.timeIntervalSince1970, 1_796_137_312.0021, accuracy: 0.01)217 XCTAssertNotNil(Timestamp.parse("2026-12-01T15:01:52+00:00"))218 XCTAssertNotNil(Timestamp.parse("2026-12-01T15:01:52Z"))219 XCTAssertNil(Timestamp.parse("yesterday"))220 }221222 func testNewFlowFields() throws {223 let s = try Fixture.decode(FlowState.self, "flow_live_awaiting_selfie")224 XCTAssertEqual(s.maxAttempts, 3)225 XCTAssertEqual(s.attemptsLeft, 3)226 XCTAssertTrue(s.lastIssue.isEmpty)227 XCTAssertEqual(s.document.front, "required")228 XCTAssertEqual(s.document.back, "required_for_cards")229 XCTAssertEqual(s.document.backRequiredFor, ["driver_licence", "id_card"])230 XCTAssertFalse(s.document.accepted.isEmpty)231 XCTAssertTrue(s.document.mayNeedBack)232 XCTAssertFalse(s.isPastExpiry(now: Date(timeIntervalSince1970: 0)))233 XCTAssertTrue(s.isPastExpiry(now: .distantFuture))234 let issue: [[String: Any]] = [["code": "capture_quality_insufficient", "message": ["fr": "Image floue.", "en": "Blurry image."]], ["code": "future_code"], ["nope": 1]]235 let retry = try JSONDecoder().decode(FlowState.self, from: Fixture.data("flow_live_awaiting_selfie", patch: ["status": "awaiting_document", "uploaded": [String: Bool](), "attempts_left": 2, "last_issue": issue]))236 XCTAssertEqual(retry.lastIssue.map(\.code), ["capture_quality_insufficient", "future_code"]) // the malformed element is skipped237 XCTAssertEqual(retry.lastIssue[0].message.fr, "Image floue.")238 XCTAssertEqual(retry.lastIssue[1].message.en, "future_code") // no message: the code stands in239 }240241 func testNewReasonCodesDecode() throws {242 let result: [String: Any] = ["status": "inconclusive", "verified_at": NSNull(), "reasons": [243 ["code": "review_not_completed", "message": ["fr": "L'examen n'a pas pu être complété à temps.", "en": "The review could not be completed in time."]],244 ["code": "decision_overturned", "message": ["fr": "a", "en": "b"]]]]245 let s = try JSONDecoder().decode(FlowState.self, from: Fixture.data("flow_sandbox_inconclusive", patch: ["result": result]))246 XCTAssertEqual(s.result?.reasons.map(\.code), ["review_not_completed", "decision_overturned"])247 XCTAssertEqual(s.result?.status, .inconclusive)248 }249250 /// A later version of the service may add, drop or reshape fields: decoding must never fail on that.251 func testTolerantDecoding() throws {252 // Only id and status.253 let bare = try JSONDecoder().decode(FlowState.self, from: Data(#"{"id":"vs_x","status":"created"}"#.utf8))254 XCTAssertEqual(bare.status, .created)255 XCTAssertTrue(bare.livemode) // unknown means live: no sandbox shortcut by mistake256 XCTAssertEqual(bare.application.name, "")257 XCTAssertTrue(bare.methods.isEmpty)258 XCTAssertEqual(bare.document, DocumentRequirements())259 XCTAssertEqual(bare.maxAttempts, 0)260 // Wrong types everywhere, unknown fields, one malformed method among valid ones.261 let odd = #"""262 {"id":"vs_x","status":"brand_new","livemode":"yes","locale":7,"application":"none","controller":[1],"sandbox":{"scenarios":[{"id":"verified"},{"label":1},7]},263 "methods":[{"id":"document_only","biometric":false,"label":"Document","consent":{"fr":{"version":"v9","title":"T"},"en":{"title":"no version"}},"extra":{"a":1}},264 {"biometric":true}, "junk", {"id":"future_method"}],265 "uploaded":{"front":true,"back":"maybe"},"selfie_done":"x","attempts_left":"3","max_attempts":null,"last_issue":"none","document":{"front":1,"accepted":["passport",3]},266 "result":{"status":7,"reasons":"x"},"expires_at":"soon","a_future_field":{"deep":[1,2,3]}}267 """#268 let s = try JSONDecoder().decode(FlowState.self, from: Data(odd.utf8))269 XCTAssertEqual(s.status, .unknown("brand_new"))270 XCTAssertTrue(s.livemode)271 XCTAssertEqual(s.locale, "fr-CA")272 XCTAssertEqual(s.methods.map(\.id), ["document_only", "future_method"])273 XCTAssertEqual(s.methods[0].label.en, "Document")274 XCTAssertEqual(s.methods[0].consent.keys.sorted(), ["fr"]) // a text without a version cannot be consented to275 XCTAssertEqual(s.methods[0].consentText(.en)?.version, "v9")276 XCTAssertTrue(s.methods[1].biometric) // unknown means biometric: the express consent is asked277 XCTAssertNil(s.methods[1].consentText(.fr))278 XCTAssertEqual(s.sandbox?.scenarios.map(\.id), ["verified"])279 XCTAssertEqual(s.uploaded, ["front": true])280 XCTAssertFalse(s.selfieDone)281 XCTAssertEqual(s.attemptsLeft, 0)282 XCTAssertTrue(s.lastIssue.isEmpty)283 XCTAssertEqual(s.document.accepted, ["passport"])284 XCTAssertEqual(s.document.front, "required")285 XCTAssertEqual(s.result?.status, .unknown(""))286 XCTAssertNil(s.expiresAt)287 // Small answers.288 let c = try JSONDecoder().decode(LivenessChallenge.self, from: Data(#"{"challenge_id":"chl_1","steps":["turn_left","nod",3],"accessible":true}"#.utf8))289 XCTAssertEqual(c.steps, [.turnLeft, .unknown("nod")])290 XCTAssertEqual(c.frames, .init(min: 3, max: 24, intervalMS: 250))291 XCTAssertEqual(c.expiresIn, 120)292 let d = try JSONDecoder().decode(DocumentUploadResult.self, from: Data(#"{"accepted":false,"issues":["image_blurry",1],"status":"later_status","new":1}"#.utf8))293 XCTAssertEqual(d.issues, ["image_blurry"])294 XCTAssertEqual(d.status, .unknown("later_status"))295 XCTAssertEqual(try JSONDecoder().decode(WithdrawResult.self, from: Data("{}".utf8)).status, .cancelled)296 XCTAssertEqual(try JSONDecoder().decode(DisputeResult.self, from: Data(#"{"id":"dsp_1"}"#.utf8)).status, "open")297 XCTAssertEqual(try JSONDecoder().decode(LocalizedText.self, from: Data(#""plain""#.utf8)), LocalizedText(fr: "plain", en: "plain"))298 }299}300