SPB Git

Repository Public

RoutingTests.swift 19.4 KB 358 lines swift

1// SP Notes iOS2// File: Tests/RoutingTests.swift3// Description: Routes of the 2.0 shell: links with a block (parsing, round trip, the 1.0 links), web addresses of pages, the4//              coordinator that delivers a route to exactly one window (several shells, a note window, background, signed out),5//              one activity = one navigation, the activity a note advertises (Handoff), and what a dragged note carries.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreSpotlight10import Foundation11import Testing12import SPNotesCore13@testable import SPNotes1415private let noteA = "0b7f6c0e-3f0a-4d5e-9b0a-111111111111"16private let noteB = "0b7f6c0e-3f0a-4d5e-9b0a-222222222222"1718@Suite("Liens avec bloc")19struct BlockDeepLinkTests {20    private func link(_ text: String) -> DeepLink? { URL(string: text).flatMap(DeepLink.init(url:)) }2122    @Test func aNoteLinkCarriesItsBlock() {23        #expect(link("spnotes://note/\(noteA)?block=aB3_x-9Qz0") == .note(noteA, blockId: "aB3_x-9Qz0"))24        #expect(link("spnotes:note/\(noteA.uppercased())?block=k1") == .note(noteA, blockId: "k1"))25        // strict: an empty or malformed block refuses the link instead of opening the note somewhere else26        #expect(link("spnotes://note/\(noteA)?block=") == nil)27        #expect(link("spnotes://note/\(noteA)?block=a%20b") == nil)28        #expect(link("spnotes://note/\(noteA)?block=../x") == nil)29        #expect(link("spnotes://note/\(noteA)?block=" + String(repeating: "a", count: 65)) == nil)30    }3132    @Test func the10LinksAreStillValid() {33        #expect(link("spnotes://note/\(noteA)") == .note(noteA))34        #expect(link("spnotes://note/\(noteA)") == .note(noteA, blockId: nil))35        #expect(link("spnotes://new") == .newNote)36        #expect(link("spnotes://new?kind=tasks&text=Lait") == .new(kind: .tasks, text: "Lait"))37        #expect(link("spnotes://search?q=budget") == .search("budget"))38        #expect(DeepLink.note(noteA).url.absoluteString == "spnotes://note/\(noteA)")39        // an unknown parameter never broke a 1.0 link40        #expect(link("spnotes://note/\(noteA)?utm=x") == .note(noteA))41    }4243    @Test func theNewDestinationsParseStrictly() {44        #expect(link("spnotes://tasks") == .tasks)45        #expect(link("spnotes://inbox") == .inbox)46        #expect(link("spnotes://today") == .today)47        #expect(link("spnotes://capture") == .capture(kind: nil))48        #expect(link("spnotes://capture?kind=audio") == .capture(kind: .audio))49        #expect(link("spnotes://capture?kind=AUDIO") == .capture(kind: .audio))50        #expect(link("spnotes://capture?kind=nope") == nil)51        #expect(link("spnotes://capture?kind=") == nil)52        #expect(link("spnotes://tasks/extra") == nil)53        #expect(link("spnotes://inbox/1") == nil)54        #expect(link("spnotes://graph") == nil)55    }5657    @Test func linksRoundTrip() {58        let links: [DeepLink] = [.note(noteA), .note(noteA, blockId: "blk_1-Z"), .newNote, .new(kind: .tasks, text: "a b"), .search("été 2026"), .search(""),59                                 .tasks, .inbox, .today, .capture(kind: nil), .capture(kind: .scan), .capture(kind: .tasks)]60        for link in links { #expect(DeepLink(url: link.url) == link, "\(link.url)") }61        #expect(DeepLink.note(noteA, blockId: "k1").url.absoluteString == "spnotes://note/\(noteA)?block=k1")62        #expect(DeepLink.capture(kind: .audio).url.absoluteString == "spnotes://capture?kind=audio")63    }6465    @Test func aWebPageAddressIsALinkToTheNote() {66        #expect(link("https://note.spboucher.ai/p/\(noteA)") == .note(noteA))67        #expect(link("https://note.spboucher.ai/p/\(noteA)#blk_9") == .note(noteA, blockId: "blk_9"))68        #expect(link("https://NOTE.spboucher.ai/p/\(noteA.uppercased())/") == .note(noteA))69        #expect(DeepLink.web(DeepLink.webURL(noteId: noteA, blockId: "k1")) == .note(noteA, blockId: "k1"))70        #expect(DeepLink.webURL(noteId: noteA).absoluteString == "https://note.spboucher.ai/p/\(noteA)")71        #expect(DeepLink.webURL(noteId: noteA, blockId: "k1").absoluteString == "https://note.spboucher.ai/p/\(noteA)#k1")72        // anything else on the web is not ours73        for text in ["http://note.spboucher.ai/p/\(noteA)", "https://evil.example/p/\(noteA)", "https://note.spboucher.ai.evil.example/p/\(noteA)",74                     "https://note.spboucher.ai/p/abc", "https://note.spboucher.ai/x/\(noteA)", "https://note.spboucher.ai/p/\(noteA)/edit",75                     "https://note.spboucher.ai:8443/p/\(noteA)", "https://user@note.spboucher.ai/p/\(noteA)", "https://note.spboucher.ai/p/\(noteA)#a%20b",76                     "https://note.spboucher.ai/", "https://example.org"] {77            #expect(link(text) == nil, "\(text)")78        }79    }8081    @MainActor @Test func linksBecomeTypedRoutes() {82        #expect(AppModel.route(for: .note(noteA, blockId: "k1")) == .note(noteA, blockId: "k1"))83        #expect(AppModel.route(for: .tasks) == .tasks)84        #expect(AppModel.route(for: .inbox) == .inbox)85        #expect(AppModel.route(for: .today) == .today)86        #expect(AppModel.route(for: .capture(kind: .audio)) == .capture(kind: "audio"))87        #expect(AppModel.route(for: .capture(kind: nil)) == .capture(kind: nil))88        #expect(AppModel.route(for: .new(kind: .tasks, text: nil)) == nil) // created first, then opened89    }90}9192/// Records what each window received.93@MainActor94private final class Windows {95    let coordinator = RouteCoordinator()96    private(set) var received: [RouteCoordinator.SceneID: [AppRoute]] = [:]97    var total: Int { received.values.reduce(0) { $0 + $1.count } }9899    @discardableResult100    func open(_ kind: RouteCoordinator.SceneKind = .shell, active: Bool = true) -> RouteCoordinator.SceneID {101        let id = RouteCoordinator.SceneID()102        coordinator.register(id, kind: kind, isActive: active) { [weak self] route in self?.received[id, default: []].append(route) }103        return id104    }105106    func routes(_ id: RouteCoordinator.SceneID) -> [AppRoute] { received[id] ?? [] }107}108109@Suite("Coordinateur de routes")110@MainActor111struct RouteCoordinatorTests {112    @Test func aRouteIsConsumedExactlyOnceByTheKeyWindow() {113        let windows = Windows()114        let first = windows.open(), second = windows.open()115        // the window activated last is the key one116        #expect(windows.coordinator.dispatch(.tasks) == second)117        #expect(windows.routes(second) == [.tasks] && windows.routes(first).isEmpty)118        // the user goes back to the first window119        windows.coordinator.noteKey(first)120        #expect(windows.coordinator.dispatch(.search("x")) == first)121        #expect(windows.total == 2, "each route reached one window only")122        #expect(windows.coordinator.pending == nil)123    }124125    @Test func aRouteGoesToTheWindowItNamesEvenWhenAnotherIsKey() {126        let windows = Windows()127        let first = windows.open(), second = windows.open()128        #expect(windows.coordinator.dispatch(.note(noteA, blockId: "k1"), from: first) == first)129        #expect(windows.routes(first) == [.note(noteA, blockId: "k1")] && windows.routes(second).isEmpty)130        // a link arriving in a window that is not active yet (it is being brought forward) is still its own131        let third = windows.open(active: false)132        #expect(windows.coordinator.dispatch(.inbox, from: third) == third)133    }134135    @Test func aNoteWindowNeverSwallowsAShellRoute() {136        let windows = Windows()137        let shellA = windows.open(), shellB = windows.open()138        let note = windows.open(.noteWindow)139        // the note window is key140        #expect(windows.coordinator.dispatch(.tasks) == shellB, "the most recently used shell takes it")141        #expect(windows.coordinator.dispatch(.search("q"), from: note) == shellB, "even when the request arrived in the note window")142        #expect(windows.coordinator.dispatch(.capture(kind: nil)) == shellB)143        #expect(windows.routes(note).isEmpty)144        // a note route goes to the key window: a mention tapped in the note window opens there145        #expect(windows.coordinator.dispatch(.note(noteB)) == note)146        // …and to a shell when a shell is key147        windows.coordinator.noteKey(shellA)148        #expect(windows.coordinator.dispatch(.note(noteA)) == shellA)149        #expect(windows.routes(shellA) == [.note(noteA)] && windows.routes(note) == [.note(noteB)])150        #expect(windows.total == 5)151    }152153    @Test func onlyNoteWindowsOpenAsksForAShellOnce() {154        let windows = Windows()155        var asked = 0156        windows.coordinator.onNeedsShell = { asked += 1 }157        let note = windows.open(.noteWindow)158        #expect(windows.coordinator.dispatch(.tasks) == nil)159        windows.coordinator.flush()160        #expect(asked == 1, "one main window is requested, not one per attempt")161        #expect(windows.routes(note).isEmpty)162        let shell = windows.open()163        #expect(windows.routes(shell) == [.tasks], "the waiting route is delivered to the new shell")164        #expect(windows.coordinator.pending == nil)165    }166167    @Test func aRouteArrivingInTheBackgroundWaitsForAnActiveWindow() {168        let windows = Windows()169        let first = windows.open(active: false), second = windows.open(active: false)170        #expect(windows.coordinator.dispatch(.note(noteA)) == nil)171        #expect(windows.coordinator.pending == .note(noteA))172        #expect(windows.total == 0)173        windows.coordinator.setActive(second, true)174        #expect(windows.routes(second) == [.note(noteA)] && windows.routes(first).isEmpty)175        // becoming active again does not deliver it a second time176        windows.coordinator.setActive(second, false)177        windows.coordinator.setActive(second, true)178        windows.coordinator.setActive(first, true)179        #expect(windows.total == 1)180    }181182    @Test func aRouteArrivingBeforeAnyWindowExistsIsKeptInOrder() {183        let windows = Windows()184        #expect(windows.coordinator.dispatch(.search("un")) == nil)185        #expect(windows.coordinator.dispatch(.note(noteA)) == nil)186        #expect(windows.coordinator.dispatch(.note(noteA)) == nil, "an identical repeat is not queued twice")187        #expect(windows.coordinator.pendingCount == 2)188        let shell = windows.open()189        #expect(windows.routes(shell) == [.search("un"), .note(noteA)])190        #expect(windows.coordinator.pendingCount == 0)191    }192193    @Test func nothingIsDeliveredWhileSignedOut() {194        let windows = Windows()195        var signedIn = false196        windows.coordinator.isAccepting = { signedIn }197        let shell = windows.open()198        #expect(windows.coordinator.dispatch(.note(noteA), from: shell) == nil)199        #expect(windows.routes(shell).isEmpty)200        signedIn = true201        windows.coordinator.flush()202        #expect(windows.routes(shell) == [.note(noteA)])203    }204205    @Test func aClosedWindowReceivesNothingAndItsRoutesAreReassigned() {206        let windows = Windows()207        let first = windows.open(active: false), second = windows.open(active: false)208        windows.coordinator.dispatch(.tasks, from: nil)209        windows.coordinator.unregister(first)210        // a queued route that named a window now closed goes to whoever is there211        var accepting = false212        windows.coordinator.isAccepting = { accepting }213        windows.coordinator.dispatch(.inbox, from: second)214        windows.coordinator.unregister(second)215        accepting = true216        let third = windows.open()217        #expect(windows.routes(third) == [.tasks, .inbox])218        #expect(windows.routes(first).isEmpty && windows.routes(second).isEmpty)219        #expect(windows.coordinator.registeredScenes == 1)220    }221222    @Test func theQueueIsBounded() {223        let windows = Windows()224        for index in 0..<30 { windows.coordinator.dispatch(.search("\(index)")) }225        #expect(windows.coordinator.pendingCount == RouteCoordinator.queueLimit)226        #expect(windows.coordinator.pending == .search("29"))227    }228229    @Test func theModelKeepsThe10InterfaceOverTheCoordinator() throws {230        let app = try ShellFixtures.app()231        app.pendingRoute = .note(noteA)232        #expect(app.pendingRoute == .note(noteA))233        app.pendingRoute = nil234        #expect(app.pendingRoute == nil)235        // with a window, setting the route delivers it at once and nothing stays pending236        var got: [AppRoute] = []237        app.routes.isAccepting = { true }238        app.routes.register(RouteCoordinator.SceneID(), kind: .shell, isActive: true) { got.append($0) }239        app.pendingRoute = .tasks240        #expect(got == [.tasks] && app.pendingRoute == nil)241    }242}243244@Suite("Activités")245@MainActor246struct ActivityRoutingTests {247    @Test func oneActivityIsOneNavigationInOneWindow() throws {248        let app = try ShellFixtures.app()249        app.routes.isAccepting = { true }250        var first: [AppRoute] = [], second: [AppRoute] = [], noteWindow: [AppRoute] = []251        let a = RouteCoordinator.SceneID(), b = RouteCoordinator.SceneID(), c = RouteCoordinator.SceneID()252        app.routes.register(a, kind: .shell, isActive: true) { first.append($0) }253        app.routes.register(b, kind: .shell, isActive: true) { second.append($0) }254        app.routes.register(c, kind: .noteWindow, isActive: true) { noteWindow.append($0) }255256        let handoff = NSUserActivity(activityType: NoteActivity.type)257        NoteActivity.fill(handoff, noteId: noteA, title: "Titre", blockId: "k1")258        // the system gives the activity to one window; that window's single handler dispatches it259        #expect(app.continueActivity(handoff, from: a))260        #expect(first == [.note(noteA, blockId: "k1")])261        #expect(second.isEmpty && noteWindow.isEmpty, "no other window navigates")262        #expect(app.pendingRoute == nil, "nothing is left for a second handler")263    }264265    @Test func theNoteWindowDoesNotReuseTheHandoffActivityType() throws {266        // 1.0: `NoteWindow.activityType == NoteActivity.type`, so "new window" was also seen as a Handoff continuation.267        // 2.0: the window is a `WindowGroup(for: NoteWindowTarget.self)` value; only real continuations use the activity type.268        let target = NoteWindowTarget(noteId: noteA, blockId: "k1")269        let decoded = try JSONDecoder().decode(NoteWindowTarget.self, from: try JSONEncoder().encode(target))270        #expect(decoded == target, "the window restores with its note after a relaunch")271        let types = Bundle.main.object(forInfoDictionaryKey: "NSUserActivityTypes") as? [String] ?? []272        #expect(types.filter { $0 == NoteActivity.type }.count == 1)273        // an activity of another type carrying a note id is not a navigation274        let foreign = NSUserActivity(activityType: "ai.spboucher.spnotes.ios.noteWindow")275        foreign.userInfo = [NoteActivity.noteIdKey: noteA]276        #expect(NoteActivity.route(for: foreign) == nil)277        let app = try ShellFixtures.app()278        #expect(!app.continueActivity(foreign))279        #expect(app.pendingRoute == nil)280    }281282    @Test func everyKindOfActivityGivesOneRoute() {283        let spotlight = NSUserActivity(activityType: CSSearchableItemActionType)284        spotlight.userInfo = [CSSearchableItemActivityIdentifier: noteA.uppercased()]285        #expect(NoteActivity.route(for: spotlight) == .note(noteA))286        let query = NSUserActivity(activityType: CSQueryContinuationActionType)287        query.userInfo = [CSSearchQueryString: "lisbonne"]288        #expect(NoteActivity.route(for: query) == .search("lisbonne"))289        let web = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)290        web.webpageURL = URL(string: "https://note.spboucher.ai/p/\(noteA)#k9")291        #expect(NoteActivity.route(for: web) == .note(noteA, blockId: "k9"))292        let elsewhere = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)293        elsewhere.webpageURL = URL(string: "https://example.org/p/\(noteA)")294        #expect(NoteActivity.route(for: elsewhere) == nil)295        let malformed = NSUserActivity(activityType: NoteActivity.type)296        malformed.userInfo = [NoteActivity.noteIdKey: "../etc", NoteActivity.blockIdKey: "k1"]297        #expect(NoteActivity.route(for: malformed) == nil)298        let badBlock = NSUserActivity(activityType: NoteActivity.type)299        badBlock.userInfo = [NoteActivity.noteIdKey: noteA, NoteActivity.blockIdKey: "a b"]300        #expect(NoteActivity.route(for: badBlock) == .note(noteA), "a malformed block is dropped, the note still opens")301    }302303    @Test func theNoteScreenAdvertisesHandoffWithItsWebAddress() {304        let content = NoteActivity.Content(noteId: noteA, title: "Untitled")305        #expect(content.title == "Sans titre")306        #expect(content.webpageURL.absoluteString == "https://note.spboucher.ai/p/\(noteA)")307        #expect(content.userInfo == [NoteActivity.noteIdKey: noteA])308        #expect(content.isEligibleForHandoff && !content.isEligibleForSearch, "Spotlight indexes notes itself: no duplicate result")309        #expect(content.targetContentIdentifier == "spnotes://note/\(noteA)")310311        let activity = NSUserActivity(activityType: NoteActivity.type)312        NoteActivity.Content(noteId: noteA, title: "Budget 2027", blockId: "k1").apply(to: activity)313        #expect(activity.title == "Budget 2027")314        #expect(activity.webpageURL?.absoluteString == "https://note.spboucher.ai/p/\(noteA)#k1")315        #expect(activity.isEligibleForHandoff && !activity.isEligibleForSearch)316        #expect(activity.requiredUserInfoKeys == [NoteActivity.noteIdKey])317        // what is advertised is what the receiving device continues318        #expect(NoteActivity.route(for: activity) == .note(noteA, blockId: "k1"))319        #expect(activity.webpageURL.flatMap(DeepLink.web) == .note(noteA, blockId: "k1"))320    }321}322323@Suite("Glisser-déposer")324struct NoteTransferTests {325    @Test func aDraggedNoteCarriesItsIdsAndItsWebAddress() throws {326        let one = NoteTransfer(ids: [noteA])327        #expect(one.webURLs == [URL(string: "https://note.spboucher.ai/p/\(noteA)")!])328        #expect(one.plainText == "https://note.spboucher.ai/p/\(noteA)")329        let two = NoteTransfer(ids: [noteA, noteB, "not an id"])330        #expect(two.webURLs.count == 2, "a malformed id never becomes an address")331        #expect(two.plainText.split(separator: "\n").count == 2)332        // between our own windows: the ids, exactly333        #expect(try JSONDecoder().decode(NoteTransfer.self, from: try JSONEncoder().encode(two)) == two)334    }335336    @Test func ourOwnAddressesDroppedOnAListAreNotTextForANewNote() {337        #expect(NoteTransfer.isOwnReference(NoteTransfer(ids: [noteA]).plainText))338        #expect(NoteTransfer.isOwnReference(NoteTransfer(ids: [noteA, noteB]).plainText + "\n"))339        #expect(!NoteTransfer.isOwnReference("Acheter du lait"))340        #expect(!NoteTransfer.isOwnReference("https://example.org/p/\(noteA)"))341        #expect(!NoteTransfer.isOwnReference("Voir https://note.spboucher.ai/p/\(noteA)"))342        #expect(!NoteTransfer.isOwnReference(""))343    }344345    @Test func theTransferExportsTheReferenceAUrlAndText() async throws {346        // the representations other apps see, through the same machinery a drag uses347        let provider = NSItemProvider()348        provider.register(NoteTransfer(ids: [noteA]))349        let types = provider.registeredContentTypes.map(\.identifier)350        #expect(types.first == "ai.spboucher.spnotes.note-reference", "our own lists receive the reference first")351        #expect(types.contains("public.url"))352        #expect(types.contains("public.utf8-plain-text") || types.contains("public.plain-text"))353        let many = NSItemProvider()354        many.register(NoteTransfer(ids: [noteA, noteB]))355        #expect(!many.registeredContentTypes.map(\.identifier).contains("public.url"), "several notes: text only (one URL would lose the others)")356    }357}358
Files main
Menu

Theme