SPB Git

Repository Public License

FocusAndSearchTests.swift 13.0 KB 221 lines swift

1import Foundation2import NavigatorCore3import Persistence4import Testing5@testable import OrbitEngine67/// A clock the test moves by hand.8final class TestClock: @unchecked Sendable {9    private let lock = NSLock()10    private var date: Date11    init(_ start: TimeInterval = 1_700_000_000) { date = Date(timeIntervalSince1970: start) }12    var now: Date { lock.withLock { date } }13    func advance(_ seconds: TimeInterval) { lock.withLock { date.addTimeInterval(seconds) } }14}1516@Suite struct FocusSessionTests {17    let start = Date(timeIntervalSince1970: 1_000)1819    @Test func timerCountsDownAndFinishesOnItsOwn() throws {20        var session = FocusSession()21        try session.start(duration: 600, now: start)22        #expect(session.phase == .running && session.remaining(now: start) == 600)23        #expect(session.remaining(now: start.addingTimeInterval(150)) == 450)24        #expect(session.deadline(now: start.addingTimeInterval(150)) == start.addingTimeInterval(600))25        let refreshed1 = session.refresh(now: start.addingTimeInterval(599))26        #expect(!refreshed1)27        let refreshed2 = session.refresh(now: start.addingTimeInterval(5_000))28        #expect(refreshed2)29        #expect(session.phase == .finished && session.endReason == .timerElapsed)30        #expect(session.endedAt == start.addingTimeInterval(600))   // when it ran out, not when it was noticed31        #expect(session.elapsed(now: start.addingTimeInterval(9_999)) == 600)32        #expect(session.remaining(now: start) == nil)33    }3435    @Test func pausesDoNotCount() throws {36        var session = FocusSession()37        try session.start(duration: 600, now: start)38        try session.pause(now: start.addingTimeInterval(100))39        #expect(session.remaining(now: start.addingTimeInterval(10_000)) == 500)40        #expect(session.deadline(now: start.addingTimeInterval(10_000)) == nil)41        let refreshed3 = session.refresh(now: start.addingTimeInterval(10_000))42        #expect(!refreshed3)43        try session.resume(now: start.addingTimeInterval(10_000))44        #expect(session.deadline(now: start.addingTimeInterval(10_100)) == start.addingTimeInterval(10_500))45        let refreshed4 = session.refresh(now: start.addingTimeInterval(10_500))46        #expect(refreshed4)47        #expect(session.endedAt == start.addingTimeInterval(10_500))48    }4950    @Test func sessionsWithoutATimerLastUntilEnded() throws {51        var session = FocusSession()52        try session.start(duration: nil, now: start)53        #expect(session.remaining(now: start) == nil && session.deadline(now: start) == nil)54        let refreshed5 = session.refresh(now: start.addingTimeInterval(1e9))55        #expect(!refreshed5)56        try session.end(now: start.addingTimeInterval(42))57        #expect(session.phase == .finished && session.endReason == .endedByUser && session.elapsed(now: start.addingTimeInterval(99)) == 42)58        var zero = FocusSession()59        try zero.start(duration: 0, now: start)60        #expect(zero.duration == nil)61    }6263    @Test func invalidTransitionsThrow() throws {64        var session = FocusSession()65        #expect(throws: FocusSession.TransitionError.invalid(from: .idle)) { try session.pause(now: start) }66        #expect(throws: FocusSession.TransitionError.invalid(from: .idle)) { try session.resume(now: start) }67        #expect(throws: FocusSession.TransitionError.invalid(from: .idle)) { try session.end(now: start) }68        try session.start(duration: 60, now: start)69        #expect(throws: FocusSession.TransitionError.invalid(from: .running)) { try session.start(duration: 60, now: start) }70        #expect(throws: FocusSession.TransitionError.invalid(from: .running)) { try session.resume(now: start) }71        try session.pause(now: start)72        #expect(throws: FocusSession.TransitionError.invalid(from: .paused)) { try session.pause(now: start) }73        try session.end(now: start)74        // Pausing after the timer ran out reports the finished phase.75        var late = FocusSession()76        try late.start(duration: 10, now: start)77        #expect(throws: FocusSession.TransitionError.invalid(from: .finished)) { try late.pause(now: start.addingTimeInterval(11)) }78        try late.start(duration: 10, now: start.addingTimeInterval(20))   // a finished session can start again79        #expect(late.phase == .running && late.elapsed(now: start.addingTimeInterval(21)) == 1)80    }8182    @Test func clockGoingBackwardsNeverProducesNegativeTime() throws {83        var session = FocusSession()84        try session.start(duration: 60, now: start)85        #expect(session.elapsed(now: start.addingTimeInterval(-500)) == 0)86        #expect(session.remaining(now: start.addingTimeInterval(-500)) == 60)87    }88}8990@Suite struct FocusControllerTests {91    private func fixture() async throws -> (NavigatorDatabase, OrbitSpace, BrowserWindow, TestClock, FocusController) {92        let database = try await NavigatorDatabase.inMemory()93        let profile = Profile(name: "P")94        try await database.profiles.save(profile)95        let space = OrbitSpace(profileID: profile.id, name: "Deep work")96        try await database.spaces.save(space)97        let window = BrowserWindow(spaceID: space.id, tabLayout: .horizontal, isSidebarCollapsed: false, isAgentPanelOpen: true)98        try await database.windows.save(window)99        let clock = TestClock()100        return (database, space, window, clock, FocusController(database: database, now: { clock.now }))101    }102103    @Test func settingsArePersistedWithTheSpace() async throws {104        let (database, space, _, _, controller) = try await fixture()105        #expect(try await controller.settings(for: space.id) == FocusSettings())106        try await controller.updateSettings(FocusSettings(isEnabled: true, timerSeconds: 1_500, hidesTabStrip: false, hidesSidebar: true), for: space.id)107        #expect(try await database.spaces.space(space.id)?.focus.timerSeconds == 1_500)108        try await controller.updateSettings(FocusSettings(timerSeconds: -5), for: space.id)109        #expect(try await controller.settings(for: space.id).timerSeconds == nil)110        await #expect(throws: FocusError.spaceNotFound) { try await controller.settings(for: SpaceID()) }111    }112113    @Test func aSessionRunsPausesAndRestoresTheWindow() async throws {114        let (_, space, window, clock, controller) = try await fixture()115        try await controller.updateSettings(FocusSettings(isEnabled: true, timerSeconds: 300, hidesTabStrip: true, hidesSidebar: false), for: space.id)116        let started = try await controller.start(space: space.id, windows: [window])117        #expect(started.remaining == 300 && started.session.phase == .running)118        #expect(try await controller.presentation(space: space.id) == (true, false))119        await #expect(throws: FocusError.invalidTransition(from: .running)) { try await controller.start(space: space.id, windows: [window]) }120121        clock.advance(100)122        #expect(try await controller.pause(space: space.id).remaining == 200)123        clock.advance(1_000)124        #expect(try await controller.resume(space: space.id).deadline == clock.now.addingTimeInterval(200))125        #expect(await controller.activeSpaces() == [space.id])126        clock.advance(250)127        let finished = try await controller.status(space: space.id)128        #expect(finished?.session.phase == .finished && finished?.session.endReason == .timerElapsed)129        #expect(try await controller.presentation(space: space.id) == (false, false))130        #expect(await controller.activeSpaces().isEmpty)131132        // During the session the UI collapsed the sidebar and the user moved to another tab layout.133        var during = window134        during.isSidebarCollapsed = true; during.isAgentPanelOpen = false; during.tabLayout = .compact135        during.selectedTabID = TabID()136        let restorations = try await controller.end(space: space.id)137        #expect(restorations.count == 1)138        let restored = restorations[0].restoring(during)139        #expect(!restored.isSidebarCollapsed && restored.isAgentPanelOpen && restored.tabLayout == .horizontal)140        #expect(restored.selectedTabID == during.selectedTabID)141        #expect(try await controller.status(space: space.id) == nil)142        await #expect(throws: FocusError.noActiveSession) { try await controller.end(space: space.id) }143        await #expect(throws: FocusError.noActiveSession) { try await controller.pause(space: space.id) }144    }145146    @Test func theTimerCanBeOverriddenForOneSession() async throws {147        let (_, space, window, _, controller) = try await fixture()148        try await controller.updateSettings(FocusSettings(timerSeconds: 300), for: space.id)149        #expect(try await controller.start(space: space.id, windows: [window], timerSeconds: .some(nil)).remaining == nil)150        try await controller.end(space: space.id)151        #expect(try await controller.start(space: space.id, windows: [window], timerSeconds: 60).remaining == 60)152    }153154    @Test func ghostSpaceSettingsStayInMemory() async throws {155        let (database, _, _, _, controller) = try await fixture()156        let ghostProfile = ProfileID(), ghostSpace = SpaceID()157        database.ghosts.declare(profile: ghostProfile, spaces: [ghostSpace])158        try await controller.updateSettings(FocusSettings(timerSeconds: 90), for: ghostSpace)159        #expect(try await controller.settings(for: ghostSpace).timerSeconds == 90)160        #expect(try await database.spaces.space(ghostSpace) == nil)161        #expect(try await controller.start(space: ghostSpace, windows: []).remaining == 90)162        await controller.forgetGhost(space: ghostSpace)163        #expect(try await controller.status(space: ghostSpace) == nil)164        #expect(try await controller.settings(for: ghostSpace).timerSeconds == nil)165    }166}167168@Suite struct FuzzySearchTests {169    @Test func subsequencesMatchWithoutCaseOrDiacritics() {170        #expect(FuzzyMatcher.match("gh", in: "GitHub")?.matchedOffsets == [0, 3])171        #expect(FuzzyMatcher.match("resume", in: "Mon Résumé")?.matchedOffsets == [4, 5, 6, 7, 8, 9])172        #expect(FuzzyMatcher.match("xyz", in: "GitHub") == nil)173        #expect(FuzzyMatcher.match("hg", in: "GitHub") == nil)   // order matters174        #expect(FuzzyMatcher.match("", in: "GitHub") == nil)175        #expect(FuzzyMatcher.match("   ", in: "GitHub") == nil)176        #expect(FuzzyMatcher.match("toolong", in: "tool") == nil)177    }178179    @Test func betterMatchesScoreHigher() throws {180        let exact = try #require(FuzzyMatcher.match("mail", in: "Mail"))181        let prefix = try #require(FuzzyMatcher.match("mail", in: "Mailbox rules"))182        let word = try #require(FuzzyMatcher.match("mail", in: "SP Mail"))183        let scattered = try #require(FuzzyMatcher.match("mail", in: "Main article list"))184        #expect(exact.score > prefix.score)185        #expect(prefix.score > word.score)186        #expect(word.score > scattered.score)187        let boundary = try #require(FuzzyMatcher.match("ot", in: "orbit tabs"))188        #expect(boundary.matchedOffsets == [0, 6])   // prefers the start of a word over the first "t"189    }190191    @Test func severalTermsMustAllMatchInAnyOrder() {192        #expect(FuzzyMatcher.match("tabs orbit", in: "Orbit tabs") != nil)193        #expect(FuzzyMatcher.match("orbit zebra", in: "Orbit tabs") == nil)194        #expect(FuzzyMatcher.match("or ta", in: "Orbit tabs")?.matchedOffsets == [0, 1, 6, 7])195    }196197    @Test func searchRanksSpacesAndTabs() {198        let profile = ProfileID(), window = WindowID()199        let research = OrbitSpace(profileID: profile, name: "Research"), home = OrbitSpace(profileID: profile, name: "Home")200        let old = Date(timeIntervalSince1970: 100), recent = Date(timeIntervalSince1970: 200)201        let paper = Tab(windowID: window, spaceID: research.id, url: URL(string: "https://arxiv.org/abs/1234"), title: "Research paper on orbits", lastActiveAt: old)202        let byURL = Tab(windowID: window, spaceID: home.id, url: URL(string: "https://www.research-gate.example/home?token=research"), title: "Welcome", lastActiveAt: recent)203        let twinA = Tab(windowID: window, spaceID: home.id, title: "Search", lastActiveAt: old)204        let twinB = Tab(windowID: window, spaceID: home.id, title: "Search", lastActiveAt: recent)205        let results = OrbitSearch.search("research", spaces: [home, research], tabs: [paper, byURL, twinA, twinB])206        #expect(results.first?.item == .space(research))207        #expect(results.contains { $0.item == .tab(paper) && $0.field == .title })208        #expect(results.contains { $0.item == .tab(byURL) && $0.field == .url })209        #expect(!results.contains { $0.item == .space(home) })210        let twins = OrbitSearch.search("search", spaces: [], tabs: [twinA, twinB])211        #expect(twins.map(\.item) == [.tab(twinB), .tab(twinA)])   // equal scores: most recent first212        #expect(OrbitSearch.search("search", spaces: [], tabs: [twinA, twinB], limit: 1).count == 1)213        #expect(OrbitSearch.search("  ", spaces: [home], tabs: [paper]).isEmpty)214    }215216    @Test func urlQueriesAreNotSearched() {217        #expect(OrbitSearch.searchableText(of: URL(string: "https://www.example.com/a/b?secret=1#frag")!) == "example.com/a/b")218        #expect(OrbitSearch.searchableText(of: URL(string: "https://example.com/")!) == "example.com")219    }220}221
Files main
Menu

Theme