Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Tests/AppTests/SearchModelTests.swift10// Description : Search model against a scripted service: debounce and11// cancellation of suggestions, stale answers, paging, rate12// limit, history, region.13// Module : AppTests14// Repository : https://git.spboucher.ai/sp-search-ios15// Project Website : https://search.spboucher.ai16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import SPSearchKit93import Testing94@testable import SPSearch9596/// Scripted service: answers are queued per call, each call is recorded, a call can be held until released.97actor ScriptedService: SearchService {98 private(set) var searches: [SearchRequest] = []99 private(set) var suggestCalls: [String] = []100 private var searchReplies: [Result<SearchResponse, SearchError>] = []101 private var gates: [CheckedContinuation<Void, Never>] = []102 private var holdNext = 0103 var suggestions: [String: [String]] = [:]104105 func queue(_ reply: Result<SearchResponse, SearchError>) { searchReplies.append(reply) }106 func setSuggestions(_ s: [String: [String]]) { suggestions = s }107 /// The next `n` searches wait for `release()`.108 func hold(_ n: Int) { holdNext = n }109 func release() { if !gates.isEmpty { gates.removeFirst().resume() } }110 var waiting: Int { gates.count }111112 private(set) var policies: [CachePolicy] = []113 private(set) var filterCalls = 0114 var catalog = FilterCatalog.minimal115 var rich: [String: [Suggestion]] = [:]116 func setCatalog(_ c: FilterCatalog) { catalog = c }117 func setRich(_ r: [String: [Suggestion]]) { rich = r }118119 func search(_ request: SearchRequest, policy: CachePolicy) async throws -> SearchResponse {120 searches.append(request)121 policies.append(policy)122 let reply = searchReplies.isEmpty ? .failure(SearchError.http(status: 599, message: "no scripted reply")) : searchReplies.removeFirst()123 if holdNext > 0 {124 holdNext -= 1125 await withCheckedContinuation { gates.append($0) }126 }127 return try reply.get()128 }129130 func autocomplete(_ query: String) async throws -> [Suggestion] {131 suggestCalls.append(query)132 return rich[query] ?? (suggestions[query] ?? []).map { Suggestion(text: $0) }133 }134135 func filters() async throws -> FilterCatalog { filterCalls += 1; return catalog }136137 func status() async throws -> EngineStatus { EngineStatus(level: .ok, documents: 10, domains: 2) }138}139140func page(_ ids: [String], next: String? = nil, notices: [SearchNotice] = []) -> SearchResponse {141 SearchResponse(results: ids.map { SearchResult(id: $0, title: "t\($0)", url: "https://e.org/\($0)", domain: "e.org") },142 nextCursor: next, total: ResultTotal(value: 30, relation: .exact), notices: notices,143 region: AppliedRegion(value: "ca", source: .browser))144}145146@MainActor147struct Rig {148 let service = ScriptedService()149 let model: SearchModel150 let settings: AppSettings151 let history: HistoryStore152 let slept = Slept()153154 final class Slept: @unchecked Sendable {155 private let lock = NSLock()156 private var list: [Duration] = []157 func add(_ d: Duration) { lock.withLock { list.append(d) } }158 var all: [Duration] { lock.withLock { list } }159 }160161 init(realDebounce: Duration? = nil) {162 let name = "spsearch.apptests.\(UUID().uuidString)"163 let defaults = UserDefaults(suiteName: name)!164 defaults.removePersistentDomain(forName: name)165 settings = AppSettings(defaults: defaults)166 history = HistoryStore(defaults: defaults)167 let slept = slept168 model = SearchModel(service: service, settings: settings, history: history, debounce: realDebounce ?? .milliseconds(150),169 interfaceLanguage: "fr", now: { Date(timeIntervalSince1970: 1_800_000_000) },170 sleep: { d in171 slept.add(d)172 if realDebounce != nil { try await Task.sleep(for: d) } else { try Task.checkCancellation() }173 })174 }175}176177/// Lets the model's tasks run until `condition` holds (at most two seconds).178@MainActor func until(_ condition: @MainActor () async -> Bool) async {179 for _ in 0..<400 {180 if await condition() { return }181 try? await Task.sleep(for: .milliseconds(5))182 }183}184185@MainActor @Suite struct SearchModelTests {186 @Test func submitLoadsTheFirstPageAndRecordsHistory() async {187 let rig = Rig()188 await rig.service.queue(.success(page(["a", "b"], next: "c1")))189 rig.model.updateText(" Université Laval ")190 rig.model.submit()191 #expect(rig.model.phase == .loading)192 #expect(rig.model.query == "Université Laval")193 #expect(rig.model.text == "Université Laval")194 await rig.model.searchTask?.value195 #expect(rig.model.phase == .loaded)196 #expect(rig.model.results.map(\.id) == ["a", "b"])197 #expect(rig.model.highlightTerms == ["Université", "Laval"])198 #expect(rig.history.entries.map(\.query) == ["Université Laval"])199 let sent = await rig.service.searches200 #expect(sent.count == 1)201 #expect(sent.first?.limit == 10)202 #expect(sent.first?.cursor == nil)203 #expect(sent.first?.interfaceLanguage == "fr")204 #expect(sent.first?.region == .automatic)205 }206207 @Test func emptyTextSearchesNothing() async {208 let rig = Rig()209 rig.model.updateText(" ")210 rig.model.submit()211 #expect(rig.model.phase == .idle)212 #expect(await rig.service.searches.isEmpty)213 #expect(rig.history.entries.isEmpty)214 }215216 @Test func typingNeverSearchesAndSuggestionsAreDebounced() async {217 let rig = Rig(realDebounce: .milliseconds(60))218 await rig.service.setSuggestions(["univ": ["university", "universite"], "un": ["une"], "uni": ["unique"]])219 // Three keystrokes faster than the pause: one request, for the last text.220 rig.model.updateText("un")221 rig.model.updateText("uni")222 rig.model.updateText("univ")223 await until { rig.model.suggestions.count == 2 }224 #expect(rig.model.suggestions.map(\.text) == ["university", "universite"])225 #expect(await rig.service.suggestCalls == ["univ"])226 #expect(await rig.service.searches.isEmpty)227 #expect(rig.slept.all == [.milliseconds(60), .milliseconds(60), .milliseconds(60)])228 }229230 @Test func shortTextClearsSuggestionsWithoutAnyRequest() async {231 let rig = Rig()232 await rig.service.setSuggestions(["laval": ["laval université"]])233 rig.model.updateText("laval")234 await rig.model.suggestTask?.value235 #expect(rig.model.suggestions.map(\.text) == ["laval université"])236 rig.model.updateText("l")237 #expect(rig.model.suggestions.isEmpty)238 await rig.model.suggestTask?.value239 #expect(await rig.service.suggestCalls == ["laval"])240 }241242 @Test func submittingCancelsPendingSuggestions() async {243 let rig = Rig(realDebounce: .milliseconds(80))244 await rig.service.setSuggestions(["laval": ["laval université"]])245 await rig.service.queue(.success(page(["a"])))246 rig.model.updateText("laval")247 rig.model.submit()248 await rig.model.searchTask?.value249 try? await Task.sleep(for: .milliseconds(160))250 #expect(rig.model.suggestions.isEmpty)251 #expect(await rig.service.suggestCalls.isEmpty)252 }253254 @Test func aStaleAnswerNeverReplacesANewerSearch() async {255 let rig = Rig()256 await rig.service.queue(.success(page(["old"])))257 await rig.service.queue(.success(page(["new"])))258 await rig.service.hold(1) // the first search hangs259 rig.model.submit("premier")260 await until { await rig.service.waiting == 1 }261 rig.model.submit("second")262 await rig.model.searchTask?.value263 #expect(rig.model.results.map(\.id) == ["new"])264 await rig.service.release() // the first one answers late265 try? await Task.sleep(for: .milliseconds(40))266 #expect(rig.model.results.map(\.id) == ["new"])267 #expect(rig.model.query == "second")268 #expect(rig.model.phase == .loaded)269 }270271 @Test func pagingAsksOnePageAtATimeWithThePreviousCursor() async {272 let rig = Rig()273 await rig.service.queue(.success(page(["a", "b"], next: "c1")))274 await rig.service.queue(.success(page(["b", "c"], next: "c2")))275 await rig.service.queue(.success(page(["d"], next: nil)))276 rig.model.submit("x")277 await rig.model.searchTask?.value278 await rig.service.hold(1)279 rig.model.loadMoreIfNeeded()280 rig.model.loadMoreIfNeeded() // a second call while one page is in flight does nothing281 await until { await rig.service.waiting == 1 }282 #expect(rig.model.more == .loading)283 #expect(await rig.service.searches.count == 2)284 await rig.service.release()285 await rig.model.moreTask?.value286 #expect(rig.model.results.map(\.id) == ["a", "b", "c"])287 rig.model.loadMoreIfNeeded()288 await rig.model.moreTask?.value289 #expect(rig.model.results.map(\.id) == ["a", "b", "c", "d"])290 #expect(!rig.model.pages.canLoadMore)291 rig.model.loadMoreIfNeeded() // end of list: nothing is asked292 let sent = await rig.service.searches293 #expect(sent.map(\.cursor) == [nil, "c1", "c2"])294 #expect(Set(sent.map(\.query)) == ["x"])295 }296297 @Test func aRateLimitedPageWaitsForRetryAfterThenContinues() async {298 let rig = Rig()299 await rig.service.queue(.success(page(["a"], next: "c1")))300 await rig.service.queue(.failure(.rateLimited(retryAfter: 7)))301 await rig.service.queue(.success(page(["b"], next: nil)))302 rig.model.submit("x")303 await rig.model.searchTask?.value304 rig.model.loadMoreIfNeeded()305 await rig.model.moreTask?.value306 #expect(rig.slept.all == [.seconds(7)])307 #expect(rig.model.results.map(\.id) == ["a", "b"])308 #expect(rig.model.more == .idle)309 #expect(await rig.service.searches.map(\.cursor) == [nil, "c1", "c1"])310 }311312 @Test func repeatedRateLimitsStopAndAskTheReader() async {313 let rig = Rig()314 await rig.service.queue(.success(page(["a"], next: "c1")))315 for _ in 0..<3 { await rig.service.queue(.failure(.rateLimited(retryAfter: 2))) }316 await rig.service.queue(.success(page(["b"], next: nil)))317 rig.model.submit("x")318 await rig.model.searchTask?.value319 rig.model.loadMoreIfNeeded()320 await rig.model.moreTask?.value321 #expect(rig.model.more == .failed(.rateLimited(retryAfter: 2)))322 #expect(rig.slept.all.count == SearchModel.automaticRetries)323 rig.model.loadMoreIfNeeded() // no silent retry once failed324 #expect(await rig.service.searches.count == 4)325 rig.model.retryMore()326 await rig.model.moreTask?.value327 #expect(rig.model.results.map(\.id) == ["a", "b"])328 }329330 @Test func aFailedFirstPageSaysWhatHappenedAndCanBeRetried() async {331 let rig = Rig()332 await rig.service.queue(.failure(.offline))333 await rig.service.queue(.success(page(["a"])))334 rig.model.submit("x")335 await rig.model.searchTask?.value336 #expect(rig.model.phase == .failed(.offline))337 rig.model.retry()338 await rig.model.searchTask?.value339 #expect(rig.model.phase == .loaded)340 }341342 @Test func aFailedRefreshKeepsThePreviousResults() async {343 let rig = Rig()344 await rig.service.queue(.success(page(["a"], next: "c1")))345 await rig.service.queue(.failure(.timedOut))346 rig.model.submit("x")347 await rig.model.searchTask?.value348 await rig.model.refresh()349 #expect(rig.model.phase == .loaded)350 #expect(rig.model.results.map(\.id) == ["a"])351 #expect(rig.model.refreshError == .timedOut)352 }353354 @Test func filtersAndRegionRestartFromTheFirstPage() async {355 let rig = Rig()356 for id in ["a", "b", "c", "d"] { await rig.service.queue(.success(page([id], next: "n-\(id)"))) }357 rig.model.submit("x")358 await rig.model.searchTask?.value359 rig.model.apply(SearchFilters(language: "fr", site: "ulaval.ca"))360 await rig.model.searchTask?.value361 rig.model.apply(SearchFilters(language: "fr", site: "ulaval.ca")) // unchanged: no request362 rig.model.setRegion(.quebec)363 await rig.model.searchTask?.value364 #expect(rig.settings.region == .quebec)365 let sent = await rig.service.searches366 #expect(sent.count == 3)367 #expect(sent.map(\.cursor) == [nil, nil, nil])368 #expect(sent.last?.filters == SearchFilters(language: "fr", site: "ulaval.ca"))369 #expect(sent.last?.region == .quebec)370 #expect(rig.model.results.map(\.id) == ["c"])371 // A new query starts without the filters of the previous one, and keeps the region.372 rig.model.submit("y")373 await rig.model.searchTask?.value374 #expect(rig.model.filters.isEmpty)375 #expect(await rig.service.searches.last?.region == .quebec)376 }377378 @Test func moreFromThisSiteRewritesTheQuery() async {379 let rig = Rig()380 await rig.service.queue(.success(page(["a"])))381 await rig.service.queue(.success(page(["b"])))382 rig.model.submit("laval site:old.org")383 await rig.model.searchTask?.value384 rig.model.moreFromSite("ulaval.ca")385 await rig.model.searchTask?.value386 #expect(rig.model.query == "laval site:ulaval.ca")387 #expect(rig.model.text == "laval site:ulaval.ca")388 }389390 @Test func historySwitchStopsRecordingAndClearEmptiesIt() async {391 let rig = Rig()392 for _ in 0..<3 { await rig.service.queue(.success(page(["a"]))) }393 rig.model.submit("un")394 rig.model.setHistoryEnabled(false)395 rig.model.submit("deux")396 #expect(rig.model.history.map(\.query) == ["un"])397 #expect(!rig.model.historyEnabled)398 rig.model.setHistoryEnabled(true)399 rig.model.submit("trois")400 #expect(rig.model.history.map(\.query) == ["trois", "un"])401 rig.model.removeFromHistory("un")402 #expect(rig.history.entries.map(\.query) == ["trois"])403 rig.model.clearHistory()404 #expect(rig.model.history.isEmpty)405 #expect(rig.history.entries.isEmpty)406 }407408 @Test func goingHomeDropsTheSearchAndIgnoresItsLateAnswer() async {409 let rig = Rig()410 await rig.service.queue(.success(page(["a"])))411 await rig.service.hold(1)412 rig.model.submit("x")413 await until { await rig.service.waiting == 1 }414 rig.model.goHome()415 await rig.service.release()416 try? await Task.sleep(for: .milliseconds(40))417 #expect(rig.model.phase == .idle)418 #expect(!rig.model.hasSearch)419 #expect(rig.model.results.isEmpty)420 #expect(rig.model.text.isEmpty)421 }422423 @Test func statusLoadsOnce() async {424 let rig = Rig()425 await rig.model.loadStatus()426 #expect(rig.model.status == .loaded(EngineStatus(level: .ok, documents: 10, domains: 2)))427 }428}429430@MainActor @Suite struct DisplayTests {431 @Test func breadcrumb() {432 #expect(Format.breadcrumb("https://www.ulaval.ca/", domain: "ulaval.ca") == "ulaval.ca")433 #expect(Format.breadcrumb("https://www.uneq.qc.ca/category/grands-dossiers/copibec/page/2/", domain: "uneq.qc.ca") == "uneq.qc.ca › category › grands-dossiers › copibec › …")434 #expect(Format.breadcrumb("https://fr.wikipedia.org/wiki/Universit%C3%A9_Laval", domain: "wikipedia.org") == "fr.wikipedia.org › wiki › Université_Laval")435 #expect(Format.breadcrumb("pas une adresse", domain: "") == "pas une adresse")436 }437438 @Test func appliedRegionIsWhatTheServerReports() {439 #expect(Format.applied(nil) == nil)440 #expect(Format.applied(AppliedRegion(value: "ca-qc", source: .choice))?.contains("Canada") == true)441 #expect(Format.applied(AppliedRegion(value: "ca-qc", source: .choice))?.hasSuffix(")") == true)442 #expect(Format.applied(AppliedRegion(value: nil, source: .off)) == Format.regionOption(.off))443 #expect(Format.applied(AppliedRegion(value: nil, source: AppliedRegion.Source.none)) != nil)444 }445446 @Test func markedSnippetKeepsItsTextAndFlagsTheTerms() {447 let r = SearchResult(id: "1", title: "t", url: "https://e.org", domain: "e.org", snippet: "Université Laval à Québec")448 let a = ResultText.snippet(r, terms: ["universite", "quebec"])449 #expect(String(a.characters) == "Université Laval à Québec")450 #expect(a.runs.filter { $0.inlinePresentationIntent == .stronglyEmphasized }.count == 2)451 }452453 @Test func metadataLeavesOutWhatIsUnknown() {454 let bare = SearchResult(id: "1", title: "t", url: "https://e.org", domain: "e.org")455 #expect(ResultText.facts(bare) == "")456 #expect(Format.validation(bare) == nil)457 let now = Date(timeIntervalSince1970: 1_800_000_000)458 let full = SearchResult(id: "2", title: "t", url: "https://e.org", domain: "e.org", language: "fr", checkedAt: now.addingTimeInterval(-7200), words: 460, kind: .encyclopedia)459 #expect(ResultText.facts(full).components(separatedBy: " · ").count == 2) // type, language; no publication date460 #expect(Format.validation(full, now: now)?.text.contains("2") == true)461 #expect(Format.validation(full, now: now)?.warning == false)462 }463464 @Test func everyErrorHasWordsAndEveryNoticeAText() {465 let errors: [SearchError] = [.offline, .timedOut, .rateLimited(retryAfter: 3), .unavailable(message: nil), .badRequest(message: ""),466 .badRequest(message: "requête vide"), .http(status: 502, message: nil), .invalidResponse, .network(code: -1003)]467 for e in errors {468 #expect(!Format.error(e).title.isEmpty)469 #expect(!Format.error(e).detail.isEmpty)470 }471 #expect(Format.error(.badRequest(message: "requête vide")).detail == "requête vide")472 for n in [SearchNotice.phraseUnsupported, .phraseUnverified, .relaxedToAnyTerm, .depthLimit, .partialShards, .cursorExpired, .degradedMetadata, .semanticUnavailable, .unknown("x")] {473 #expect(!Format.notice(n).isEmpty)474 }475 #expect(Format.notice(.unknown("nouveau_code")).contains("nouveau_code"))476 }477}478