Repository Public
1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/WorkSearchTests.swift3// Description: The unified search view model: local results as you type, the debounced free server search merged in,4// the semantic search only on an explicit submit, filters, a failing or unreachable server that never5// fails the search, and the highlighted snippet.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SPNotesAPI11import SPNotesStore12import SPNotesSync13import SPNotesTestSupport14import Testing15@testable import SPNotesFeatures16@testable import SPNotesFeaturesCatalog1718/// A debounce the test opens by hand.19final class ManualSleep: @unchecked Sendable {20 private let lock = NSLock()21 private var continuations: [CheckedContinuation<Void, Error>] = []22 private(set) var requested: [Duration] = []2324 func sleep(_ duration: Duration) async throws {25 try await withCheckedThrowingContinuation { continuation in26 lock.withLock { requested.append(duration); continuations.append(continuation) }27 }28 }2930 var waiting: Int { lock.withLock { continuations.count } }3132 func fire() {33 let pending = lock.withLock { let all = continuations; continuations = []; return all }34 pending.forEach { $0.resume() }35 }3637 func cancelAll() {38 let pending = lock.withLock { let all = continuations; continuations = []; return all }39 pending.forEach { $0.resume(throwing: CancellationError()) }40 }41}4243@Suite("Work · unified search")44@MainActor45struct WorkSearchTests {46 private func searches(_ world: FeatureWorld) -> [LoggedRequest] { world.fake.requests.filter { $0.path == "/api/search" } }4748 @Test("as you type: local results at once, the server only after the debounce, lexical (free)")49 func debounce() async throws {50 let world = try await FeatureWorld()51 let sleeper = ManualSleep()52 let model = UnifiedSearchModel(repositories: world.repositories, debounce: .milliseconds(350), sleep: { try await sleeper.sleep($0) }, now: { FeatureSamples.now })53 await model.load()54 world.fake.clearLog()55 model.query = "taux"56 model.queryChanged()57 for _ in 0..<100 where sleeper.waiting == 0 { try await Task.sleep(for: .milliseconds(10)) }58 #expect(sleeper.requested == [.milliseconds(350)])59 #expect(model.answeredQuery == "taux")60 #expect(!model.results.isEmpty)61 #expect(model.results.allSatisfy { $0.origin == .local })62 #expect(!model.usedServer)63 #expect(searches(world).isEmpty) // nothing sent before the debounce64 sleeper.fire()65 await model.settle()66 #expect(model.usedServer)67 #expect(searches(world).count == 1)68 #expect(searches(world).first?.query.contains("semantic=0") == true)69 #expect(model.results.contains { $0.origin == .both })70 #expect(model.results.contains { $0.origin == .server && $0.title.contains("Offre de la banque") })71 #expect(model.statusText?.contains("appareil et serveur") == true)72 }7374 @Test("typing again cancels the pending server search")75 func cancellation() async throws {76 let world = try await FeatureWorld()77 let sleeper = ManualSleep()78 let model = UnifiedSearchModel(repositories: world.repositories, sleep: { try await sleeper.sleep($0) })79 world.fake.clearLog()80 model.query = "tau"81 model.queryChanged()82 for _ in 0..<100 where sleeper.waiting == 0 { try await Task.sleep(for: .milliseconds(10)) }83 model.query = "volatilité"84 model.queryChanged()85 for _ in 0..<100 where sleeper.waiting < 2 { try await Task.sleep(for: .milliseconds(10)) }86 sleeper.fire()87 await model.settle()88 #expect(model.answeredQuery == "volatilité")89 #expect(searches(world).count == 1)90 #expect(searches(world).first?.query.contains("volatilit") == true)91 model.query = ""92 model.queryChanged()93 #expect(model.results.isEmpty)94 #expect(model.statusText == nil)95 }9697 @Test("semantic search is never run while typing; only an explicit submit sends the paid hybrid query")98 func semanticIsExplicit() async throws {99 let world = try await FeatureWorld()100 let model = UnifiedSearchModel(repositories: world.repositories, debounce: .zero, sleep: { _ in })101 world.fake.clearLog()102 model.semantic = true103 model.query = "garantie"104 model.queryChanged()105 await model.settle()106 #expect(searches(world).count == 1)107 #expect(searches(world).allSatisfy { $0.query.contains("semantic=0") })108 #expect(!model.answeredSemantic)109 await model.submit()110 #expect(searches(world).count == 2)111 #expect(searches(world).last?.query.contains("semantic=0") == false)112 #expect(model.answeredSemantic)113 #expect(model.statusText?.contains("par le sens") == true)114 }115116 @Test("heading and block of a server passage go to the router")117 func openPassage() async throws {118 let world = try await FeatureWorld()119 let router = FeatureRouterRecorder()120 let model = UnifiedSearchModel(repositories: world.repositories, router: router, debounce: .zero, sleep: { _ in })121 model.query = "volatilité"122 await model.submit()123 let hit = try #require(model.results.first { $0.pageId == FeatureSamples.workNotePageId })124 #expect(hit.heading == "Modèles GARCH")125 model.open(hit)126 #expect(router.calls == [.page(id: FeatureSamples.workNotePageId, blockId: "p-garch")])127 }128129 @Test("offline or failing server: the local results stay and the reason is told calmly")130 func serverDown() async throws {131 let world = try await FeatureWorld()132 let model = UnifiedSearchModel(repositories: world.repositories, debounce: .zero, sleep: { _ in })133 world.setOffline(true)134 model.query = "taux"135 await model.submit()136 #expect(model.phase == .loaded)137 #expect(!model.results.isEmpty)138 #expect(model.serverFailure?.isOffline == true)139 #expect(!model.usedServer)140 #expect(model.statusText?.contains("appareil seulement") == true)141 world.setOffline(false)142 world.fake.inject(.status(500), method: "GET", path: "^/api/search\\?", count: 10) // more than any retry of a GET143 await model.submit()144 #expect(model.serverFailure?.kind == .server)145 #expect(!model.results.isEmpty)146 world.fake.clearFaults()147 await model.submit()148 #expect(model.serverFailure == nil)149 #expect(model.usedServer)150 }151152 @Test("filters narrow the local results and are sent to the server")153 func filters() async throws {154 let world = try await FeatureWorld()155 let model = UnifiedSearchModel(repositories: world.repositories, debounce: .zero, sleep: { _ in }, now: { FeatureSamples.now })156 model.query = "taux"157 model.section = .research158 world.fake.clearLog()159 world.setOffline(true)160 await model.submit()161 #expect(model.results.map(\.pageId) == [FeatureSamples.workNotePageId])162 world.setOffline(false)163 model.period = .week164 #expect(model.activeFilterCount == 2)165 #expect(model.filters.updatedAfter == FeatureSamples.now.addingTimeInterval(-7 * 86_400))166 await model.submit()167 #expect(searches(world).last?.query.contains("section=research") == true)168 #expect(searches(world).last?.query.contains("since=2026-11-12") == true)169 model.clearFilters()170 #expect(model.activeFilterCount == 0)171 }172173 @Test("no result: an empty state, not an error")174 func noResult() async throws {175 let world = try await FeatureWorld(samples: false)176 let model = UnifiedSearchModel(repositories: world.repositories, debounce: .zero, sleep: { _ in })177 await model.load()178 #expect(model.phase == .loaded)179 model.query = "introuvable"180 await model.submit()181 #expect(model.results.isEmpty)182 #expect(model.answeredQuery == "introuvable")183 #expect(model.phase == .loaded)184 }185186 @Test("the highlight markers of a snippet become emphasised segments")187 func snippet() {188 let start = String(SPNotesStoreMarkers.start), end = String(SPNotesStoreMarkers.end)189 let segments = WorkHighlightedText.segments("Le \(start)taux\(end) fixe et le \(start)taux\(end) variable")190 #expect(segments.map(\.text) == ["Le ", "taux", " fixe et le ", "taux", " variable"])191 #expect(segments.map(\.isMatch) == [false, true, false, true, false])192 #expect(WorkHighlightedText.segments("sans marqueur").map(\.isMatch) == [false])193 #expect(UnifiedSearchModel.originLabel(.both) == "Appareil + serveur")194 }195}196197enum SPNotesStoreMarkers {198 static let start = SPNotesStore.SearchHit.highlightStart199 static let end = SPNotesStore.SearchHit.highlightEnd200}201