SPB Git

Repository Public License

ExtensionTests.swift 40.1 KB 658 lines swift

1import DownloadEngine2import Foundation3import LunarDesign4import NavigatorCore5import PrivacyEngine6import SwiftUI7import TestSupport8import Testing9@testable import Persistence10@testable import WebRuntime11@testable import NavigatorUI1213/// A feature the tests plug in: one contribution of each kind, and a log of the hooks it receives.14@MainActor15final class ProbeFeature {16    var events: [String] = []17    var commits: [NavigationEvent] = []18    var finishes: [NavigationEvent] = []19    var profileEvents: [ProfileEvent] = []20    var ranCommand = 021    var readyStores = 022    let strings = FeatureStrings(module: "Probe", bundle: .main)2324    func register(in registry: FeatureRegistry) {25        registry.register(NavigatorCommand(id: "probe.run", title: strings.text("Run Probe"), category: .tools,26                                           shortcut: CommandShortcut("9", modifiers: [.command, .option]),27                                           placements: [.menuBar(.tools, group: 10, order: 10), .windowMenu(group: 50, order: 10),28                                                        .tabContextMenu(group: 50, order: 10), .pageContextMenu(order: 10)],29                                           isAvailable: { $0.window != nil }) { [weak self] _ in self?.ranCommand += 1 })30        registry.register(SidePanelContribution(id: "probe.panel", title: strings.text("Probe"), icon: .glyph(.lens)) { _ in Text("panel") })31        registry.register(ToolbarItemContribution(id: "probe.item", label: strings.text("Probe"), icon: .glyph(.shield),32                                                  placement: [.addressField, .capsule], isVisible: { $0.isWebPage },33                                                  state: { _ in ContributionState(isActive: true, badge: 3) },34                                                  action: .command("probe.run")))35        registry.register(SidebarSectionContribution(id: "probe.section", placement: .belowTabs) { _ in Text("section") })36        registry.register(SidebarFooterItem(id: "probe.footer", label: strings.text("Probe"), icon: .glyph(.lens), action: .panel("probe.panel")))37        registry.register(WindowBadgeContribution(id: "probe.badge") { window in38            window.isEphemeral ? WindowBadge(label: "Private", icon: .glyph(.ghost), status: .accent) : nil39        })40        registry.register(WindowOverlayContribution(id: "probe.overlay", style: .scrim(alignment: .top)) { _ in Text("overlay") })41        registry.register(webArea: WebAreaProvider(id: "probe.webarea", priority: 100,42                                                   isActive: { $0.existingFeatureState(ProbeWindowState.self)?.takesOver ?? false }) { _ in Text("area") })43        registry.register(TabLayoutContribution(mode: .grid, title: strings.text("Grid"), icon: .symbol("square.grid.2x2")) {44            WebAreaView(window: $0.window)45        })46        registry.register(SettingsSectionContribution(id: "probe.settings", title: strings.text("Probe"), icon: .glyph(.lens), order: 100) { _ in Text("settings") })47        registry.register(EngineHooks(48            id: "probe",49            profileContextCreated: { [weak self] in self?.profileEvents.append($0); self?.events.append("profile:\($0.isGhost ? "ghost" : "standard")") },50            windowOpened: { [weak self] in self?.events.append("windowOpened:\($0.isEphemeral ? "ephemeral" : "normal")") },51            windowClosed: { [weak self] in self?.events.append("windowClosed:\($0.isEphemeral ? "ephemeral" : "normal")") },52            configureSettings: { settings, _, isEphemeral in if isEphemeral { settings.mirrorsConsole = true } },53            engineCreated: { [weak self] in self?.events.append("engineCreated:\($0.isEphemeral)") },54            engineWillClose: { [weak self] _ in self?.events.append("engineWillClose") },55            navigationCommitted: { [weak self] in self?.commits.append($0) },56            navigationFinished: { [weak self] in self?.finishes.append($0) },57            tabSelected: { [weak self] _, previous in self?.events.append("tabSelected:\(previous == nil ? "first" : "switch")") },58            tabClosed: { [weak self] _ in self?.events.append("tabClosed") }))59        registry.whenStoreReady { [weak self] store in60            self?.readyStores += 161            store.services.register(ProbeService(name: "probe"), for: .probe)62        }63    }64}6566@MainActor @Observable final class ProbeWindowState { var takesOver = false }67struct ProbeService: Sendable, Equatable { var name: String }68extension ServiceKey where Service == ProbeService { static let probe = ServiceKey("probe.service") }6970extension StoreFixture {71    func open(registry: FeatureRegistry, permissions: PermissionService? = nil, downloads: DownloadManager? = nil,72              faviconDirectory: URL? = nil, database existing: NavigatorDatabase? = nil) async throws -> (BrowserStore, NavigatorDatabase) {73        let database: NavigatorDatabase74        if let existing { database = existing } else {75            database = try await NavigatorDatabase(url: directory.url.appending(path: "Navigator.sqlite"))76        }77        let settings = AppSettings(store: database.settings)78        await settings.load()79        let store = try await BrowserStore.open(database: database, settings: settings, permissions: permissions, downloads: downloads,80                                                faviconDirectory: faviconDirectory, sessionDebounce: .milliseconds(20), registry: registry)81        return (store, database)82    }83}8485/// Rows per table, to prove that something wrote nothing.86func tableCounts(_ database: NavigatorDatabase) async throws -> [String: Int] {87    try await database.sqlite.read { connection in88        var counts: [String: Int] = [:]89        for table in try connection.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'history_fts_%'") {90            let name = try table.get("name", as: String.self)91            counts[name] = try connection.scalar("SELECT count(*) FROM \(name)", as: Int.self) ?? 092        }93        return counts94    }95}9697@Suite("Feature registry")98@MainActor99struct FeatureRegistryTests {100    @Test func shellContributionsAreWellFormed() {101        let registry = FeatureRegistry()102        #expect(registry.issues.isEmpty)103        for (kind, ids) in registry.identifiersByKind {104            #expect(Set(ids).count == ids.count, "duplicate \(kind) identifiers")105        }106        #expect(registry.shortcutCollisions.isEmpty, "\(registry.shortcutCollisions)")107        #expect(registry.commands.count >= 50)108        for command in registry.commands {109            #expect(command.id.range(of: #"^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$"#, options: .regularExpression) != nil, "\(command.id)")110            #expect(!command.title.string.isEmpty && command.title.module == "NavigatorUI")111        }112        #expect(registry.panels.map(\.id) == [.history, .bookmarks, .downloads, .settings, .help])113        #expect(registry.supportedLayouts == [.vertical, .horizontal, .compact])114        #expect(registry.settingsSections.last?.id == ShellSettingsSectionID.about)115        #expect(registry.sidebarFooterItems.map(\.id).suffix(1) == ["settings"])116        // Every action the menus offered before the registry existed is a command.117        let expected = [ShellCommandID.newTab, ShellCommandID.closeTab, ShellCommandID.reopenClosedTab, ShellCommandID.newWindow,118                        ShellCommandID.back, ShellCommandID.forward, ShellCommandID.reload, ShellCommandID.stop, ShellCommandID.find,119                        ShellCommandID.zoomIn, ShellCommandID.zoomOut, ShellCommandID.zoomReset, ShellCommandID.toggleSidebar,120                        ShellCommandID.pinTab, ShellCommandID.duplicateTab, ShellCommandID.muteTab, ShellCommandID.showBookmarks,121                        ShellCommandID.showHistory, ShellCommandID.showDownloads, ShellCommandID.showSettings,122                        ShellCommandID.toggleContentMode, ShellCommandID.copyURL, ShellCommandID.share, ShellCommandID.print,123                        ShellCommandID.savePDF, ShellCommandID.nextTab, ShellCommandID.previousTab, ShellCommandID.moveTabLeft,124                        ShellCommandID.moveTabRight, ShellCommandID.closeOtherTabs, ShellCommandID.showHelp]125            + (1...9).map(ShellCommandID.selectTab) + TabLayoutMode.allCases.map(ShellCommandID.tabLayout)126        for id in expected { #expect(registry.command(id) != nil, "missing command \(id)") }127        // Menus are generated from placements: the File menu starts with New Tab, Help holds the help command.128        #expect(registry.commands(in: .file).first?.first?.id == ShellCommandID.newTab)129        #expect(registry.commands(in: .help).flatMap { $0 }.map(\.id) == [ShellCommandID.showHelp, ShellCommandID.showWelcome])130        #expect(registry.commands(in: .tools).isEmpty)131        #expect(registry.tabContextMenuCommands.flatMap { $0 }.map(\.id).contains(ShellCommandID.closeOtherTabs))132    }133134    @Test func duplicatesAreRefusedAndReported() {135        let registry = FeatureRegistry(includesShell: false)136        let probe = ProbeFeature()137        probe.register(in: registry)138        #expect(registry.issues.isEmpty)139        probe.register(in: registry)140        #expect(registry.issues.count == 11, "\(registry.issues)")141        #expect(registry.commands.count == 1 && registry.panels.count == 1 && registry.overlays.count == 1)142        #expect(registry.presentable("probe.overlay") == .overlay)143        #expect(registry.presentable("probe.panel") == .panel)144        #expect(registry.presentable("probe.run") == .command)145        #expect(registry.presentable("nothing") == nil)146        #expect(registry.commands(in: .tools).flatMap { $0 }.map(\.id) == ["probe.run"])147        #expect(registry.toolbarItems(in: .capsule).map(\.id) == ["probe.item"])148        #expect(registry.supportedLayouts == [.grid])149    }150151    @Test func shortcutsDescribeThemselvesAndCollide() {152        #expect(CommandShortcut("T", modifiers: [.command, .shift]) == CommandShortcut("t", modifiers: [.shift, .command]))153        #expect(CommandShortcut("t", modifiers: [.command, .shift]).description == "⇧⌘T")154        #expect(CommandShortcut(.tab, modifiers: [.control, .shift]).keyCaps == ["⌃", "⇧", "⇥"])155        let registry = FeatureRegistry()156        let strings = FeatureStrings(module: "Probe", bundle: .main)157        registry.register(NavigatorCommand(id: "probe.clash", title: strings.text("Clash"), category: .tools, shortcut: CommandShortcut("T")) { _ in })158        #expect(registry.shortcutCollisions.map(\.commandIDs) == [["probe.clash", ShellCommandID.newTab]])159    }160161    @Test func helpListsCommandsFromTheRegistry() {162        let registry = FeatureRegistry()163        let probe = ProbeFeature()164        probe.register(in: registry)165        let shortcuts = HelpIndex.sections(registry: registry, query: "", shortcutsOnly: true)166        #expect(shortcuts.first?.id == "tabs")167        #expect(shortcuts.flatMap(\.rows).allSatisfy { $0.shortcut != nil })168        #expect(shortcuts.flatMap(\.rows).contains { $0.id == "probe.run" }, "a feature command appears without more work")169        let all = HelpIndex.sections(registry: registry, query: "", shortcutsOnly: false)170        #expect(all.flatMap(\.rows).count == registry.commands.count)171        let found = HelpIndex.sections(registry: registry, query: "reopen", shortcutsOnly: false).flatMap(\.rows)172        #expect(found.map(\.id) == [ShellCommandID.reopenClosedTab])173        #expect(HelpIndex.sections(registry: registry, query: "⇧⌘T", shortcutsOnly: true).flatMap(\.rows).map(\.id) == [ShellCommandID.reopenClosedTab])174        #expect(HelpIndex.sections(registry: registry, query: "zzzz", shortcutsOnly: false).isEmpty)175    }176}177178@Suite("Shell through the registry", .serialized)179@MainActor180struct ExtensionIntegrationTests {181    @Test func commandsDriveTheWindow() async throws {182        let fixture = try await StoreFixture()183        defer { fixture.finish() }184        let registry = FeatureRegistry()185        let probe = ProbeFeature()186        probe.register(in: registry)187        let (store, database) = try await fixture.open(registry: registry)188        #expect(probe.readyStores == 1 && store.services.service(.probe) == ProbeService(name: "probe"))189        #expect(store.services.registeredServiceNames == ["probe.service"])190        let window = store.claimWindow()191        let context = window.commandContext()192        #expect(context.environment.store === store && context.registry === registry)193194        #expect(await registry.run(ShellCommandID.newTab, in: context))195        #expect(window.tabs.count == 2 && window.omnibox.isEditing)196        window.omnibox.cancel()197        let first = window.tabs[0], second = window.tabs[1]198199        // A command aimed at a tab that is not the selected one (context menu).200        #expect(await registry.run(ShellCommandID.pinTab, in: context.targeting(first)))201        #expect(first.isPinned && !second.isPinned)202        #expect(registry.command(ShellCommandID.pinTab)?.displayTitle(in: context.targeting(first)) == "Unpin Tab")203        #expect(registry.command(ShellCommandID.pinTab)?.displayTitle(in: context.targeting(second)) == "Pin Tab")204        #expect(await registry.run(ShellCommandID.pinTab, in: context.targeting(first)))205206        // Unavailable commands do not run.207        #expect(!(await registry.run(ShellCommandID.back, in: context)))208        #expect(!(await registry.run(ShellCommandID.find, in: context)), "nothing to search on the new-tab page")209        #expect(!(await registry.run("does.not.exist", in: context)))210211        window.navigate(to: fixture.url("one"))212        try await waitForTitle(second, "Page one")213        let page = window.commandContext()214        #expect(page.isWebPage && page.hasPage)215        #expect(await registry.run(ShellCommandID.find, in: page))216        #expect(window.isFindVisible)217        #expect(await registry.run(ShellCommandID.zoomIn, in: page))218        #expect(second.engine.pageZoom > 1)219        #expect(await registry.run(ShellCommandID.zoomReset, in: page))220        #expect(!(await registry.run(ShellCommandID.zoomReset, in: page)), "already at actual size")221222        #expect(await registry.run(ShellCommandID.selectTab(1), in: page))223        #expect(window.selectedTabID == first.id)224        #expect(await registry.run(ShellCommandID.selectTab(9), in: window.commandContext()))225        #expect(window.selectedTabID == second.id)226        #expect(await registry.run(ShellCommandID.moveTabLeft, in: window.commandContext()))227        #expect(window.tabs.map(\.id) == [second.id, first.id])228        #expect(!(await registry.run(ShellCommandID.moveTabLeft, in: window.commandContext())))229        #expect(await registry.run(ShellCommandID.moveTabRight, in: window.commandContext()))230        #expect(window.tabs.map(\.id) == [first.id, second.id])231232        // Layouts: the shell's three, plus the one the probe registered; orbit has no renderer.233        #expect(registry.supportedLayouts == [.vertical, .horizontal, .compact, .grid])234        #expect(await registry.run(ShellCommandID.tabLayout(.grid), in: window.commandContext()))235        #expect(window.tabLayout == .grid && store.settings.defaultTabLayout == .grid)236        #expect(!(await registry.run(ShellCommandID.tabLayout(.orbit), in: window.commandContext())))237        window.tabLayout = .orbit238        #expect(window.tabLayout == .grid)239240        // Panels, overlays, launch-argument resolution.241        #expect(await registry.present("help", in: window) && window.panel == .help)242        #expect(await registry.present("probe.panel", in: window) && window.panel == "probe.panel")243        #expect(await registry.present("probe.overlay", in: window) && window.presentedOverlayID == "probe.overlay")244        window.dismissOverlay()245        #expect(window.presentedOverlayID == nil)246        window.present(overlay: "unknown")247        #expect(window.presentedOverlayID == nil)248        #expect(await registry.present("probe.run", in: window) && probe.ranCommand == 1)249        #expect(!(await registry.present("nothing", in: window)))250        window.run("probe.run")251        try await waitUntil("command ran") { probe.ranCommand == 2 }252253        // Toolbar items: visible on http pages only, with their state.254        let item = try #require(registry.toolbarItem("probe.item"))255        #expect(item.isVisible(window.commandContext()))256        #expect(item.state(window.commandContext()).badge == 3)257        window.select(first.id)258        #expect(!item.isVisible(window.commandContext()), "the new-tab page is not a web page")259260        // Web area providers and chrome requests follow per-window state.261        #expect(registry.activeWebAreaProvider(for: window) == nil)262        window.featureState(ProbeWindowState.self) { ProbeWindowState() }.takesOver = true263        #expect(registry.activeWebAreaProvider(for: window)?.id == "probe.webarea")264        #expect(window.featureState(ProbeWindowState.self) { ProbeWindowState() }.takesOver, "one state per window")265        window.setChromeHidden([.sidebar, .tabStrip], requester: "probe")266        window.setChromeHidden([.toolbar], requester: "other")267        #expect(window.hiddenChrome == [.sidebar, .tabStrip, .toolbar])268        window.setChromeHidden([], requester: "probe")269        #expect(window.hiddenChrome == [.toolbar])270271        await store.shutDown()272        await database.close()273    }274275    @Test func hooksFollowTabsAndPages() async throws {276        let fixture = try await StoreFixture()277        defer { fixture.finish() }278        let registry = FeatureRegistry()279        let probe = ProbeFeature()280        probe.register(in: registry)281        let (store, database) = try await fixture.open(registry: registry)282        let window = store.claimWindow()283        #expect(probe.events == ["windowOpened:normal", "profile:standard", "engineCreated:false", "tabSelected:first"])284        #expect(probe.profileEvents.first?.context === store.profileContext(for: store.profile))285        probe.events.removeAll()286287        let tab = try #require(window.selectedTab)288        window.navigate(to: fixture.url("one"))289        try await waitForTitle(tab, "Page one")290        try await waitUntil("finish announced") { probe.finishes.count == 1 }291        #expect(probe.commits.count == 1)292        let commit = try #require(probe.commits.first), finish = try #require(probe.finishes.first)293        #expect(commit.url == fixture.url("one") && finish.url == fixture.url("one"))294        #expect(commit.commitCount == finish.commitCount && finish.title == "Page one")295        #expect(commit.tab.tabID == tab.id && commit.tab.windowID == window.id && commit.tab.spaceID == store.space.id)296        #expect(commit.profile.id == store.profile.id && !commit.isGhost && !commit.isEphemeral)297298        // A reload is a new commit of the same address; a second tab is announced separately.299        tab.engine.reload()300        try await waitUntil("reload announced") { probe.finishes.count == 2 }301        #expect(probe.commits.map(\.url) == [fixture.url("one"), fixture.url("one")])302        let other = window.newTab(url: fixture.url("two"))303        try await waitForTitle(other, "Page two")304        try await waitUntil("second tab announced") { probe.finishes.contains { $0.tab.tabID == other.id } }305        #expect(probe.events == ["engineCreated:false", "tabSelected:switch"])306        #expect(probe.profileEvents.count == 1, "one context per standard profile")307308        window.close(other.id)309        #expect(probe.events.suffix(3) == ["tabClosed", "engineWillClose", "tabSelected:switch"])310        store.closeWindow(window.id)311        #expect(probe.events.suffix(2) == ["engineWillClose", "windowClosed:normal"])312        await store.shutDown()313        await database.close()314    }315316    @Test func anEphemeralWindowWritesNothing() async throws {317        let fixture = try await StoreFixture()318        defer { fixture.finish() }319        let icons = try TemporaryDirectory(prefix: "orix-icons")320        defer { icons.remove() }321        let registry = FeatureRegistry()322        let probe = ProbeFeature()323        probe.register(in: registry)324        let database = try await NavigatorDatabase(url: fixture.directory.url.appending(path: "Navigator.sqlite"))325        let permissions = PermissionService(database: database)326        let (store, _) = try await fixture.open(registry: registry, permissions: permissions, faviconDirectory: icons.url, database: database)327        let normal = store.claimWindow()328        normal.navigate(to: fixture.url("one"))329        try await waitForTitle(try #require(normal.selectedTab), "Page one")330        try await waitUntil("normal page announced") { probe.finishes.count == 1 }331        await store.session.flush()332        try await waitUntilAsync("normal visit recorded") {333            (try? await database.history.visits(profile: store.profile.id, limit: 10).count) == 1334        }335        let before = try await tableCounts(database)336        let filesBefore = (try? FileManager.default.subpathsOfDirectory(atPath: icons.url.path)) ?? []337        probe.events.removeAll()338339        // A private window on a standard profile gets a ghost profile of its own.340        let ghost = store.openWindow(in: store.space, profile: store.profile, persistence: .ephemeral)341        #expect(ghost.isEphemeral && ghost.profile.isGhost && ghost.profile.id != store.profile.id)342        #expect(ghost.profile.name == store.profile.name && ghost.space.id == store.space.id)343        #expect(store.sceneSwitchRequest == ghost.id, "a single-scene platform is asked to show it")344        #expect(probe.events == ["windowOpened:ephemeral", "profile:ghost", "engineCreated:true", "tabSelected:first"])345        let tab = try #require(ghost.selectedTab)346        #expect(tab.engine.profile.isGhost && tab.engine.profile !== normal.selectedTab?.engine.profile)347        #expect(tab.engine.settings.mirrorsConsole, "configureSettings saw the ephemeral window")348        #expect(registry.badges(for: ghost).map(\.label) == ["Private"] && registry.badges(for: normal).isEmpty)349350        // Browse, open and close tabs, pin, zoom, answer a permission prompt "always", then close the window.351        ghost.navigate(to: fixture.url("two"))352        try await waitForTitle(tab, "Page two")353        try await waitUntil("private page announced") { probe.finishes.contains { $0.isEphemeral } }354        #expect(probe.finishes.last?.isGhost == true)355        let second = ghost.newTab(url: fixture.url("three"))356        try await waitForTitle(second, "Page three")357        ghost.setPinned(true, for: second.id)358        ghost.zoomIn()359        ghost.toggleMute(second.id)360        _ = ghost.duplicate(second.id)361        ghost.close(second.id)362        ghost.tabLayout = .horizontal363        ghost.isSidebarCollapsed = true364        #expect(store.closedTabCount == 0, "a private tab is never 'recently closed'")365        #expect(!(await registry.run(ShellCommandID.reopenClosedTab, in: ghost.commandContext())))366        let request = PermissionRequest(kinds: [.camera], origin: WebOrigin(scheme: "https", host: "example.com"), requestingOrigin: nil, isMainFrame: true)367        async let answer = ghost.prompts.webEngine(tab.engine, decide: request)368        try await waitUntil("prompt queued") { ghost.prompts.queue.count == 1 }369        ghost.answerPermission(ghost.prompts.queue[0], allow: true, duration: .always)370        #expect(await answer == PermissionPromptResponse(allow: true, remember: false))371        #expect(await permissions.verdict(for: .camera, origin: request.origin, profileID: ghost.profile.id) == .allow)372373        // Tabs do not cross between a private window and a normal one, and are not suggested across.374        #expect(!store.canMoveTab(tab.id, to: normal))375        store.moveTab(tab.id, to: normal)376        #expect(ghost.tabs.contains { $0.id == tab.id })377        let suggestions = await store.suggestions(for: "Page", in: normal)378        #expect(!suggestions.contains { if case .openTab = $0.kind { true } else { false } })379        let privateSuggestions = await store.suggestions(for: "three", in: normal)380        #expect(privateSuggestions.allSatisfy { $0.url != fixture.url("three") })381382        store.captureSessionState()383        await store.session.flush()384        await settle(milliseconds: 400)385        store.closeWindow(ghost.id)386        #expect(probe.events.last == "windowClosed:ephemeral")387        #expect(!store.profiles.hasOpenGhostSession(for: ghost.profile.id))388        await store.session.flush()389        await settle()390391        let after = try await tableCounts(database)392        #expect(after == before, "an ephemeral window wrote rows: \(after.filter { before[$0.key] != $0.value })")393        #expect(try await database.history.visits(profile: ghost.profile.id, limit: 10).isEmpty)394        #expect(try await database.session.restore().tabCount == 1)395        #expect(await permissions.verdict(for: .camera, origin: request.origin, profileID: ghost.profile.id) == .ask,396                "the private session's answers are gone")397        let filesAfter = (try? FileManager.default.subpathsOfDirectory(atPath: icons.url.path)) ?? []398        #expect(filesAfter == filesBefore, "no icon of a private page on disk")399        #expect(!filesAfter.contains { $0.contains(ghost.profile.id.string) })400401        // The next launch knows nothing of it.402        await store.shutDown()403        await database.close()404        let (relaunched, reopened) = try await fixture.open(registry: FeatureRegistry())405        #expect(relaunched.windows.count == 1 && relaunched.windows[0].tabs.count == 1 && !relaunched.windows[0].isEphemeral)406        await relaunched.shutDown()407        await reopened.close()408    }409410    @Test func windowsOfAnotherSpaceAreRestoredWithTheirProfile() async throws {411        let fixture = try await StoreFixture()412        defer { fixture.finish() }413        let (store, database) = try await fixture.open(registry: FeatureRegistry())414        let work = try await store.services.orbit.createProfile(name: "Work", tint: .solar)415        let window = store.openWindow(in: work.space, profile: work.profile)416        #expect(!window.isEphemeral && window.profile.id == work.profile.id)417        window.navigate(to: fixture.url("four"))418        try await waitForTitle(try #require(window.selectedTab), "Page four")419        #expect(window.selectedTab?.engine.profile.profile.id == work.profile.id)420        #expect(window.selectedTab?.engine.profile !== store.claimWindow().selectedTab?.engine.profile)421        try await waitUntilAsync("visit recorded for the work profile") {422            (try? await database.history.visits(profile: work.profile.id, limit: 10).count) == 1423        }424        #expect(try await database.history.visits(profile: store.profile.id, limit: 10).isEmpty)425        await store.shutDown()426        await database.close()427428        let (relaunched, reopened) = try await fixture.open(registry: FeatureRegistry())429        #expect(relaunched.windows.count == 2)430        let restored = try #require(relaunched.windows.first { $0.space.id == work.space.id })431        #expect(restored.profile.id == work.profile.id && restored.tabs.first?.engine.url == fixture.url("four"))432        await relaunched.shutDown()433        await reopened.close()434    }435436    @Test func permissionAnswersLastAsLongAsChosen() async throws {437        let fixture = try await StoreFixture()438        defer { fixture.finish() }439        let database = try await NavigatorDatabase(url: fixture.directory.url.appending(path: "Navigator.sqlite"))440        let permissions = PermissionService(database: database)441        let (store, _) = try await fixture.open(registry: FeatureRegistry(), permissions: permissions, database: database)442        let window = store.claimWindow()443        let tab = try #require(window.selectedTab)444        let profile = store.profile.id445446        func ask(_ kind: PermissionKind, host: String, allow: Bool, _ duration: PermissionDuration) async throws -> WebOrigin {447            let origin = WebOrigin(scheme: "https", host: host)448            let request = PermissionRequest(kinds: [kind], origin: origin, requestingOrigin: nil, isMainFrame: true)449            async let answer = window.prompts.webEngine(tab.engine, decide: request)450            try await waitUntil("prompt queued") { window.prompts.queue.count == 1 }451            window.answerPermission(window.prompts.queue[0], allow: allow, duration: duration)452            #expect(await answer == PermissionPromptResponse(allow: allow, remember: false))453            return origin454        }455456        let once = try await ask(.camera, host: "once.example", allow: true, .once)457        #expect(await permissions.verdict(for: .camera, origin: once, profileID: profile) == .ask)458        #expect(try await database.permissions.decisions(profile: profile, origin: once).isEmpty)459460        let session = try await ask(.microphone, host: "session.example", allow: true, .session)461        #expect(await permissions.verdict(for: .microphone, origin: session, profileID: profile) == .allow)462        #expect(try await database.permissions.decisions(profile: profile, origin: session).isEmpty, "a session answer is never stored")463        #expect(await permissions.sitePermissions(origin: session, profile: profile).first { $0.kind == .microphone }?.source == .session)464465        let day = try await ask(.location, host: "day.example", allow: true, .day)466        let stored = try #require(try await database.permissions.decisions(profile: profile, origin: day).first)467        let expiry = try #require(stored.expiresAt)468        #expect(abs(expiry.timeIntervalSinceNow - 86_400) < 60 && stored.verdict == .allow)469470        let always = try await ask(.camera, host: "always.example", allow: true, .always)471        let kept = try #require(try await database.permissions.decisions(profile: profile, origin: always).first)472        #expect(kept.expiresAt == nil && kept.verdict == .allow)473474        let denied = try await ask(.camera, host: "denied.example", allow: false, .once)475        #expect(await permissions.verdict(for: .camera, origin: denied, profileID: profile) == .ask, "“Don’t Allow” is for this request only")476477        await permissions.endSession()478        #expect(await permissions.verdict(for: .microphone, origin: session, profileID: profile) == .ask)479        #expect(await permissions.verdict(for: .location, origin: day, profileID: profile) == .allow)480        await store.shutDown()481        await database.close()482    }483484    @Test func aSettingsChangeReachesOpenTabs() async throws {485        let fixture = try await StoreFixture()486        defer { fixture.finish() }487        let (store, database) = try await fixture.open(registry: FeatureRegistry())488        let window = store.claimWindow()489        let tab = try #require(window.selectedTab)490        window.navigate(to: fixture.url("one"))491        try await waitForTitle(tab, "Page one")492        #expect(!tab.engine.settings.navigation.httpsOnly)493        store.settings.httpsOnly = true494        try await waitUntil("HTTPS-only applied to the open tab") { tab.engine.settings.navigation.httpsOnly }495        #expect(window.newTab().engine.settings.navigation.httpsOnly)496        store.settings.httpsOnly = false497        try await waitUntil("HTTPS-only removed from the open tab") { !tab.engine.settings.navigation.httpsOnly }498        await store.shutDown()499        await database.close()500    }501502    @Test func aRestartedDownloadKeepsItsEntry() async throws {503        let fixture = try await StoreFixture()504        defer { fixture.finish() }505        let folder = try TemporaryDirectory(prefix: "orix-dl")506        defer { folder.remove() }507        fixture.server.route("/file") { _ in508            FixtureResponse(headers: [("Content-Type", "application/octet-stream"), ("Content-Disposition", "attachment; filename=\"data.bin\"")],509                            body: Data(repeating: 7, count: 2_048))510        }511        let database = try await NavigatorDatabase(url: fixture.directory.url.appending(path: "Navigator.sqlite"))512        let manager = DownloadManager(database: database, defaultDirectory: folder.url)513        let (store, _) = try await fixture.open(registry: FeatureRegistry(), downloads: manager, database: database)514        let center = try #require(store.downloads)515        let window = store.claimWindow()516        let tab = try #require(window.selectedTab)517        window.navigate(to: fixture.url("one"))518        try await waitForTitle(tab, "Page one")519520        await tab.engine.startDownload(fixture.server.url("/file"))521        try await waitUntil("first transfer finished", timeout: 20) { center.items.first?.download.state == .finished }522        let item = try #require(center.items.first)523        #expect(center.items.count == 1 && fixture.server.requests(path: "/file").count == 1)524525        center.downloadAgain(item)526        try await waitUntil("second transfer requested", timeout: 20) { fixture.server.requests(path: "/file").count == 2 }527        try await waitUntil("second transfer finished", timeout: 20) { center.items.first?.download.state == .finished }528        #expect(center.items.count == 1, "the same entry, not a new one")529        #expect(center.items.first?.id == item.id)530        #expect(try await database.downloads.downloads(profile: store.profile.id).count == 1)531        await store.shutDown()532        await database.close()533    }534}535536@Suite("Site icons", .serialized)537@MainActor538struct FaviconTests {539    /// A solid square, as PNG.540    static func png(size: Int = 8, alpha: CGFloat = 1) -> Data {541        let context = CGContext(data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: size * 4,542                                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!543        context.setFillColor(CGColor(red: 0.2 * alpha, green: 0.4 * alpha, blue: 0.9 * alpha, alpha: alpha))544        context.fill(CGRect(x: 0, y: 0, width: size, height: size))545        let data = NSMutableData()546        let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)!547        CGImageDestinationAddImage(destination, context.makeImage()!, nil)548        CGImageDestinationFinalize(destination)549        return data as Data550    }551552    /// An `.ico` whose first entry is an empty (fully transparent) image and whose second is a visible one.553    static func ico(entries: [Data]) -> Data {554        var data = Data([0, 0, 1, 0, UInt8(entries.count), 0])555        var offset = 6 + 16 * entries.count556        for entry in entries {557            data.append(contentsOf: [0, 0, 0, 0, 1, 0, 32, 0])558            withUnsafeBytes(of: UInt32(entry.count).littleEndian) { data.append(contentsOf: $0) }559            withUnsafeBytes(of: UInt32(offset).littleEndian) { data.append(contentsOf: $0) }560            offset += entry.count561        }562        for entry in entries { data.append(entry) }563        return data564    }565566    @Test func iconsAreRecognisedByTheirBytes() {567        #expect(FaviconDecoder.sniff(Self.png()) == .png)568        #expect(FaviconDecoder.sniff(Self.ico(entries: [Self.png()])) == .ico)569        #expect(FaviconDecoder.sniff(Data("<!doctype html><title>404</title>".utf8)) == nil)570        #expect(FaviconDecoder.sniff(Data("<svg xmlns='http://www.w3.org/2000/svg'/>".utf8)) == nil)571        #expect(FaviconDecoder.normalizedPNG(from: Data("<html>not an icon</html>".utf8)) == nil)572        #expect(FaviconDecoder.normalizedPNG(from: Data()) == nil)573        #expect(FaviconDecoder.normalizedPNG(from: Data(repeating: 0x89, count: FaviconDecoder.maximumBytes + 1)) == nil)574575        #expect(FaviconDecoder.normalizedPNG(from: Self.png(size: 32)).flatMap(PlatformImage.init(data:)) != nil)576        // A large icon is scaled down before it is kept.577        let large = FaviconDecoder.normalizedPNG(from: Self.png(size: 512)).flatMap { CGImageSourceCreateWithData($0 as CFData, nil) }578            .flatMap { CGImageSourceCreateImageAtIndex($0, 0, nil) }579        #expect(large?.width == FaviconDecoder.maximumPixelSize)580    }581582    @Test func aBlankIconFallsBackToTheMonogram() {583        // Fully transparent: nothing to show.584        #expect(FaviconDecoder.normalizedPNG(from: Self.png(alpha: 0)) == nil)585        #expect(FaviconDecoder.normalizedPNG(from: Self.ico(entries: [Self.png(alpha: 0)])) == nil)586        // An .ico with a blank small entry and a real larger one: the real one is chosen.587        let mixed = Self.ico(entries: [Self.png(size: 16, alpha: 0), Self.png(size: 48)])588        let chosen = FaviconDecoder.normalizedPNG(from: mixed).flatMap { CGImageSourceCreateWithData($0 as CFData, nil) }589            .flatMap { CGImageSourceCreateImageAtIndex($0, 0, nil) }590        #expect(chosen?.width == 48)591    }592593    @Test func rowsNeverFetchAndVisitedPagesAreCached() async throws {594        let fixture = try await StoreFixture()595        defer { fixture.finish() }596        let icons = try TemporaryDirectory(prefix: "orix-icons")597        defer { icons.remove() }598        let icon = Self.png(size: 32)599        fixture.server.route("/icon.png") { _ in FixtureResponse(headers: [("Content-Type", "image/png")], body: icon) }600        fixture.server.route("/fake.ico") { _ in FixtureResponse(headers: [("Content-Type", "image/x-icon")], body: Data("<html>nope</html>".utf8)) }601        fixture.server.route("/with-icon") { _ in .html("<!doctype html><title>Icon page</title><link rel='icon' href='/icon.png'>") }602        let (store, database) = try await fixture.open(registry: FeatureRegistry(), faviconDirectory: icons.url)603        let profile = store.profile.id604        let page = fixture.server.url("/with-icon")605606        // Rows of history, bookmarks and favourites only read the cache: no request, whatever the address.607        #expect(store.favicons.image(forPage: page, profile: profile) == nil)608        #expect(store.favicons.image(forPage: URL(string: "https://never-visited.example/a"), profile: profile) == nil)609        #expect(store.favicons.image(forPage: URL(string: "file:///etc/hosts"), profile: profile) == nil)610        await settle(milliseconds: 300)611        #expect(await store.favicons.loader.requestCount == 0)612        #expect(fixture.server.requests.isEmpty)613614        // Loading the page in a tab fetches the icon it declares, without cookies, and caches it.615        let window = store.claimWindow()616        let tab = try #require(window.selectedTab)617        window.navigate(to: page)618        try await waitForTitle(tab, "Icon page")619        try await waitUntil("icon cached", timeout: 15) { store.favicons.image(forPage: page, profile: profile) != nil }620        let request = try #require(fixture.server.requests(path: "/icon.png").last)621        #expect(request.header("cookie") == nil)622        let files = try FileManager.default.subpathsOfDirectory(atPath: icons.url.appending(path: profile.string).path)623        #expect(files.count == 1 && files[0].hasSuffix(".png"))624        // Any page of the same site shows it; another profile does not.625        #expect(store.favicons.image(forPage: fixture.server.url("/one"), profile: profile) != nil)626        #expect(store.favicons.image(forPage: page, profile: ProfileID()) == nil)627628        // A fresh store reads the icon from disk, still without a request.629        let reread = FaviconStore(directory: icons.url)630        #expect(reread.image(forPage: page, profile: profile) == nil)631        try await waitUntil("icon read from disk") { reread.image(forPage: page, profile: profile) != nil }632        #expect(await reread.loader.requestCount == 0)633634        // Something that is not an image is refused and not asked for again.635        let other = FaviconStore(directory: icons.url)636        let fake = fixture.server.url("/fake.ico", host: "localhost")637        other.pageDidLoad(fixture.server.url("/one", host: "localhost"), icon: fake, profile: profile, isEphemeral: false)638        try await waitUntilAsync("fake icon requested") { await other.loader.requestCount == 1 }639        await settle()640        #expect(other.image(forPage: fixture.server.url("/one", host: "localhost"), profile: profile) == nil)641642        // A private page: shown from memory, never written.643        let ghost = ProfileID()644        other.pageDidLoad(page, icon: fixture.server.url("/icon.png"), profile: ghost, isEphemeral: true)645        try await waitUntil("private icon in memory") { other.image(forPage: page, profile: ghost) != nil }646        #expect(!FileManager.default.fileExists(atPath: icons.url.appending(path: ghost.string).path))647        other.forgetEphemeral(profile: ghost)648        #expect(other.image(forPage: page, profile: ghost) == nil)649650        // Clearing browsing data removes the cache.651        await store.favicons.removeAll(profile: profile)652        #expect(!FileManager.default.fileExists(atPath: icons.url.appending(path: profile.string).path))653        #expect(store.favicons.image(forPage: page, profile: profile) == nil)654        await store.shutDown()655        await database.close()656    }657}658
Files main
Menu

Theme