Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Core/Tests/SPSearchKitTests/V2Tests.swift10// Description : API V2: decoding of fixtures written from the contract,11// code-point highlights, request parameters, V1 fallback,12// caches, favorites, links, history migration.13// Module : SPSearchKitTests14// 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 Testing93@testable import SPSearchKit9495func v2<T: Decodable>(_ type: T.Type, _ name: String) throws -> T { try SPSearchClient.decoder(.v2).decode(T.self, from: fixture(name)) }9697@Suite struct V2DecodingTests {98 @Test func searchPageFromTheContract() throws {99 let r = try v2(SearchResponse.self, "v2-search")100 #expect(r.requestID == "r-9f2c41aa")101 #expect(r.ranker == "searchrank-v2.0")102 #expect(r.results.count == 4)103 #expect(r.total == ResultTotal(value: 5321, relation: .estimate))104 #expect(r.nextCursor == "c2.abc")105 #expect(r.indexVersion == 19559)106 #expect(r.elapsedMS == 41) // timing.total_ms107 #expect(r.related == ["université laval admission", "université laval programmes"])108 #expect(r.facets.kinds == [Facet(value: "university", count: 40)])109 #expect(r.region == AppliedRegion(value: "ca-qc", source: .choice))110 let q = try #require(r.query)111 #expect(q.raw == "univeristé lavla")112 #expect(q.effective == "université laval")113 #expect(q.language == "fr")114 #expect(q.isNavigational)115 #expect(q.correction == QueryInfo.Correction(applied: true, original: "univeristé lavla", suggestion: "université laval"))116 #expect(q.terms == ["universite", "laval"])117 }118119 @Test func resultFields() throws {120 let r = try v2(SearchResponse.self, "v2-search")121 let a = r.results[0]122 #expect(a.displayURL == "ulaval.ca")123 #expect(a.siteName == "Université Laval")124 #expect(a.faviconPath == "/v2/favicon?domain=ulaval.ca")125 #expect(a.serverHighlights)126 #expect(a.highlights.count == 4)127 #expect(a.titleHighlights == [0..<10, 11..<16])128 #expect(a.validation == Validation(state: .ok, validatedAt: Date(timeIntervalSince1970: 1_796_120_000), httpStatus: 200))129 #expect(a.publishedAt == nil)130 #expect(a.checkedAt != nil)131 #expect(a.sitelinks.map(\.title) == ["Admission", "Programmes d’études", "Bibliothèque", "Nous joindre"]) // four at most132 #expect(a.moreFromSite == 12)133 #expect(a.kind == .university)134 #expect(a.tier == .premium)135 let b = r.results[1]136 #expect(b.publishedAt == Date(timeIntervalSince1970: 1_795_000_000))137 #expect(b.validation?.state == .changed)138 #expect(b.sitelinks.isEmpty)139 let c = r.results[2]140 #expect(c.snippet.isEmpty)141 #expect(c.snippetSource == "none")142 #expect(c.validation?.state == .unknown) // unknown enumeration value143 #expect(c.validation?.validatedAt == nil)144 #expect(c.checkedAt == nil)145 }146147 @Test func v2TextIsLeftUntouchedAndBadIntervalsAreDropped() throws {148 let d = try v2(SearchResponse.self, "v2-search").results[3]149 #expect(d.snippet == "Texte brut avec & laissé tel quel.") // plain text: no entity decoding in V2150 #expect(d.highlights == [0..<5, 900..<950]) // reversed and malformed pairs dropped; clamping happens at display151 #expect(d.validation == nil)152 #expect(d.displayURL == nil)153 #expect(d.faviconPath == nil)154 #expect(d.kind == .page)155 }156157 @Test func aBareV2PageDecodes() throws {158 let r = try SPSearchClient.decoder(.v2).decode(SearchResponse.self, from: Data(#"{"results":[{"url":"https://e.org/"}],"query":{"correction":null},"timing":null,"related":null,"facets":null}"#.utf8))159 #expect(r.results.count == 1)160 #expect(r.results[0].title == "e.org")161 #expect(r.query?.correction == nil)162 #expect(r.related.isEmpty)163 #expect(r.elapsedMS == 0)164 #expect(r.results[0].serverHighlights)165 }166167 @Test func correctionForms() throws {168 func correction(_ json: String) throws -> QueryInfo.Correction? {169 try SPSearchClient.decoder(.v2).decode(QueryInfo.self, from: Data(#"{"raw":"lavla","correction":\#(json)}"#.utf8)).correction170 }171 #expect(try correction("null") == nil)172 #expect(try correction(#"{"applied":false,"original":"lavla","suggestion":"laval"}"#) == QueryInfo.Correction(applied: false, original: "lavla", suggestion: "laval"))173 #expect(try correction(#"{"applied":true,"original":"lavla","suggestion":""}"#) == nil)174 #expect(try correction(#"{"applied":false,"original":"laval","suggestion":"laval"}"#) == nil)175 #expect(try correction(#""oui""#) == nil)176 }177178 @Test func autocompleteTypes() throws {179 let s = try v2(AutocompleteResponse.self, "v2-autocomplete").suggestions180 #expect(s.map(\.text) == ["université laval", "ulaval.ca", "université", "nouveau", "chaîne nue"])181 #expect(s.map(\.kind) == [.completion, .site, .correction, .completion, .completion])182 #expect(s[1].title == "Université Laval")183 #expect(s[1].link?.host == "www.ulaval.ca")184 #expect(Set(s.map(\.id)).count == s.count)185 // The V1 list of bare strings reads into the same model.186 let v1 = try JSONDecoder().decode(AutocompleteResponse.self, from: fixture("suggest")).suggestions187 #expect(v1.count == 8)188 #expect(v1.allSatisfy { $0.kind == .completion })189 }190191 @Test func filtersCatalog() throws {192 let f = try v2(FilterCatalog.self, "v2-filters")193 #expect(f.verticals.map(\.id) == ["web", "news"])194 #expect(f.verticals[1].documents == 412_000)195 #expect(f.languages.map(\.value) == ["en", "fr"])196 #expect(f.kinds.count == 12)197 #expect(f.regions == ["ca", "ca-qc", "fr", "be", "ch", "us", "gb"])198 #expect(f.fresh == ["day", "week", "month", "year"])199 let empty = try SPSearchClient.decoder(.v2).decode(FilterCatalog.self, from: Data("{}".utf8))200 #expect(empty.verticals.map(\.id) == ["web"]) // the Web is always there; nothing else is invented201 #expect(empty.kinds.isEmpty && empty.fresh.isEmpty && empty.regions.isEmpty)202 #expect(FilterCatalog.minimal.verticals.map(\.id) == ["web"])203 }204205 @Test func status() throws {206 let s = try v2(EngineStatus.self, "v2-status")207 #expect(s.level == .ok)208 #expect(s.documents == 17_491_959)209 #expect(s.domains == 665_369)210 #expect(s.indexVersion == 19559)211 #expect(s.updatedAt == Date(timeIntervalSince1970: 1_796_125_946))212 #expect(s.medianAgeSeconds == 86_400)213 #expect(s.validated24h == 1_250_000)214 #expect(s.services["index_primary"] == .degraded)215 #expect(s.services["semantic"] == .off)216 #expect(s.services["nouveau"] == .unknown)217 let bare = try SPSearchClient.decoder(.v2).decode(EngineStatus.self, from: Data(#"{"status":"en panne"}"#.utf8))218 #expect(bare.level == .unknown)219 #expect(bare.documents == 0)220 }221}222223@Suite struct CodePointHighlightTests {224 private func marked(_ text: String, _ ranges: [Range<Int>]) -> [String] {225 Highlighter.ranges(in: text, codePoints: ranges).map { String(text[$0]) }226 }227228 @Test func accentsCountAsOneCodePoint() {229 #expect(marked("L’Université Laval à Québec", [2..<12, 13..<18, 21..<27]) == ["Université", "Laval", "Québec"])230 }231232 @Test func offsetsAreCodePointsNotUTF16NorCharacters() throws {233 // 🇨🇦 is two code points and four UTF-16 units; 👩🏽🎓 is four code points and seven UTF-16 units; both are one character.234 let r = try v2(SearchResponse.self, "v2-search").results[0]235 #expect(marked(r.snippet, r.highlights) == ["Université", "Laval", "🇨🇦", "université"])236 let text = "a 👩🏽🎓 étudie"237 #expect(marked(text, [7..<13]) == ["étudie"])238 }239240 @Test func aBoundInsideACharacterMovesOutward() {241 #expect(marked("x 🇨🇦 y", [2..<3]) == ["🇨🇦"]) // half a flag marks the flag242 #expect(marked("x 🇨🇦 y", [3..<6]) == ["🇨🇦 y"])243 let decomposed = "cafe\u{301} noir" // e + combining acute244 #expect(marked(decomposed, [3..<4]) == ["e\u{301}"])245 #expect(marked(decomposed, [0..<4]) == ["cafe\u{301}"])246 }247248 @Test func clampsMergesAndSorts() {249 #expect(marked("abc def", [4..<99]) == ["def"])250 #expect(marked("abc def", [50..<60]).isEmpty)251 #expect(marked("abc def", [4..<6, 0..<2, 1..<3, 5..<7]) == ["abc", "def"])252 #expect(marked("", [0..<3]).isEmpty)253 #expect(marked("abc", []).isEmpty)254 }255256 @Test func attributedKeepsTheTextAndFlagsTheMarks() throws {257 let r = try v2(SearchResponse.self, "v2-search").results[0]258 let a = Highlighter.attributed(r.snippet, codePoints: r.highlights)259 #expect(String(a.characters) == r.snippet)260 let flagged = a.runs.filter { $0.inlinePresentationIntent == .stronglyEmphasized }.map { String(a[$0.range].characters) }261 #expect(flagged == ["Université", "Laval", "🇨🇦", "université"])262 }263}264265@Suite struct V2RequestTests {266 @Test func v2ParametersAndOrder() {267 let r = SearchRequest(query: "lavla", cursor: "c1", filters: SearchFilters(language: "fr", site: "ulaval.ca", kind: "university", fresh: "week"),268 region: .quebec, interfaceLanguage: "fr", vertical: "news", correct: false)269 #expect(Endpoint.search(r).absoluteString ==270 "https://search.spboucher.ai/v2/search?q=lavla&limit=10&cursor=c1&vertical=news&lang=fr&site=ulaval.ca&kind=university&fresh=week&hl=fr®ion=ca-qc&correct=0")271 }272273 @Test func defaultsAreNotSent() {274 let s = Endpoint.search(SearchRequest(query: "x")).absoluteString275 #expect(s == "https://search.spboucher.ai/v2/search?q=x&limit=10")276 }277278 @Test func freshReplacesTheBoundsAndV1LeavesV2ParametersOut() {279 let day = Date(timeIntervalSince1970: 1_796_000_000)280 let r = SearchRequest(query: "x", filters: SearchFilters(kind: "blog", fresh: "month", from: day, to: day), vertical: "news", correct: false)281 let v2 = Endpoint.search(r, version: .v2).absoluteString282 #expect(v2.contains("fresh=month") && !v2.contains("from=") && !v2.contains("to="))283 let v1 = Endpoint.search(r, version: .v1).absoluteString284 #expect(v1.hasPrefix("https://search.spboucher.ai/v1/search?q=x&limit=10&from="))285 #expect(!v1.contains("vertical") && !v1.contains("kind") && !v1.contains("fresh") && !v1.contains("correct"))286 }287288 @Test func otherV2Endpoints() {289 #expect(Endpoint.autocomplete("univ lav", interfaceLanguage: "fr").absoluteString == "https://search.spboucher.ai/v2/autocomplete?q=univ%20lav&hl=fr")290 #expect(Endpoint.filters().absoluteString == "https://search.spboucher.ai/v2/filters")291 #expect(Endpoint.status().absoluteString == "https://search.spboucher.ai/v2/status")292 }293294 @Test func faviconStaysOnOurServer() {295 #expect(Endpoint.favicon(path: "/v2/favicon?domain=ulaval.ca")?.absoluteString == "https://search.spboucher.ai/v2/favicon?domain=ulaval.ca")296 #expect(Endpoint.favicon(path: "https://tiers.example/icone.png") == nil)297 #expect(Endpoint.favicon(path: "//tiers.example/icone.png") == nil)298 #expect(Endpoint.favicon(path: "") == nil)299 }300301 @Test func dayRoundTrip() {302 let d = SearchRequest.date(day: "2026-12-01")303 #expect(d.map { SearchRequest.day($0) } == "2026-12-01")304 #expect(SearchRequest.date(day: "2026-13-01") == nil)305 #expect(SearchRequest.date(day: "hier") == nil)306 }307}308309/// Answers by path, and counts the requests, for one invented host.310final class RouteProtocol: URLProtocol, @unchecked Sendable {311 struct Reply { var status = 200; var headers: [String: String] = ["Content-Type": "application/json"]; var body = Data() }312 private static let lock = NSLock()313 nonisolated(unsafe) private static var routes: [String: Reply] = [:]314 nonisolated(unsafe) private static var log: [String: [String]] = [:]315316 static func set(_ reply: Reply, host: String, path: String) { lock.withLock { routes[host + path] = reply } }317 static func paths(_ host: String) -> [String] { lock.withLock { log[host] ?? [] } }318 nonisolated(unsafe) private static var failures: [String: (URLError.Code, Int)] = [:]319 /// The next `times` requests to this host fail in transport with this code.320 static func failNext(host: String, code: URLError.Code, times: Int) { lock.withLock { failures[host] = (code, times) } }321322 override class func canInit(with request: URLRequest) -> Bool { true }323 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }324 override func stopLoading() {}325 override func startLoading() {326 let host = request.url?.host ?? "", path = request.url?.path ?? ""327 let reply = Self.lock.withLock { () -> Reply? in328 Self.log[host, default: []].append(path)329 if let f = Self.failures[host], f.1 > 0 { Self.failures[host] = (f.0, f.1 - 1); return nil }330 return Self.routes[host + path] ?? Reply(status: 200, headers: ["Content-Type": "text/html"], body: Data("<!doctype html><html>".utf8))331 }332 guard let reply else {333 let code = Self.lock.withLock { Self.failures[host]?.0 ?? .unknown }334 client?.urlProtocol(self, didFailWithError: URLError(code)); return335 }336 let r = HTTPURLResponse(url: request.url!, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers)!337 client?.urlProtocol(self, didReceive: r, cacheStoragePolicy: .notAllowed)338 client?.urlProtocol(self, didLoad: reply.body)339 client?.urlProtocolDidFinishLoading(self)340 }341}342343final class Clock: @unchecked Sendable {344 private let lock = NSLock()345 private var t: Date346 init(_ t: Date = Date(timeIntervalSince1970: 1_800_000_000)) { self.t = t }347 var now: Date { lock.withLock { t } }348 func advance(_ s: TimeInterval) { lock.withLock { t = t.addingTimeInterval(s) } }349}350351func tempDirectory() -> URL {352 FileManager.default.temporaryDirectory.appendingPathComponent("spsearch-tests-\(UUID().uuidString)", isDirectory: true)353}354355@Suite struct FallbackTests {356 private func client(cache: ResponseCache? = nil) -> (SPSearchClient, String) {357 let host = "\(UUID().uuidString.lowercased()).test"358 return (SPSearchClient(baseURL: URL(string: "https://\(host)")!, session: SPSearchClient.makeSession(protocolClasses: [RouteProtocol.self]),359 userAgent: "t", interfaceLanguage: "fr", cache: cache), host)360 }361362 @Test func v2IsUsedWhenTheServerHasIt() async throws {363 let (c, host) = client()364 RouteProtocol.set(.init(body: try fixture("v2-search")), host: host, path: "/v2/search")365 let r = try await c.search(SearchRequest(query: "univeristé lavla"))366 #expect(r.query?.correction?.applied == true)367 #expect(r.results[0].serverHighlights)368 #expect(RouteProtocol.paths(host) == ["/v2/search"])369 #expect(await c.isUsingV2)370 }371372 @Test func aServerThatAnswersItsHTMLShellFallsBackToV1AndStaysThere() async throws {373 // What search.spboucher.ai does today for /v2/*: 200 with the site's HTML page.374 let (c, host) = client()375 RouteProtocol.set(.init(body: try fixture("search")), host: host, path: "/v1/search")376 RouteProtocol.set(.init(body: try fixture("suggest")), host: host, path: "/v1/suggest")377 RouteProtocol.set(.init(body: try fixture("stats")), host: host, path: "/v1/stats")378 let r = try await c.search(SearchRequest(query: "université laval", filters: SearchFilters(kind: "blog"), vertical: "news"))379 #expect(r.results.count == 5)380 #expect(r.query == nil)381 #expect(!r.results[0].serverHighlights) // V1: the app marks the terms itself382 #expect(RouteProtocol.paths(host) == ["/v2/search", "/v1/search"])383 #expect(!(await c.isUsingV2))384 let s = try await c.autocomplete("univ")385 #expect(s.count == 8 && s.allSatisfy { $0.kind == .completion })386 #expect(try await c.filters() == .minimal)387 let status = try await c.status()388 #expect(status.level == .unknown)389 #expect(status.documents > 9_000_000)390 // No V2 route is asked again while the fallback holds.391 #expect(RouteProtocol.paths(host) == ["/v2/search", "/v1/search", "/v1/suggest", "/v1/stats"])392 }393394 @Test func a404AlsoFallsBack() async throws {395 let (c, host) = client()396 RouteProtocol.set(.init(status: 404, body: Data(#"{"error":{"code":"not_found","message":"route inconnue"}}"#.utf8)), host: host, path: "/v2/autocomplete")397 RouteProtocol.set(.init(body: Data(#"{"suggestions":["a"]}"#.utf8)), host: host, path: "/v1/suggest")398 #expect(try await c.autocomplete("ab") == [Suggestion(text: "a")])399 #expect(RouteProtocol.paths(host) == ["/v2/autocomplete", "/v1/suggest"])400 }401402 @Test func errorsOfAV2ServerAreNotMistakenForAMissingRoute() async throws {403 let (c, host) = client()404 RouteProtocol.set(.init(status: 429, headers: ["Retry-After": "3"], body: Data()), host: host, path: "/v2/search")405 await #expect(throws: SearchError.rateLimited(retryAfter: 3)) { try await c.search(SearchRequest(query: "x")) }406 RouteProtocol.set(.init(status: 400, body: Data(#"{"error":{"code":"bad_request","message":"q trop long"}}"#.utf8)), host: host, path: "/v2/search")407 await #expect(throws: SearchError.badRequest(message: "q trop long")) { try await c.search(SearchRequest(query: "x")) }408 #expect(RouteProtocol.paths(host) == ["/v2/search", "/v2/search"])409 #expect(await c.isUsingV2)410 }411412 @Test func v2IsTriedAgainAfterTheDelay() async {413 let gate = APIGate()414 let t0 = Date(timeIntervalSince1970: 1_800_000_000)415 #expect(await gate.useV2(now: t0))416 await gate.markMissing(now: t0)417 #expect(!(await gate.useV2(now: t0.addingTimeInterval(APIGate.retryAfter - 1))))418 #expect(await gate.useV2(now: t0.addingTimeInterval(APIGate.retryAfter)))419 }420421 @Test func aSearchIsServedFromTheCacheAndReloadedOnDemand() async throws {422 let cache = ResponseCache()423 let (c, host) = client(cache: cache)424 RouteProtocol.set(.init(body: try fixture("v2-search")), host: host, path: "/v2/search")425 let r = SearchRequest(query: "université laval")426 _ = try await c.search(r)427 _ = try await c.search(r) // from the cache428 _ = try await c.search(r.page(after: "c2.abc")) // another page: another address429 #expect(RouteProtocol.paths(host).count == 2)430 _ = try await c.search(r, policy: .reload) // pull to refresh431 #expect(RouteProtocol.paths(host).count == 3)432 }433434 @Test func errorsAndPassingConditionsAreNeverCached() async throws {435 let cache = ResponseCache()436 let (c, host) = client(cache: cache)437 RouteProtocol.set(.init(body: Data(#"{"results":[{"url":"https://e.org/"}],"partial":true,"notices":["partial_shards"],"index_version":5}"#.utf8)), host: host, path: "/v2/search")438 _ = try await c.search(SearchRequest(query: "x"))439 _ = try await c.search(SearchRequest(query: "x"))440 #expect(RouteProtocol.paths(host).count == 2)441 #expect(await cache.memoryCount == 0)442 }443}444445@Suite struct ResponseCacheTests {446 @Test func servesWhileYoungEnough() async {447 let clock = Clock()448 let cache = ResponseCache(now: { clock.now })449 await cache.store(Data("a".utf8), for: "k")450 #expect(await cache.data(for: "k", maxAge: 300) == Data("a".utf8))451 clock.advance(299)452 #expect(await cache.data(for: "k", maxAge: 300) != nil)453 clock.advance(2)454 #expect(await cache.data(for: "k", maxAge: 300) == nil)455 #expect(await cache.memoryCount == 0) // an expired entry is dropped456 #expect(await cache.data(for: "inconnu", maxAge: 300) == nil)457 }458459 @Test func aNewerIndexVersionDropsOlderAnswers() async {460 let cache = ResponseCache()461 await cache.store(Data("old".utf8), for: "search", indexVersion: 100)462 await cache.store(Data("filters".utf8), for: "filters") // does not depend on the index version463 await cache.noteIndexVersion(100)464 #expect(await cache.data(for: "search", maxAge: 300) != nil)465 await cache.noteIndexVersion(101)466 #expect(await cache.data(for: "search", maxAge: 300) == nil)467 #expect(await cache.data(for: "filters", maxAge: 300) != nil)468 await cache.noteIndexVersion(50) // an older announcement changes nothing469 await cache.store(Data("new".utf8), for: "search", indexVersion: 101)470 #expect(await cache.data(for: "search", maxAge: 300) == Data("new".utf8))471 }472473 @Test func memoryIsBounded() async {474 let cache = ResponseCache(memoryLimit: 3)475 for i in 0..<5 { await cache.store(Data("\(i)".utf8), for: "k\(i)") }476 #expect(await cache.memoryCount == 3)477 #expect(await cache.data(for: "k0", maxAge: 60) == nil)478 #expect(await cache.data(for: "k4", maxAge: 60) != nil)479 }480481 @Test func diskCopySurvivesAProcessAndHonoursTheIndexVersion() async throws {482 let dir = tempDirectory()483 defer { try? FileManager.default.removeItem(at: dir) }484 let first = ResponseCache(directory: dir)485 await first.store(Data("page".utf8), for: "https://h/v2/search?q=secret", indexVersion: 7)486 let names = try FileManager.default.contentsOfDirectory(atPath: dir.path)487 #expect(names.count == 1)488 #expect(!names[0].contains("secret")) // the file name is a digest489 let second = ResponseCache(directory: dir) // a new process490 #expect(await second.data(for: "https://h/v2/search?q=secret", maxAge: 300) == Data("page".utf8))491 let third = ResponseCache(directory: dir)492 await third.noteIndexVersion(8)493 #expect(await third.data(for: "https://h/v2/search?q=secret", maxAge: 300) == nil)494 #expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).isEmpty)495 }496497 @Test func diskIsBoundedAndCanBeSwitchedOff() async throws {498 let dir = tempDirectory()499 defer { try? FileManager.default.removeItem(at: dir) }500 let cache = ResponseCache(directory: dir, diskLimit: 6_000)501 for i in 0..<10 { await cache.store(Data(repeating: 65, count: 1_000), for: "k\(i)") }502 #expect(await cache.diskBytes() <= 6_000)503 #expect(await cache.diskBytes() > 0)504 await cache.store(Data("m".utf8), for: "memoire", onDisk: false)505 await cache.setPersistent(false) // history switched off: nothing stays on disk506 #expect(!FileManager.default.fileExists(atPath: dir.path))507 await cache.store(Data("x".utf8), for: "apres")508 #expect(!FileManager.default.fileExists(atPath: dir.path))509 #expect(await cache.data(for: "apres", maxAge: 60) != nil) // still served from memory510 await cache.removeAll()511 #expect(await cache.memoryCount == 0)512 }513}514515@Suite struct FaviconStoreTests {516 actor Counter { var n = 0; func hit() { n += 1 } }517 static let png = Data([0x89, 0x50, 0x4E, 0x47, 1, 2, 3])518519 @Test func oneRequestPerIconThenMemoryThenDisk() async {520 let dir = tempDirectory()521 defer { try? FileManager.default.removeItem(at: dir) }522 let counter = Counter()523 let loader: FaviconStore.Loader = { _ in await counter.hit(); return (Self.png, 200, "image/png") }524 let store = FaviconStore(directory: dir, loader: loader)525 async let a = store.data(path: "/v2/favicon?domain=ulaval.ca")526 async let b = store.data(path: "/v2/favicon?domain=ulaval.ca")527 #expect(await a == Self.png)528 #expect(await b == Self.png)529 #expect(await store.data(path: "/v2/favicon?domain=ulaval.ca") == Self.png)530 #expect(await counter.n == 1)531 let again = FaviconStore(directory: dir, loader: loader) // a new process reads the disk copy532 #expect(await again.data(path: "/v2/favicon?domain=ulaval.ca") == Self.png)533 #expect(await counter.n == 1)534 }535536 @Test func aMissIsRememberedForADayAndAHitForAWeek() async {537 let dir = tempDirectory()538 defer { try? FileManager.default.removeItem(at: dir) }539 let counter = Counter()540 let clock = Clock(Date())541 let store = FaviconStore(directory: dir, now: { clock.now }) { _ in await counter.hit(); return (Data(), 404, nil) }542 #expect(await store.data(path: "/v2/favicon?domain=sans.icone") == nil)543 #expect(await store.data(path: "/v2/favicon?domain=sans.icone") == nil)544 #expect(await counter.n == 1)545 clock.advance(FaviconStore.missAge + 60)546 let later = FaviconStore(directory: dir, now: { clock.now }) { _ in await counter.hit(); return (Self.png, 200, "image/png") }547 #expect(await later.data(path: "/v2/favicon?domain=sans.icone") == Self.png)548 #expect(await counter.n == 2)549 }550551 @Test func onlyRasterImagesFromOurServer() async {552 #expect(FaviconStore.accept(Self.png, status: 200, contentType: "image/png; charset=binary") == Self.png)553 #expect(FaviconStore.accept(Self.png, status: 200, contentType: "image/x-icon") != nil)554 #expect(FaviconStore.accept(Self.png, status: 200, contentType: "image/svg+xml") == nil)555 #expect(FaviconStore.accept(Self.png, status: 200, contentType: "text/html") == nil) // the HTML shell of a V1 server556 #expect(FaviconStore.accept(Self.png, status: 404, contentType: "image/png") == nil)557 #expect(FaviconStore.accept(Data(repeating: 0, count: FaviconStore.maxBytes + 1), status: 200, contentType: "image/png") == nil)558 let counter = Counter()559 let store = FaviconStore(directory: nil) { _ in await counter.hit(); return (Self.png, 200, "image/png") }560 #expect(await store.data(path: "https://tiers.example/favicon.ico") == nil)561 #expect(await store.data(path: nil) == nil)562 #expect(await counter.n == 0) // a third-party address is never requested563 }564565 @Test func aTransportFailureIsNotRemembered() async {566 let counter = Counter()567 let store = FaviconStore(directory: nil) { _ in await counter.hit(); return nil }568 #expect(await store.data(path: "/v2/favicon?domain=x.org") == nil)569 #expect(await store.data(path: "/v2/favicon?domain=x.org") == nil)570 #expect(await counter.n == 2)571 }572}573574@Suite struct FavoritesTests {575 private func store() -> FavoritesStore { FavoritesStore(file: tempDirectory().appendingPathComponent("favorites.json")) }576577 @Test func addRemoveAndOrder() throws {578 let s = store()579 defer { try? FileManager.default.removeItem(at: s.file.deletingLastPathComponent()) }580 #expect(s.all.isEmpty)581 let r = try v2(SearchResponse.self, "v2-search").results582 s.add(Favorite(r[0], at: Date(timeIntervalSince1970: 10)))583 s.add(Favorite(r[1], at: Date(timeIntervalSince1970: 20)))584 s.add(Favorite(r[0], at: Date(timeIntervalSince1970: 30))) // saved again: moves to the top, not listed twice585 #expect(s.all.map(\.url) == ["https://www.ulaval.ca/", "https://www.ulaval.ca/admission"])586 #expect(s.all[0].savedAt == Date(timeIntervalSince1970: 30))587 #expect(s.all[0].siteName == "Université Laval")588 #expect(s.all[0].faviconPath == "/v2/favicon?domain=ulaval.ca")589 #expect(s.contains("https://www.ulaval.ca/admission"))590 #expect(s.remove("https://www.ulaval.ca/").map(\.url) == ["https://www.ulaval.ca/admission"])591 #expect(FavoritesStore(file: s.file).all.count == 1) // read back from the file592 #expect(s.clear().isEmpty)593 #expect(s.all.isEmpty)594 }595596 @Test func unreadableFileIsAnEmptyList() throws {597 let s = store()598 defer { try? FileManager.default.removeItem(at: s.file.deletingLastPathComponent()) }599 try FileManager.default.createDirectory(at: s.file.deletingLastPathComponent(), withIntermediateDirectories: true)600 try Data("pas du json".utf8).write(to: s.file)601 #expect(s.all.isEmpty)602 s.add(Favorite(url: "https://e.org/", title: "t", domain: "e.org", savedAt: Date()))603 #expect(s.all.count == 1)604 }605}606607@Suite struct HistoryMigrationTests {608 private func defaults() -> UserDefaults {609 let name = "spsearch.tests.\(UUID().uuidString)"610 let d = UserDefaults(suiteName: name)!611 d.removePersistentDomain(forName: name)612 return d613 }614615 /// Exactly what 1.0.0 wrote: `history.items` = JSON array of {query, date (seconds since 2001)}, `history.enabled` = Bool.616 private func write10(_ d: UserDefaults, _ entries: [(String, Double)], enabled: Bool? = nil) {617 let json = "[" + entries.map { #"{"query":"\#($0.0)","date":\#($0.1)}"# }.joined(separator: ",") + "]"618 d.set(Data(json.utf8), forKey: "history.items")619 if let enabled { d.set(enabled, forKey: "history.enabled") }620 }621622 @Test func dataWrittenBy10IsReadAsIs() {623 let d = defaults()624 write10(d, [("université laval", 786_300_000), ("\\\"vision collective\\\" laval", 786_200_000)])625 let h = HistoryStore(defaults: d)626 #expect(h.entries.map(\.query) == ["université laval", "\"vision collective\" laval"])627 #expect(h.entries[0].date == Date(timeIntervalSinceReferenceDate: 786_300_000))628 #expect(h.isEnabled)629 }630631 @Test func movesEntriesAndSwitchToTheSharedStoreOnce() {632 let old = defaults(), new = defaults()633 write10(old, [("b", 200), ("a", 100)], enabled: false)634 #expect(HistoryStore.migrate(from: old, to: new))635 let h = HistoryStore(defaults: new)636 #expect(h.entries.map(\.query) == ["b", "a"])637 #expect(!h.isEnabled) // the reader's choice follows638 #expect(old.data(forKey: "history.items") == nil)639 #expect(old.object(forKey: "history.enabled") == nil)640 #expect(!HistoryStore.migrate(from: old, to: new)) // nothing left to move641 #expect(h.entries.count == 2)642 }643644 @Test func mergesWithWhatTheDestinationAlreadyHolds() {645 let old = defaults(), new = defaults()646 write10(old, [("commun", 300), ("ancien", 100)])647 HistoryStore(defaults: new).record("Commun", at: Date(timeIntervalSinceReferenceDate: 400))648 HistoryStore(defaults: new).record("neuf", at: Date(timeIntervalSinceReferenceDate: 200))649 HistoryStore.migrate(from: old, to: new)650 #expect(HistoryStore(defaults: new).entries.map(\.query) == ["Commun", "neuf", "ancien"])651 #expect(HistoryStore(defaults: new).isEnabled)652 }653654 @Test func nothingToMove() {655 let old = defaults(), new = defaults()656 #expect(!HistoryStore.migrate(from: old, to: new))657 #expect(!HistoryStore.migrate(from: old, to: old))658 #expect(HistoryStore(defaults: new).entries.isEmpty)659 }660}661662@Suite struct SearchLinkTests {663 private func parse(_ s: String) -> SearchLink.Target? { SearchLink.parse(URL(string: s)!) }664665 @Test func theWebResultsPage() {666 #expect(parse("https://search.spboucher.ai/search?q=universit%C3%A9+laval") == .search(SearchLink(query: "université laval")))667 #expect(parse("https://search.spboucher.ai/search/?q=%22vision%20collective%22%20laval&lang=FR&site=ULaval.ca&from=2026-01-05&to=2026-12-01&cursor=abc") ==668 .search(SearchLink(query: "\"vision collective\" laval", filters: SearchFilters(language: "fr", site: "ulaval.ca",669 from: SearchRequest.date(day: "2026-01-05"), to: SearchRequest.date(day: "2026-12-01")))))670 }671672 @Test func v2ParametersWhenPresent() {673 #expect(parse("https://search.spboucher.ai/search?q=budget&vertical=news&kind=news&fresh=week&from=2026-01-01") ==674 .search(SearchLink(query: "budget", filters: SearchFilters(kind: "news", fresh: "week"), vertical: "news")))675 }676677 @Test func homeAndEmptyQueries() {678 #expect(parse("https://search.spboucher.ai/") == .home)679 #expect(parse("https://search.spboucher.ai") == .home)680 #expect(parse("https://search.spboucher.ai/search") == .home)681 #expect(parse("https://search.spboucher.ai/search?q=%20%20") == .home)682 #expect(parse("https://search.spboucher.ai/?q=laval") == .search(SearchLink(query: "laval")))683 }684685 @Test func whatIsNotOurs() {686 #expect(parse("https://search.spboucher.ai/about") == nil)687 #expect(parse("https://search.spboucher.ai/v2/search?q=x") == nil)688 #expect(parse("https://bot.spboucher.ai/search?q=x") == nil)689 #expect(parse("https://example.org/search?q=x") == nil)690 #expect(parse("ftp://search.spboucher.ai/search?q=x") == nil)691 }692693 @Test func longAndInvalidValuesAreBounded() {694 let long = String(repeating: "a", count: 600)695 guard case .search(let link)? = parse("https://search.spboucher.ai/search?q=\(long)&from=hier&to=2026-99-99") else { Issue.record("not a search"); return }696 #expect(link.query.count == SearchRequest.maxQueryLength)697 #expect(link.filters.from == nil && link.filters.to == nil)698 }699700 @Test func appScheme() {701 #expect(parse("spsearch://search?q=laval") == .search(SearchLink(query: "laval")))702 #expect(parse("spsearch:///search?q=laval") == .search(SearchLink(query: "laval")))703 #expect(parse("spsearch://") == .home)704 #expect(SearchLink.parse(SearchLink.newSearchURL) == .newSearch)705 #expect(parse("https://search.spboucher.ai/new") == nil)706 #expect(parse("spsearch://settings") == nil)707 }708709 @Test func aSearchWritesTheAddressItIsReadFrom() {710 let link = SearchLink(query: "c++ \"a&b\"", filters: SearchFilters(language: "fr", site: "ulaval.ca", kind: "blog", fresh: "month"), vertical: "news")711 #expect(link.webURL.absoluteString == "https://search.spboucher.ai/search?q=c%2B%2B%20%22a%26b%22&vertical=news&lang=fr&site=ulaval.ca&kind=blog&fresh=month")712 #expect(SearchLink.parse(link.webURL) == .search(link))713 let dated = SearchLink(query: "x", filters: SearchFilters(from: SearchRequest.date(day: "2026-01-05"), to: SearchRequest.date(day: "2026-02-01")))714 #expect(SearchLink.parse(dated.webURL) == .search(dated))715 }716}717718@Suite struct PagingV2Tests {719 @Test func cursorPaginationOverV2Pages() throws {720 let first = try v2(SearchResponse.self, "v2-search")721 var pages = ResultPages(first: first)722 #expect(pages.results.count == 4)723 #expect(pages.nextCursor == "c2.abc")724 #expect(pages.head?.query?.correction?.suggestion == "université laval")725 func page(_ ids: [String], next: String?, notices: [String] = []) throws -> SearchResponse {726 let results = ids.map { #"{"id":"\#($0)","url":"https://e.org/\#($0)","title":"t"}"# }.joined(separator: ",")727 let cursor = next.map { "\"\($0)\"" } ?? "null"728 let n = notices.map { "\"\($0)\"" }.joined(separator: ",")729 return try SPSearchClient.decoder(.v2).decode(SearchResponse.self, from: Data(#"{"results":[\#(results)],"next_cursor":\#(cursor),"notices":[\#(n)]}"#.utf8))730 }731 #expect(pages.append(try page(["aa11", "p2a", "p2b"], next: "c3")) == 2) // a result already listed is not repeated732 #expect(pages.results.count == 6)733 #expect(pages.nextCursor == "c3")734 #expect(pages.head?.query?.raw == "univeristé lavla") // the head stays the first page735 #expect(pages.append(try page(["p3a"], next: nil)) == 1)736 #expect(!pages.canLoadMore)737 var expiring = ResultPages(first: first)738 expiring.append(try page(["n1", "n2"], next: "c9", notices: ["cursor_expired"]))739 #expect(expiring.results.map(\.id) == ["n1", "n2"]) // the list restarts from the page the server sent740 #expect(expiring.nextCursor == "c9")741 var deep = ResultPages(first: first)742 deep.append(try page(["z"], next: "c4", notices: ["depth_limit"]))743 #expect(!deep.canLoadMore)744 }745}746