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/ResilienceTests.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/// Retries, Retry-After, deadlines, cancellation and the sessions that move on without the app.92@MainActor93final class ResilienceTests: XCTestCase {94 private let jpeg = Data([0xFF, 0xD8, 0xFF, 0xE0, 0x01, 0x02, 0x03, 0xFF, 0xD9])95 private let liveAwaitingDocument = Fixture.data("flow_live_awaiting_selfie", patch: ["status": "awaiting_document", "uploaded": [String: Bool]()])96 private let liveVerified = Fixture.data("flow_live_processing", patch: ["status": "verified", "result": ["status": "verified", "reasons": [[String: Any]]()] as [String: Any]])9798 /// A client with the default retry policy whose waits are recorded instead of slept.99 private func client(_ t: IdentityTransport, _ waits: Waits, policy: IdentityRetryPolicy = .default) -> IdentityClient {100 IdentityClient(session: testSession, transport: t, retryPolicy: policy, sleeper: { waits.add($0) })101 }102103 private func model(_ t: MockTransport, _ waits: Waits = Waits(), policy: IdentityRetryPolicy = .default) -> VerificationFlowModel {104 let m = VerificationFlowModel(client: client(t, waits, policy: policy), sleeper: { _ in await Task.yield() })105 m.pollJitter = 0106 return m107 }108109 private func wait(_ m: VerificationFlowModel, for expected: FlowStep, file: StaticString = #filePath, line: UInt = #line) async {110 for _ in 0..<2000 {111 if m.step == expected { return }112 try? await Task.sleep(nanoseconds: 1_000_000)113 }114 XCTFail("step is \(m.step), expected \(expected)", file: file, line: line)115 }116117 // MARK: Client retries118119 func testUploadIsRetriedAfterNetworkFailuresWithTheSameBytes() async throws {120 let t = MockTransport(), waits = Waits()121 t.fail("POST", "/document", URLError(.networkConnectionLost))122 t.fail("POST", "/document", URLError(.timedOut))123 t.on("POST", "/document", fixture: "document_accepted_front")124 let r = try await client(t, waits).uploadDocument(side: .front, image: jpeg)125 XCTAssertTrue(r.accepted)126 XCTAssertEqual(t.count("POST /document"), 3)127 let bodies = t.requests.map(\.httpBody)128 XCTAssertNotNil(bodies[0])129 XCTAssertEqual(bodies[0], bodies[1]) // same multipart body, same boundary: the image held in memory is sent again130 XCTAssertEqual(bodies[1], bodies[2])131 XCTAssertNotNil(bodies[0]?.range(of: jpeg))132 XCTAssertEqual(waits.values.count, 2)133 XCTAssertTrue((0.25...0.5).contains(waits.values[0]), "\(waits.values)") // 0.5 s × [50 %, 100 %]134 XCTAssertTrue((0.5...1.0).contains(waits.values[1]), "\(waits.values)")135 }136137 func testGivesUpAfterMaxRetries() async {138 let t = MockTransport(), waits = Waits()139 t.fail("GET", "/", URLError(.notConnectedToInternet))140 do { _ = try await client(t, waits).flowState(); XCTFail() } catch {141 guard case .network = error as? IdentityError else { return XCTFail("\(error)") }142 }143 XCTAssertEqual(t.count("GET /"), 3) // 1 attempt + 2 retries144 XCTAssertEqual(waits.values.count, 2)145 let single = MockTransport()146 single.fail("GET", "/", URLError(.notConnectedToInternet))147 _ = try? await client(single, waits, policy: .none).flowState()148 XCTAssertEqual(single.count("GET /"), 1)149 }150151 func testRateLimitWithShortRetryAfterIsWaitedFor() async throws {152 let t = MockTransport(), waits = Waits()153 t.on("GET", "/", fixture: "error_rate_limited", status: 429, headers: ["Retry-After": "2"])154 t.on("GET", "/", fixture: "flow_created")155 let s = try await client(t, waits).flowState()156 XCTAssertEqual(s.status, .created)157 XCTAssertEqual(waits.values, [2])158 }159160 func testLongRetryAfterIsReportedInsteadOfFreezingTheFlow() async {161 let t = MockTransport(), waits = Waits()162 t.on("GET", "/", fixture: "error_rate_limited", status: 429, headers: ["Retry-After": "40"])163 do { _ = try await client(t, waits).flowState(); XCTFail() } catch {164 let e = error as? IdentityError165 XCTAssertEqual(e?.code, "rate_limited")166 XCTAssertEqual(e?.retryAfter, 40)167 XCTAssertTrue(e?.isRetryable == true)168 XCTAssertEqual(IdentityString.forError(e!), .errorRateLimited)169 }170 XCTAssertEqual(t.count("GET /"), 1)171 XCTAssertTrue(waits.values.isEmpty)172 }173174 func testServiceUnavailableHonoursRetryAfter() async throws {175 let t = MockTransport(), waits = Waits()176 t.on("POST", "/submit", status: 503, headers: ["retry-after": "5"], errorBody("service_unavailable"))177 t.on("POST", "/submit", fixture: "flow_live_processing")178 let s = try await client(t, waits).submit()179 XCTAssertEqual(s.status, .processing)180 XCTAssertEqual(waits.values, [5])181 // Without the header: exponential backoff.182 let u = MockTransport(), w2 = Waits()183 u.on("GET", "/", status: 503, errorBody("service_unavailable"))184 u.on("GET", "/", status: 502, Data("<html>".utf8))185 u.on("GET", "/", fixture: "flow_created")186 _ = try await client(u, w2).flowState()187 XCTAssertEqual(w2.values.count, 2)188 XCTAssertTrue((0.25...0.5).contains(w2.values[0]))189 XCTAssertEqual(IdentityString.forError(.api(APIError(status: 503, type: "api_error", code: "service_unavailable", message: ""))), .errorServiceUnavailable)190 }191192 func testClientErrorsAndQuotasAreNeverRetried() async {193 let cases: [(Int, String)] = [(400, "consent_required"), (401, "invalid_client_secret"), (403, "forbidden_network"), (404, "not_found"), (409, "invalid_session_state"),194 (411, "length_required"), (413, "payload_too_large"), (429, "too_many_uploads"), (429, "too_many_challenges")]195 for (status, code) in cases {196 let t = MockTransport(), waits = Waits()197 t.on("GET", "/", status: status, headers: ["Retry-After": "1"], errorBody(code))198 do { _ = try await client(t, waits).flowState(); XCTFail(code) } catch {199 XCTAssertEqual((error as? IdentityError)?.code, code)200 }201 XCTAssertEqual(t.count("GET /"), 1, code)202 XCTAssertTrue(waits.values.isEmpty, code)203 }204 }205206 func testCapturedTransportErrors() async {207 let t = MockTransport()208 t.on("POST", "/consent", fixture: "error_payload_too_large", status: 413)209 do { _ = try await client(t, Waits()).consent(method: "document_only", textVersion: "v", biometricConsent: false); XCTFail() } catch {210 guard case .api(let e)? = error as? IdentityError else { return XCTFail("\(error)") }211 XCTAssertEqual(e.status, 413)212 XCTAssertEqual(e.code, "payload_too_large")213 XCTAssertEqual(e.type, "invalid_request_error")214 XCTAssertEqual(IdentityString.forError(.api(e)), .errorFileTooLarge)215 }216 }217218 func testBackoffIsExponentialCappedAndJittered() {219 let p = IdentityRetryPolicy()220 XCTAssertEqual(p.backoff(attempt: 0, random: 1), 0.5)221 XCTAssertEqual(p.backoff(attempt: 0, random: 0), 0.25)222 XCTAssertEqual(p.backoff(attempt: 2, random: 1), 2)223 XCTAssertEqual(p.backoff(attempt: 10, random: 1), 8) // capped224 XCTAssertEqual(p.backoff(attempt: 400, random: 1), 8) // no overflow225 for _ in 0..<50 { XCTAssertTrue((1.0...2.0).contains(p.backoff(attempt: 2))) }226 let net = IdentityError.network("x")227 XCTAssertNotNil(p.delay(after: net, attempt: 1))228 XCTAssertNil(p.delay(after: net, attempt: 2)) // budget spent229 XCTAssertNil(p.delay(after: .cameraDenied, attempt: 0))230 XCTAssertNil(IdentityRetryPolicy.none.delay(after: net, attempt: 0))231 XCTAssertEqual(p.delay(after: .api(APIError(status: 429, type: "", code: "rate_limited", message: "", retryAfter: 15)), attempt: 0), 15)232 XCTAssertNil(p.delay(after: .api(APIError(status: 429, type: "", code: "rate_limited", message: "", retryAfter: 16)), attempt: 0))233 }234235 func testRetryAfterParsing() {236 XCTAssertEqual(IdentityError.parseRetryAfter("7"), 7)237 XCTAssertEqual(IdentityError.parseRetryAfter(" 1.5 "), 1.5)238 XCTAssertEqual(IdentityError.parseRetryAfter("-3"), 0)239 XCTAssertNil(IdentityError.parseRetryAfter(nil))240 XCTAssertNil(IdentityError.parseRetryAfter(""))241 XCTAssertNil(IdentityError.parseRetryAfter("soon"))242 XCTAssertNil(IdentityError.parseRetryAfter("inf"))243 let now = Date(timeIntervalSince1970: 1_796_137_200) // Tue, 01 Dec 2026 15:00:00 GMT244 XCTAssertEqual(IdentityError.parseRetryAfter("Tue, 01 Dec 2026 15:00:30 GMT", now: now) ?? -1, 30, accuracy: 0.5)245 XCTAssertEqual(IdentityError.parseRetryAfter("Tue, 01 Dec 2026 14:00:00 GMT", now: now), 0)246 }247248 // MARK: Deadlines and cancellation249250 private struct Hanging: IdentityTransport {251 let started = Waits()252 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {253 started.add(0)254 try await Task.sleep(nanoseconds: 30_000_000_000)255 throw URLError(.unknown)256 }257 }258259 func testEachAttemptHasADeadline() async {260 let t = Hanging(), waits = Waits()261 let c = client(t, waits, policy: IdentityRetryPolicy(maxRetries: 1, requestTimeout: 0.05, uploadTimeout: 0.05))262 let t0 = Date()263 do { _ = try await c.flowState(); XCTFail() } catch {264 XCTAssertEqual(error as? IdentityError, .network("timeout"))265 }266 XCTAssertLessThan(Date().timeIntervalSince(t0), 5)267 XCTAssertEqual(t.started.values.count, 2) // the timeout is a network failure: retried once, then reported268 XCTAssertEqual(waits.values.count, 1)269 }270271 func testRequestsCarryTheirOwnTimeout() throws {272 let c = IdentityClient(session: testSession, transport: MockTransport(), retryPolicy: IdentityRetryPolicy(requestTimeout: 12, uploadTimeout: 77))273 XCTAssertEqual(try c.makeRequest("GET", "").timeoutInterval, 12)274 var form = MultipartForm()275 form.addField(name: "side", value: "front")276 XCTAssertEqual(try c.makeRequest("POST", "/document", form: form).timeoutInterval, 77)277 }278279 func testCancellingStopsTheCallAndItsRetries() async {280 let t = Hanging()281 let c = IdentityClient(session: testSession, transport: t)282 let task = Task { () -> IdentityError? in283 do { _ = try await c.flowState(); return nil } catch { return error as? IdentityError }284 }285 try? await Task.sleep(nanoseconds: 50_000_000)286 task.cancel()287 let e = await task.value288 XCTAssertEqual(e, .cancelled)289 XCTAssertEqual(t.started.values.count, 1)290291 // Cancelled while waiting between two attempts: no further attempt.292 let failing = MockTransport()293 failing.fail("GET", "/", URLError(.networkConnectionLost))294 let slow = IdentityClient(session: testSession, transport: failing, sleeper: { _ in try await Task.sleep(nanoseconds: 30_000_000_000) })295 let waiting = Task { () -> IdentityError? in296 do { _ = try await slow.flowState(); return nil } catch { return error as? IdentityError }297 }298 try? await Task.sleep(nanoseconds: 50_000_000)299 waiting.cancel()300 let e2 = await waiting.value301 XCTAssertEqual(e2, .cancelled)302 XCTAssertEqual(failing.count("GET /"), 1)303 }304305 func testACancelledActionLeavesTheModelUsable() async {306 let t = MockTransport()307 t.on("GET", "/", liveAwaitingDocument)308 t.fail("POST", "/document", CancellationError())309 t.on("POST", "/document", fixture: "document_accepted_front")310 let m = model(t)311 await m.start()312 let first = await m.uploadDocument(side: .front, image: jpeg)313 XCTAssertEqual(first, .failed)314 XCTAssertNil(m.lastError) // a cancellation is not shown as an error315 XCTAssertFalse(m.isBusy)316 XCTAssertEqual(m.step, .documentFront)317 let second = await m.uploadDocument(side: .front, image: jpeg)318 XCTAssertEqual(second, .accepted)319 }320321 // MARK: Flow model322323 func testModelUploadSurvivesANetworkFailureWithoutRecapture() async {324 let t = MockTransport(), waits = Waits()325 t.on("GET", "/", liveAwaitingDocument)326 t.fail("POST", "/document", URLError(.networkConnectionLost))327 t.on("POST", "/document", fixture: "document_accepted_front")328 let m = model(t, waits)329 await m.start()330 let r = await m.uploadDocument(side: .front, image: jpeg)331 XCTAssertEqual(r, .accepted) // retried by the client, the person saw nothing332 XCTAssertEqual(m.step, .documentBack)333 XCTAssertEqual(t.count("POST /document"), 2)334 XCTAssertEqual(waits.values.count, 1)335 }336337 func testSessionExpiringAtEachStepEndsOnTheExpiredResult() async {338 let expired = Fixture.data("flow_live_awaiting_selfie", patch: ["status": "expired"])339 let conflict = Fixture.data("error_invalid_session_state")340 // During a document upload.341 var t = MockTransport()342 t.on("GET", "/", liveAwaitingDocument)343 t.on("POST", "/document", status: 409, conflict)344 var m = model(t)345 await m.start()346 t.on("GET", "/", expired)347 let r = await m.uploadDocument(side: .front, image: jpeg)348 XCTAssertEqual(r, .failed)349 XCTAssertEqual(m.step, .result(.expired))350 XCTAssertEqual(m.resultForDismissal, .completed(status: .expired))351 XCTAssertFalse(m.canWithdraw)352 XCTAssertFalse(m.canChangeMethod)353 // Late actions on the expired session change nothing and do not crash.354 m.changeMethod(); m.resumeCapture(); m.continueFromIntro(); m.declineConsent()355 await m.skipDocumentBack()356 XCTAssertEqual(m.step, .result(.expired))357358 // When asking for a selfie challenge.359 t = MockTransport()360 t.on("GET", "/", fixture: "flow_live_awaiting_selfie")361 t.on("POST", "/selfie/challenge", status: 409, conflict)362 m = model(t)363 await m.start()364 XCTAssertEqual(m.step, .selfie)365 t.on("GET", "/", expired)366 do { _ = try await m.requestChallenge(accessible: false); XCTFail() } catch { XCTAssertEqual((error as? IdentityError)?.code, "invalid_session_state") }367 XCTAssertEqual(m.step, .result(.expired))368369 // When sending the selfie, then when submitting.370 for failing in ["/selfie", "/submit"] {371 t = MockTransport()372 t.on("GET", "/", fixture: "flow_live_awaiting_selfie")373 if failing == "/submit" { t.on("POST", "/selfie", fixture: "selfie_accepted") }374 t.on("POST", failing, status: 409, conflict)375 m = model(t)376 await m.start()377 t.on("GET", "/", expired)378 let ok = await m.uploadSelfie(challengeID: "chl_x", frames: [jpeg, jpeg, jpeg])379 XCTAssertEqual(ok, failing == "/submit", failing)380 XCTAssertEqual(m.step, .result(.expired), failing)381 XCTAssertFalse(m.isBusy)382 }383384 // The resynchronisation itself fails: the error is kept, the step does not move, nothing crashes.385 t = MockTransport()386 t.on("GET", "/", liveAwaitingDocument)387 t.on("POST", "/document", status: 409, conflict)388 m = model(t, policy: .none)389 await m.start()390 t.fail("GET", "/", URLError(.notConnectedToInternet))391 _ = await m.uploadDocument(side: .front, image: jpeg)392 XCTAssertEqual(m.step, .documentFront)393 XCTAssertEqual(m.lastError?.code, "invalid_session_state")394 }395396 func testSelfieWhoseAnswerWasLostIsRecognisedAsSent() async {397 let t = MockTransport()398 t.on("GET", "/", fixture: "flow_live_awaiting_selfie")399 t.on("POST", "/selfie", fixture: "error_invalid_challenge", status: 409)400 t.on("POST", "/submit", fixture: "flow_live_processing")401 let m = model(t)402 await m.start()403 t.on("GET", "/", Fixture.data("flow_live_awaiting_selfie", patch: ["selfie_done": true]))404 let ok = await m.uploadSelfie(challengeID: "chl_used", frames: [jpeg, jpeg, jpeg])405 XCTAssertTrue(ok)406 XCTAssertEqual(m.step, .processing)407 m.stop()408 // The frames are not there: the challenge really is invalid, a new capture is needed.409 let u = MockTransport()410 u.on("GET", "/", fixture: "flow_live_awaiting_selfie")411 u.on("POST", "/selfie", fixture: "error_invalid_challenge", status: 409)412 let n = model(u)413 await n.start()414 let ko = await n.uploadSelfie(challengeID: "chl_used", frames: [jpeg, jpeg, jpeg])415 XCTAssertFalse(ko)416 XCTAssertEqual(n.lastError?.code, "invalid_challenge")417 XCTAssertEqual(n.step, .selfie)418 }419420 func testConsentCanBeWithdrawnDuringManualReview() async {421 let t = MockTransport()422 t.on("GET", "/", Fixture.data("flow_live_processing", patch: ["status": "manual_review"]))423 t.on("POST", "/withdraw", fixture: "withdraw")424 let m = model(t)425 await m.start()426 XCTAssertEqual(m.step, .result(.manualReview))427 XCTAssertTrue(m.canWithdraw)428 XCTAssertEqual(m.resultForDismissal, .completed(status: .manualReview))429 await m.withdraw()430 XCTAssertEqual(m.step, .result(.cancelled))431 XCTAssertEqual(m.resultForDismissal, .canceled)432 XCTAssertFalse(m.canWithdraw)433 }434435 func testMethodCanBeChangedWhileAwaitingSelfie() async {436 let t = MockTransport()437 t.on("GET", "/", fixture: "flow_live_awaiting_selfie")438 let m = model(t)439 await m.start()440 XCTAssertEqual(m.step, .selfie)441 XCTAssertTrue(m.canChangeMethod)442 m.changeMethod()443 XCTAssertEqual(m.step, .method)444 m.resumeCapture() // changed their mind: nothing was sent, nothing is lost445 XCTAssertEqual(m.step, .selfie)446 XCTAssertEqual(t.log, ["GET /"])447 m.changeMethod()448 m.selectMethod("document_review")449 XCTAssertEqual(m.step, .consent(methodID: "document_review"))450 t.on("POST", "/consent", Fixture.data("flow_live_awaiting_selfie", patch: ["status": "awaiting_document", "method": "document_review", "uploaded": [String: Bool]()]))451 await m.acceptConsent()452 XCTAssertEqual(m.step, .documentFront) // the service reset the uploads453 XCTAssertEqual(m.state?.method, "document_review")454 let body = try! JSONSerialization.jsonObject(with: t.requests.last!.httpBody!) as! [String: Any]455 XCTAssertEqual(body["method"] as? String, "document_review")456 XCTAssertEqual(body["text_version"] as? String, m.methods.first { $0.id == "document_review" }?.consentText(m.language)?.version)457 XCTAssertNil(body["biometric_consent"])458 // Sandbox sessions and single-method sessions do not offer it.459 let s = MockTransport()460 s.on("GET", "/", fixture: "flow_awaiting_document")461 let sandbox = model(s)462 await sandbox.start()463 XCTAssertFalse(sandbox.canChangeMethod)464 }465466 func testResumeShowsWhyTheCaptureMustBeRedone() async {467 let issue: [[String: Any]] = [["code": "capture_quality_insufficient", "message": ["fr": "La qualité de capture est insuffisante.", "en": "The capture quality is insufficient."]]]468 let t = MockTransport()469 t.on("GET", "/", Fixture.data("flow_live_awaiting_selfie", patch: ["status": "awaiting_document", "uploaded": [String: Bool](), "attempts_left": 1, "last_issue": issue]))470 let m = model(t)471 await m.start()472 XCTAssertEqual(m.step, .documentFront)473 XCTAssertTrue(m.retryRequested)474 XCTAssertEqual(m.lastIssue.map(\.code), ["capture_quality_insufficient"])475 XCTAssertEqual(m.lastIssue[0].message[.en], "The capture quality is insufficient.")476 XCTAssertEqual(m.state?.attemptsLeft, 1)477 XCTAssertEqual(m.state?.maxAttempts, 3)478 }479480 func testReviewNotCompletedEndsInconclusiveAndCanBeContested() async {481 let result: [String: Any] = ["status": "inconclusive", "reasons": [["code": "review_not_completed", "message": ["fr": "a", "en": "b"]]]]482 let t = MockTransport()483 t.on("GET", "/", Fixture.data("flow_live_processing", patch: ["status": "manual_review"]))484 let m = model(t)485 await m.start()486 XCTAssertEqual(m.step, .result(.manualReview))487 t.on("GET", "/", Fixture.data("flow_live_processing", patch: ["status": "inconclusive", "result": result]))488 await m.refresh()489 XCTAssertEqual(m.step, .result(.inconclusive))490 XCTAssertEqual(m.state?.result?.reasons.map(\.code), ["review_not_completed"])491 XCTAssertEqual(m.resultForDismissal, .completed(status: .inconclusive))492 XCTAssertFalse(m.canWithdraw)493 }494495 func testPollingFollowsRetryAfter() async {496 let t = MockTransport()497 t.on("GET", "/", fixture: "flow_live_processing")498 t.on("GET", "/", fixture: "error_rate_limited", status: 429, headers: ["Retry-After": "22"])499 t.on("GET", "/", status: 503, headers: ["Retry-After": "600"], errorBody("service_unavailable"))500 t.on("GET", "/", liveVerified)501 let delays = Waits()502 let m = VerificationFlowModel(client: IdentityClient(session: testSession, transport: t, retryPolicy: .none)) { d in503 delays.add(d)504 await Task.yield()505 }506 m.pollJitter = 0507 await m.start()508 await wait(m, for: .result(.verified))509 XCTAssertEqual(delays.values, [1.0, 22, 60]) // the service's wait, capped at one minute510 }511512 func testPollingDelaysAreSpreadRandomly() async {513 let t = MockTransport()514 for _ in 0..<4 { t.on("GET", "/", fixture: "flow_live_processing") }515 t.on("GET", "/", liveVerified)516 let delays = Waits()517 let m = VerificationFlowModel(client: IdentityClient(session: testSession, transport: t, retryPolicy: .none)) { d in518 delays.add(d)519 await Task.yield()520 }521 await m.start() // default jitter: ±20 %522 await wait(m, for: .result(.verified))523 let base = [1.0, 1.5, 2.25, 3.375]524 XCTAssertEqual(delays.values.count, base.count)525 for (d, b) in zip(delays.values, base) { XCTAssertTrue((b * 0.8...b * 1.2).contains(d), "\(d) vs \(b)") }526 }527528 func testAnAnswerArrivingAfterStopDoesNotRestartPolling() async {529 let t = MockTransport()530 t.on("GET", "/", fixture: "flow_live_awaiting_selfie")531 t.on("POST", "/selfie", fixture: "selfie_accepted")532 t.on("POST", "/submit", fixture: "flow_live_processing")533 let m = model(t)534 await m.start()535 m.stop() // the flow is dismissed…536 _ = await m.uploadSelfie(challengeID: "chl_x", frames: [jpeg, jpeg, jpeg]) // …while an upload was still under way537 XCTAssertEqual(m.step, .processing)538 try? await Task.sleep(nanoseconds: 30_000_000)539 XCTAssertEqual(t.count("GET /"), 1) // no polling was started540 t.on("GET", "/", fixture: "flow_live_processing")541 await m.start() // presenting the flow again resumes normally542 try? await Task.sleep(nanoseconds: 30_000_000)543 XCTAssertGreaterThan(t.count("GET /"), 2)544 m.stop()545 }546547 func testADisputeAlreadyRecordedCountsAsSent() async {548 let t = MockTransport()549 t.on("GET", "/", fixture: "flow_sandbox_rejected")550 t.on("POST", "/dispute", fixture: "error_dispute_exists", status: 409)551 let m = model(t)552 await m.start()553 XCTAssertTrue(m.canDispute)554 let ok = await m.dispute(message: "Please review my document again.")555 XCTAssertTrue(ok)556 XCTAssertTrue(m.disputeSent)557 XCTAssertNil(m.lastError)558 XCTAssertFalse(m.canDispute)559 }560}561