Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Tests/AppTests/V2ModelTests.swift10// Description : V2 behaviour of the app: correction flow, categories from11// the catalog, links, cache policy, typed suggestions,12// history effects, favorites, Spotlight, wording of the13// address check.14// Module : AppTests15// Repository : https://git.spboucher.ai/sp-search-ios16// Project Website : https://search.spboucher.ai17// Created : 2026-12-0118// Last Modified : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import CoreSpotlight93import Foundation94import SPSearchKit95import Testing96@testable import SPSearch9798func corrected(_ ids: [String], applied: Bool, original: String, suggestion: String) -> SearchResponse {99 SearchResponse(results: ids.map { SearchResult(id: $0, title: "t\($0)", url: "https://e.org/\($0)", domain: "e.org") },100 query: QueryInfo(raw: original, effective: applied ? suggestion : original,101 correction: QueryInfo.Correction(applied: applied, original: original, suggestion: suggestion)))102}103104let newsCatalog = FilterCatalog(verticals: [.init(id: "web", documents: 100), .init(id: "news", documents: 10)],105 languages: [.init(value: "fr", documents: 5)], kinds: ["news", "blog"], regions: ["ca", "ca-qc", "zz"], fresh: ["day", "week"])106107@MainActor @Suite struct CorrectionFlowTests {108 @Test func appliedCorrectionOffersTheOriginalAndSendsCorrectZero() async {109 let rig = Rig()110 await rig.service.queue(.success(corrected(["a", "b"], applied: true, original: "univeristé lavla", suggestion: "université laval")))111 await rig.service.queue(.success(corrected(["c"], applied: false, original: "univeristé lavla", suggestion: "université laval")))112 await rig.service.queue(.success(page(["d"])))113 rig.model.submit("univeristé lavla")114 await rig.model.searchTask?.value115 // The field and the history keep what the reader wrote; the banner says what the server searched.116 #expect(rig.model.query == "univeristé lavla")117 #expect(rig.model.text == "univeristé lavla")118 #expect(rig.model.correction == QueryInfo.Correction(applied: true, original: "univeristé lavla", suggestion: "université laval"))119 #expect(rig.model.autocorrect)120 #expect(rig.model.results.map(\.id) == ["a", "b"]) // the server's list, in the server's order121 #expect(await rig.service.searches.last?.correct == true)122123 rig.model.searchVerbatim("univeristé lavla") // "search instead for"124 await rig.model.searchTask?.value125 #expect(!rig.model.autocorrect)126 #expect(rig.model.query == "univeristé lavla")127 #expect(await rig.service.searches.last?.correct == false)128 #expect(await rig.service.searches.last?.query == "univeristé lavla")129 #expect(rig.model.correction?.applied == false) // now a mere proposal130 #expect(rig.model.results.map(\.id) == ["c"])131 #expect(rig.history.entries.map(\.query) == ["univeristé lavla"]) // not recorded twice132133 rig.model.submit(rig.model.correction!.suggestion) // "try with": an ordinary search, correction back on134 await rig.model.searchTask?.value135 #expect(rig.model.autocorrect)136 #expect(await rig.service.searches.last?.correct == true)137 #expect(await rig.service.searches.last?.query == "université laval")138 #expect(rig.model.correction == nil)139 }140141 @Test func verbatimKeepsFiltersAndPagesStayVerbatim() async {142 let rig = Rig()143 await rig.service.queue(.success(page(["a"], next: "c1")))144 await rig.service.queue(.success(page(["b"], next: "c2")))145 await rig.service.queue(.success(page(["c"], next: "c3")))146 await rig.service.queue(.success(page(["d"])))147 rig.model.submit("lavla")148 await rig.model.searchTask?.value149 rig.model.apply(SearchFilters(language: "fr"))150 await rig.model.searchTask?.value151 rig.model.searchVerbatim("lavla")152 await rig.model.searchTask?.value153 rig.model.loadMoreIfNeeded()154 await rig.model.moreTask?.value155 let sent = await rig.service.searches156 #expect(sent.map(\.correct) == [true, true, false, false]) // the next page carries correct=0 too157 #expect(sent.map(\.cursor) == [nil, nil, nil, "c3"])158 #expect(sent.last?.filters == SearchFilters(language: "fr"))159 rig.model.goHome()160 #expect(rig.model.autocorrect)161 }162}163164@MainActor @Suite struct CatalogTests {165 @Test func onlyTheWebUntilTheServerListsMore() async {166 let rig = Rig()167 #expect(rig.model.verticals.isEmpty) // nothing to choose from: no tabs at all168 rig.model.setVertical("news") // not listed: refused169 #expect(rig.model.vertical == "web")170 rig.model.setVertical("images")171 #expect(rig.model.vertical == "web")172 await rig.service.setCatalog(newsCatalog)173 await rig.model.loadCatalog()174 await rig.model.loadCatalog()175 #expect(await rig.service.filterCalls == 1)176 #expect(rig.model.verticals.map(\.id) == ["web", "news"])177 rig.model.setVertical("images") // still not listed178 #expect(rig.model.vertical == "web")179 #expect(await rig.service.searches.isEmpty)180 }181182 @Test func changingCategoryRerunsTheSearchAndKeepsQueryAndFilters() async {183 let rig = Rig()184 await rig.service.setCatalog(newsCatalog)185 await rig.model.loadCatalog()186 for id in ["a", "b", "c"] { await rig.service.queue(.success(page([id], next: "n"))) }187 rig.model.submit("budget")188 await rig.model.searchTask?.value189 rig.model.apply(SearchFilters(fresh: "week"))190 await rig.model.searchTask?.value191 rig.model.setVertical("news")192 await rig.model.searchTask?.value193 rig.model.setVertical("news") // unchanged: no request194 let sent = await rig.service.searches195 #expect(sent.map(\.vertical) == ["web", "web", "news"])196 #expect(sent.last?.query == "budget")197 #expect(sent.last?.filters == SearchFilters(fresh: "week"))198 #expect(sent.last?.cursor == nil)199 #expect(rig.model.results.map(\.id) == ["c"])200 }201202 @Test func aLinkOpensItsSearchAndDropsWhatTheServerDoesNotList() async {203 let rig = Rig()204 await rig.service.setCatalog(newsCatalog)205 await rig.service.queue(.success(page(["a"])))206 await rig.service.queue(.success(page(["b"])))207 guard case .search(let link)? = SearchLink.parse(URL(string: "https://search.spboucher.ai/search?q=budget+qu%C3%A9bec&vertical=news&lang=fr&fresh=week&kind=news")!) else { Issue.record("not a search"); return }208 await rig.model.open(link)209 await rig.model.searchTask?.value210 #expect(rig.model.query == "budget québec")211 #expect(rig.model.vertical == "news")212 #expect(rig.model.filters == SearchFilters(language: "fr", kind: "news", fresh: "week"))213 #expect(rig.history.entries.map(\.query) == ["budget québec"])214 guard case .search(let odd)? = SearchLink.parse(URL(string: "https://search.spboucher.ai/search?q=chats&vertical=images&fresh=decade&kind=meme&site=e.org")!) else { Issue.record("not a search"); return }215 await rig.model.open(odd)216 await rig.model.searchTask?.value217 #expect(rig.model.vertical == "web") // Images is not listed: the Web218 #expect(rig.model.filters == SearchFilters(site: "e.org"))219 #expect(await rig.service.searches.last?.vertical == "web")220 #expect(rig.model.link.webURL.absoluteString == "https://search.spboucher.ai/search?q=chats&site=e.org")221 }222}223224@MainActor @Suite struct CacheAndSuggestionTests {225 @Test func refreshAndRetryBypassTheCache() async {226 let rig = Rig()227 await rig.service.queue(.success(page(["a"], next: "c1")))228 await rig.service.queue(.success(page(["b"])))229 await rig.service.queue(.success(page(["a2"], next: "c1")))230 await rig.service.queue(.failure(.offline))231 await rig.service.queue(.success(page(["z"])))232 rig.model.submit("x")233 await rig.model.searchTask?.value234 rig.model.loadMoreIfNeeded()235 await rig.model.moreTask?.value236 await rig.model.refresh()237 rig.model.submit("y")238 await rig.model.searchTask?.value239 rig.model.retry()240 await rig.model.searchTask?.value241 #expect(await rig.service.policies == [.useCache, .useCache, .reload, .useCache, .reload])242 }243244 @Test func typedSuggestionsKeepTheServersOrderAndKinds() async {245 let rig = Rig()246 await rig.service.setRich(["univ": [Suggestion(text: "univ", kind: .completion), Suggestion(text: "université laval"),247 Suggestion(text: "ulaval.ca", kind: .site, url: "https://www.ulaval.ca/", title: "Université Laval"),248 Suggestion(text: "université", kind: .correction)]])249 rig.model.updateText("univ")250 await rig.model.suggestTask?.value251 #expect(rig.model.suggestions.map(\.text) == ["université laval", "ulaval.ca", "université"]) // only the echo of the text is left out252 #expect(rig.model.suggestions.map(\.kind) == [.completion, .site, .correction])253 #expect(SuggestionsPanel.completion("université laval", typed: "univ").runs.count == 2)254 #expect(SuggestionsPanel.completion("laval", typed: "univ").runs.count == 1)255 }256}257258@MainActor @Suite struct HistoryEffectsTests {259 final class Log: @unchecked Sendable {260 private let lock = NSLock()261 private var list: [String] = []262 func add(_ s: String) { lock.withLock { list.append(s) } }263 var all: [String] { lock.withLock { list } }264 }265266 @Test func spotlightWidgetAndCacheFollowTheHistory() async {267 let name = "spsearch.apptests.\(UUID().uuidString)"268 let defaults = UserDefaults(suiteName: name)!269 defaults.removePersistentDomain(forName: name)270 let log = Log()271 let service = ScriptedService()272 for _ in 0..<3 { await service.queue(.success(page(["a"]))) }273 let effects = HistoryEffects(changed: { entries, enabled in log.add("changed \(entries.map(\.query)) \(enabled)") }, cleared: { log.add("cleared") })274 let model = SearchModel(service: service, settings: AppSettings(defaults: defaults), history: HistoryStore(defaults: defaults), effects: effects, interfaceLanguage: "fr")275 model.submit("un")276 model.setHistoryEnabled(false)277 model.submit("deux") // history off: nothing recorded, nothing announced278 model.setHistoryEnabled(true)279 model.removeFromHistory("un")280 model.submit("trois")281 model.clearHistory()282 #expect(log.all == [#"changed ["un"] true"#, #"changed ["un"] false"#, #"changed ["un"] true"#, "changed [] true", #"changed ["trois"] true"#, "changed [] true", "cleared"])283 }284}285286@MainActor @Suite struct FavoritesModelTests {287 @Test func toggleSavesAndRemovesAndAnnouncesTheList() {288 let file = FileManager.default.temporaryDirectory.appendingPathComponent("spsearch-fav-\(UUID().uuidString)/favorites.json")289 defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }290 let log = HistoryEffectsTests.Log()291 let model = FavoritesModel(store: FavoritesStore(file: file), now: { Date(timeIntervalSince1970: 1_800_000_000) }, changed: { log.add($0.map(\.url).joined(separator: ",")) })292 let r = SearchResult(id: "1", title: "Université Laval", url: "https://www.ulaval.ca/", domain: "ulaval.ca", snippet: "s", siteName: "Université Laval", faviconPath: "/v2/favicon?domain=ulaval.ca")293 #expect(!model.contains(r.url))294 #expect(model.toggle(r))295 #expect(model.contains(r.url))296 #expect(model.items.first?.siteName == "Université Laval")297 #expect(FavoritesModel(store: FavoritesStore(file: file)).items.count == 1) // persisted298 #expect(!model.toggle(r))299 #expect(model.items.isEmpty)300 #expect(log.all == ["https://www.ulaval.ca/", ""])301 }302}303304@MainActor @Suite struct SpotlightTests {305 @Test func identifiersRoundTrip() {306 #expect(Spotlight.target(identifier: Spotlight.identifier(query: "\"vision collective\" laval")) == .search("\"vision collective\" laval"))307 #expect(Spotlight.target(identifier: Spotlight.identifier(favorite: "https://www.ulaval.ca/a|b")) == .page(URL(string: "https://www.ulaval.ca/a%7Cb") ?? URL(string: "https://www.ulaval.ca/")!)308 || Spotlight.target(identifier: Spotlight.identifier(favorite: "https://www.ulaval.ca/a|b")) == nil)309 #expect(Spotlight.target(identifier: Spotlight.identifier(favorite: "https://www.ulaval.ca/admission")) == .page(URL(string: "https://www.ulaval.ca/admission")!))310 #expect(Spotlight.target(identifier: "fav|javascript:alert(1)") == nil)311 #expect(Spotlight.target(identifier: "q| ") == nil)312 #expect(Spotlight.target(identifier: "autre") == nil)313 }314315 @Test func activitiesFromTheSystem() {316 let tapped = NSUserActivity(activityType: CSSearchableItemActionType)317 tapped.userInfo = [CSSearchableItemActivityIdentifier: "q|histoire du Québec"]318 #expect(Spotlight.target(activity: tapped) == .search("histoire du Québec"))319 let continued = NSUserActivity(activityType: CSQueryContinuationActionType)320 continued.userInfo = [CSSearchQueryString: " rust documentation "]321 #expect(Spotlight.target(activity: continued) == .search("rust documentation"))322 #expect(Spotlight.target(activity: NSUserActivity(activityType: "autre")) == nil)323 }324325 @Test func itemsCarryWhatTheListsShow() {326 let f = Favorite(url: "https://www.ulaval.ca/", title: "Université Laval", domain: "ulaval.ca", siteName: "UL", snippet: "extrait", savedAt: Date())327 let item = Spotlight.item(f)328 #expect(item.uniqueIdentifier == "fav|https://www.ulaval.ca/")329 #expect(item.domainIdentifier == Spotlight.favoritesDomain)330 #expect(item.attributeSet.title == "Université Laval")331 #expect(item.attributeSet.contentDescription == "extrait")332 let q = Spotlight.item(HistoryEntry(query: "laval", date: Date()))333 #expect(q.uniqueIdentifier == "q|laval")334 #expect(q.domainIdentifier == Spotlight.historyDomain)335 }336}337338@MainActor @Suite struct ResultWordingTests {339 let now = Date(timeIntervalSince1970: 1_800_000_000)340341 private func result(_ state: Validation.State?, checked: TimeInterval? = -7_200, published: Date? = nil) -> SearchResult {342 SearchResult(id: "1", title: "t", url: "https://e.org/", domain: "e.org", checkedAt: checked.map { now.addingTimeInterval($0) }, publishedAt: published,343 validation: state.map { Validation(state: $0, validatedAt: checked.map { now.addingTimeInterval($0) }, httpStatus: 200) })344 }345346 @Test func theAddressCheckIsWordedAsATechnicalCheck() {347 for state in [Validation.State.ok, .changed, .redirected, .unknown] {348 let v = Format.validation(result(state), now: now)349 #expect(v?.warning == false)350 #expect(v?.text.hasPrefix(String(localized: "Adresse vérifiée \("")").trimmingCharacters(in: .whitespaces)) == true)351 }352 #expect(Format.validation(result(.unreachable), now: now)?.warning == true)353 #expect(Format.validation(result(.unreachable, checked: nil), now: now)?.warning == true)354 #expect(Format.validation(result(.ok, checked: nil), now: now) == nil) // nothing known: nothing said355 #expect(Format.validation(result(nil), now: now) != nil) // V1: `checked_at` alone356 }357358 @Test func aPublicationDateIsShownOnlyWhenTheEngineVerifiedOne() {359 #expect(!ResultText.facts(result(.ok)).contains(String(localized: "Publié le \("")").trimmingCharacters(in: .whitespaces)))360 let published = ResultText.facts(result(.ok, published: now.addingTimeInterval(-86_400 * 30)))361 #expect(published.contains(String(localized: "Publié le \("")").trimmingCharacters(in: .whitespaces)))362 #expect(ResultText.spoken(result(.ok), now: now).contains("e.org"))363 }364365 @Test func serverMarksAreUsedAsSentAndV1FallsBackToTheQueryTerms() {366 let v2 = SearchResult(id: "1", title: "Université Laval", url: "https://e.org/", domain: "e.org", snippet: "À Québec 🇨🇦, l’université accueille", serverHighlights: true,367 highlights: [9..<11], titleHighlights: [0..<10])368 let marked = ResultText.snippet(v2, terms: ["quebec", "universite"]) // the terms are ignored: the server decides369 #expect(marked.runs.filter { $0.inlinePresentationIntent == .stronglyEmphasized }.map { String(marked[$0.range].characters) } == ["🇨🇦"])370 let title = ResultText.title(v2)371 #expect(title.runs.filter { $0.inlinePresentationIntent == .stronglyEmphasized }.map { String(title[$0.range].characters) } == ["Université"])372 let none = SearchResult(id: "2", title: "t", url: "https://e.org/", domain: "e.org", snippet: "Québec", serverHighlights: true)373 #expect(ResultText.snippet(none, terms: ["quebec"]).runs.allSatisfy { $0.inlinePresentationIntent != .stronglyEmphasized })374 let v1 = SearchResult(id: "3", title: "t", url: "https://e.org/", domain: "e.org", snippet: "Québec")375 #expect(ResultText.snippet(v1, terms: ["quebec"]).runs.contains { $0.inlinePresentationIntent == .stronglyEmphasized })376 }377378 @Test func labelsOfWhatTheServerLists() {379 #expect(Format.vertical("web") == String(localized: "Web"))380 #expect(Format.vertical("news") == String(localized: "Actualités"))381 #expect(Format.vertical("cartes") == "Cartes") // listed by the server, unknown to the app: shown as written382 #expect(Format.fresh("decade") == "decade")383 #expect(Format.kind("encyclopedia") == PageKind.encyclopedia.label)384 #expect(Format.kind("podcast") == "Podcast")385 #expect(Monogram.letter("www.ulaval.ca") == "U")386 #expect(Monogram.letter("Wikipédia") == "W")387 #expect(Monogram.letter("") == "·")388 #expect(Monogram.tintIndex("ulaval.ca") == Monogram.tintIndex("ULaval.ca"))389 #expect(EngineStatusLine.summary(EngineStatus(level: .ok, documents: 10, domains: 2)).components(separatedBy: " · ").count == 3)390 #expect(EngineStatusLine.summary(EngineStatus(documents: 0, domains: 0)).isEmpty) // V1 figures missing: nothing invented391 }392}393394@MainActor @Suite(.serialized) struct RoutingTests {395 @Test func linksActivitiesAndIntentsLeaveTheirRequestForTheInterface() async throws {396 Router.shared.pending = nil397 SPSearchApp.route(URL(string: "https://search.spboucher.ai/search?q=universit%C3%A9+laval&lang=fr")!)398 #expect(Router.shared.pending == .search(SearchLink(query: "université laval", filters: SearchFilters(language: "fr"))))399 SPSearchApp.route(URL(string: "https://example.org/search?q=x")!) // not ours: nothing changes400 #expect(Router.shared.pending == .search(SearchLink(query: "université laval", filters: SearchFilters(language: "fr"))))401 SPSearchApp.route(SearchLink.newSearchURL) // the widget's field402 #expect(Router.shared.pending == .focus)403 SPSearchApp.route(URL(string: "https://search.spboucher.ai/")!)404 #expect(Router.shared.pending == .home)405406 let tapped = NSUserActivity(activityType: CSSearchableItemActionType)407 tapped.userInfo = [CSSearchableItemActivityIdentifier: Spotlight.identifier(favorite: "https://www.ulaval.ca/")]408 SPSearchApp.route(tapped)409 #expect(Router.shared.pending == .page(URL(string: "https://www.ulaval.ca/")!))410411 let intent = SearchSPSearchIntent()412 intent.query = " histoire du Québec "413 _ = try await intent.perform()414 #expect(Router.shared.pending == .search(SearchLink(query: "histoire du Québec")))415 intent.query = " "416 _ = try await intent.perform()417 #expect(Router.shared.pending == .focus)418 Router.shared.pending = nil419 _ = try await OpenSPSearchIntent().perform()420 #expect(Router.shared.pending == .focus)421 Router.shared.pending = nil422 }423424 /// The private Spotlight index of the app accepts the items and finds them again (simulator).425 @Test func spotlightIndexRoundTrip() async throws {426 guard CSSearchableIndex.isIndexingAvailable() else { return }427 let index = CSSearchableIndex.default()428 let marker = "spsearchtest\(Int.random(in: 100_000...999_999))"429 let f = Favorite(url: "https://example.org/\(marker)", title: "Titre \(marker)", domain: "example.org", snippet: "extrait", savedAt: Date())430 try await index.indexSearchableItems([Spotlight.item(f), Spotlight.item(HistoryEntry(query: "requête \(marker)", date: Date()))])431 defer { Task { try? await index.deleteSearchableItems(withIdentifiers: [Spotlight.identifier(favorite: f.url), Spotlight.identifier(query: "requête \(marker)")]) } }432 var found: [String] = []433 for _ in 0..<20 where found.count < 2 {434 let context = CSSearchQueryContext()435 context.fetchAttributes = ["title"]436 let query = CSSearchQuery(queryString: "title == \"*\(marker)*\"c", queryContext: context)437 found = []438 for try await result in query.results { found.append(result.item.uniqueIdentifier) }439 if found.count < 2 { try await Task.sleep(for: .milliseconds(250)) }440 }441 #expect(Set(found) == [Spotlight.identifier(favorite: f.url), Spotlight.identifier(query: "requête \(marker)")])442 #expect(found.compactMap(Spotlight.target(identifier:)).count == 2)443 }444}445