SPB Git

Repository Public

RealServerTests.swift 13.9 KB 267 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Core/Tests/SPSearchKitTests/RealServerTests.swift10// Description      : Answers captured from the real API V2 server on 2026-12-0111//                    (trimmed to a few results): decoding, marks, paging, and12//                    what differs from the written contract.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 SPSearchKit9495/// The `real-*.json` fixtures are bodies of `/v2/*` as the search server sent them, cut to a few results.96@Suite struct RealServerTests {97    @Test func navigationalSearch() throws {98        let r = try v2(SearchResponse.self, "real-laval")99        #expect(r.results.count == 3)100        #expect(r.ranker == "searchrank-v2.0")101        #expect(r.total == ResultTotal(value: 17_943, relation: .estimate))102        #expect(r.query?.isNavigational == true)103        #expect(r.query?.correction == nil)104        #expect(r.query?.language == "fr")105        #expect(r.nextCursor?.hasPrefix("eyJ") == true)106        #expect(r.related.count == 5)107        #expect(r.elapsedMS == 75)108        #expect(r.coverage.shardsOK == 8 && r.coverage.shardsTotal == 8)109        #expect(r.notices.isEmpty && !r.partial)110        #expect(r.facets.candidates == 280)111        // Server: {"source":"none","value":null} when no region applies.112        #expect(r.region == AppliedRegion(value: nil, source: AppliedRegion.Source.none))113        let a = r.results[0]114        #expect(a.url == "https://www.ulaval.ca/")115        #expect(a.displayURL == "ulaval.ca")116        #expect(a.siteName == "Accueil")117        #expect(a.kind == .university)118        #expect(a.tier == .standard)119        #expect(a.sitelinks.count == 4)120        #expect(a.moreFromSite == 13)121        #expect(a.publishedAt == nil)122        // The server sends http_status null and two fields the contract does not list (changed_at, first_seen).123        #expect(a.validation == Validation(state: .ok, validatedAt: Date(timeIntervalSince1970: 1_796_110_786), httpStatus: nil))124        #expect(a.faviconPath == "/v2/favicon?domain=ulaval.ca")125        #expect(r.results[2].siteName == nil)                            // site_name is null on most results126    }127128    /// Offsets are code points of the text as sent: every mark of every captured answer falls on whole words.129    @Test func marksCutTheTextWhereTheServerMeans() throws {130        for name in ["real-laval", "real-laval-page2", "real-maison", "real-pandas", "real-typo", "real-typo-verbatim", "real-kind-news", "real-vertical-news"] {131            let r = try v2(SearchResponse.self, name)132            #expect(!r.results.isEmpty)133            for result in r.results {134                for (text, marks) in [(result.snippet, result.highlights), (result.title, result.titleHighlights)] {135                    let scalars = Array(text.unicodeScalars)136                    for m in marks {137                        #expect(m.upperBound <= scalars.count, "\(name): mark outside the text")138                        guard m.upperBound <= scalars.count else { continue }139                        let word = String(String.UnicodeScalarView(scalars[m]))140                        #expect(word.unicodeScalars.allSatisfy { CharacterSet.alphanumerics.contains($0) }, "\(name): \(word)")141                        if m.lowerBound > 0 { #expect(!CharacterSet.letters.contains(scalars[m.lowerBound - 1])) }142                    }143                    #expect(Highlighter.ranges(in: text, codePoints: marks).count <= marks.count)144                }145            }146        }147        let a = try v2(SearchResponse.self, "real-laval").results[0]148        let marked = Highlighter.ranges(in: a.title, codePoints: a.titleHighlights).map { String(a.title[$0]) }149        #expect(marked == ["Université", "Laval"])150    }151152    @Test func correctionAppliedThenRefused() throws {153        let applied = try v2(SearchResponse.self, "real-typo")154        #expect(applied.query?.raw == "univeristé lavla")155        #expect(applied.query?.effective == "université laval")156        #expect(applied.query?.correction == QueryInfo.Correction(applied: true, original: "univeristé lavla", suggestion: "université laval"))157        // correct=0: the search ran as typed, the suggestion stays as a proposal, and the server relaxed the query.158        let verbatim = try v2(SearchResponse.self, "real-typo-verbatim")159        #expect(verbatim.query?.effective == "univeristé lavla")160        #expect(verbatim.query?.correction == QueryInfo.Correction(applied: false, original: "univeristé lavla", suggestion: "université laval"))161        #expect(verbatim.notices == [.relaxedToAnyTerm])162        #expect(verbatim.total == ResultTotal(value: 76, relation: .exact))163    }164165    @Test func noResult() throws {166        let r = try v2(SearchResponse.self, "real-empty")167        #expect(r.results.isEmpty)168        #expect(r.total == ResultTotal(value: 0, relation: .exact))169        #expect(r.nextCursor == nil)170        #expect(r.related.isEmpty)171        #expect(r.query?.language == nil)                                // "und"172        #expect(r.query?.correction == nil)173        #expect(r.facets.domains.isEmpty && r.facets.candidates == 0)174    }175176    @Test func kindFilterAndNewsCategory() throws {177        let kind = try v2(SearchResponse.self, "real-kind-news")178        #expect(kind.results.allSatisfy { $0.kind == .news })179        let news = try v2(SearchResponse.self, "real-vertical-news")180        #expect(news.results.count == 2)181        #expect(news.results[0].publishedAt == Date(timeIntervalSince1970: 1_790_863_867))182        #expect(news.query?.intent == "documentary")183    }184185    @Test func secondPageByCursor() throws {186        let first = try v2(SearchResponse.self, "real-laval")187        let second = try v2(SearchResponse.self, "real-laval-page2")188        var pages = ResultPages(first: first)189        #expect(pages.nextCursor == first.nextCursor)190        #expect(pages.append(second) == 2)191        #expect(pages.results.count == 5)192        #expect(Set(pages.results.map(\.id)).count == 5)193        #expect(pages.results.map(\.id) == first.results.map(\.id) + second.results.map(\.id))   // server order, untouched194        #expect(pages.nextCursor == second.nextCursor)195    }196197    /// Text is plain and untrusted: what looks like markup is kept and shown as text (the marks count on it).198    @Test func markupLeftoversInATitleStayText() throws {199        let r = try v2(SearchResponse.self, "real-maison").results[0]200        #expect(r.title.contains("<!-- -->"))201        #expect(Highlighter.ranges(in: r.title, codePoints: r.titleHighlights).map { String(r.title[$0]).lowercased() } == ["coût", "maison", "prix"])202        #expect(r.kind == .blog)203        #expect(r.publishedAt != nil)204    }205206    @Test func statusWithoutTheOptionalFigures() throws {207        let s = try v2(EngineStatus.self, "real-status")208        #expect(s.level == .ok)209        #expect(s.documents == 19_934_633)210        #expect(s.domains == 711_349)211        #expect(s.indexVersion == 19_732)212        #expect(s.medianAgeSeconds == 20_374)213        #expect(s.validated24h == nil)                                   // not sent by the server214        #expect(s.services == ["index_primary": .ok, "index_replica": .ok, "search": .ok, "semantic": .off])   // no "crawler"215        #expect(s.updatedAt == Date(timeIntervalSince1970: 1_796_131_532))216    }217218    @Test func filtersAndAutocomplete() throws {219        let f = try v2(FilterCatalog.self, "real-filters")220        #expect(f.verticals.map(\.id) == ["web", "news"])221        #expect(f.languages.count == 20 && f.languages[0].value == "en")222        #expect(f.kinds.count == 12)223        #expect(f.regions.contains("lu") && f.regions.contains("au"))    // more regions than the contract's example224        #expect(f.fresh == ["day", "week", "month", "year"])225        let s = try v2(AutocompleteResponse.self, "real-autocomplete").suggestions226        #expect(s.count == 8)227        #expect(s[0] == Suggestion(text: "univie.ac.at", kind: .site, url: "https://univie.ac.at/", title: nil))   // a site comes without a title228        #expect(s[2] == Suggestion(text: "university", kind: .completion))229    }230231    @Test func errorBody() throws {232        let http = HTTPURLResponse(url: URL(string: "https://e.test/v2/search")!, statusCode: 400, httpVersion: nil, headerFields: nil)!233        #expect(SPSearchClient.error(status: 400, headers: http, body: try fixture("real-error")) == .badRequest(message: "requête vide"))234    }235236    /// `/v2/status` announces index version 19732 while searches carry 68: the status must not date cached searches,237    /// or no search would ever be served from the cache again.238    @Test func theStatusDoesNotEmptyTheSearchCache() async throws {239        let host = "\(UUID().uuidString.lowercased()).test"240        let cache = ResponseCache()241        let c = SPSearchClient(baseURL: URL(string: "https://\(host)")!, session: SPSearchClient.makeSession(protocolClasses: [RouteProtocol.self]),242                               userAgent: "t", interfaceLanguage: "fr", cache: cache)243        RouteProtocol.set(.init(body: try fixture("real-status")), host: host, path: "/v2/status")244        RouteProtocol.set(.init(body: try fixture("real-laval")), host: host, path: "/v2/search")245        #expect(try await c.status().indexVersion == 19_732)246        let r = SearchRequest(query: "université laval")247        #expect(try await c.search(r).indexVersion == 68)248        _ = try await c.search(r)                                        // from the cache249        _ = try await c.status()                                         // cached too (60 s)250        _ = try await c.search(r)251        #expect(RouteProtocol.paths(host) == ["/v2/status", "/v2/search"])252    }253254    /// Seen through the tunnel on 2026-12-01: an idle connection closed under the app answered "connection lost".255    @Test func aLostConnectionIsAskedOnceMore() async throws {256        let host = "\(UUID().uuidString.lowercased()).test"257        let c = SPSearchClient(baseURL: URL(string: "https://\(host)")!, session: SPSearchClient.makeSession(protocolClasses: [RouteProtocol.self]),258                               userAgent: "t", interfaceLanguage: "fr")259        RouteProtocol.set(.init(body: try fixture("real-laval")), host: host, path: "/v2/search")260        RouteProtocol.failNext(host: host, code: .networkConnectionLost, times: 1)261        #expect(try await c.search(SearchRequest(query: "université laval")).results.count == 3)262        #expect(RouteProtocol.paths(host) == ["/v2/search", "/v2/search"])263        RouteProtocol.failNext(host: host, code: .networkConnectionLost, times: 2)264        await #expect(throws: SearchError.offline) { _ = try await c.search(SearchRequest(query: "autre")) }265    }266}267
Files main
Menu

Theme