Repository Public
1import WebKit2import XCTest3@testable import SPBrowser45/// Integration tests that run inside the real application process with real WKWebViews.6/// Pages are served with `loadHTMLString(_:baseURL:)`, so no network or local server is needed.7@MainActor8final class EngineIntegrationTests: XCTestCase {9 private var root: URL!10 private var environment: AppEnvironment!11 private var state: BrowserWindowState!1213 override func setUp() async throws {14 root = FileManager.default.temporaryDirectory.appendingPathComponent("spb-app-tests-" + UUID().uuidString, isDirectory: true)15 environment = AppEnvironment(root: root, secrets: InMemorySecretStore())16 state = BrowserWindowState(environment: environment, profile: environment.defaultContext)17 }1819 override func tearDown() async throws {20 state.teardown()21 state = nil22 await environment.removeAllWebsiteDataStores()23 environment = nil24 try? FileManager.default.removeItem(at: root)25 }2627 // MARK: Helpers2829 private func waitUntil(_ timeout: TimeInterval = 15, _ condition: () -> Bool) async -> Bool {30 let deadline = Date().addingTimeInterval(timeout)31 while Date() < deadline {32 if condition() { return true }33 try? await Task.sleep(for: .milliseconds(40))34 }35 return condition()36 }3738 @discardableResult39 private func load(_ html: String, at address: String, in tab: BrowserTab, expectTitle: String? = nil) async -> Bool {40 let webView = tab.ensureWebView()41 webView.loadHTMLString(html, baseURL: URL(string: address))42 return await waitUntil { !tab.isLoading && tab.url?.absoluteString == address && (expectTitle == nil || tab.title == expectTitle) }43 }4445 private func page(_ title: String, body: String = "<p>Hello</p>", script: String = "") -> String {46 "<!doctype html><html lang='en'><head><meta charset='utf-8'><title>\(title)</title><meta name='description' content='A test page'></head><body>\(body)<script>\(script)</script></body></html>"47 }4849 // MARK: Navigation and history5051 func testLoadUpdatesStateAndRecordsHistory() async {52 let tab = state.newTab()53 let loaded = await load(page("First Page"), at: "https://test.example/first", in: tab, expectTitle: "First Page")54 XCTAssertTrue(loaded)55 XCTAssertEqual(tab.displayTitle, "First Page")56 XCTAssertEqual(tab.security, .secure)57 XCTAssertFalse(tab.isBlank)58 let recorded = await waitUntil { self.state.profile.history.recent().first?.title == "First Page" }59 XCTAssertTrue(recorded, "the visit and its final title are stored")60 XCTAssertEqual(state.profile.history.recent().first?.url, "https://test.example/first")61 XCTAssertEqual(state.profile.history.count, 1)62 }6364 func testInsecurePageIsFlagged() async {65 let tab = state.newTab()66 await load(page("Plain"), at: "http://plain.example/", in: tab, expectTitle: "Plain")67 XCTAssertEqual(tab.security, .insecure)68 XCTAssertTrue(tab.warnings.contains(.insecureTransport))69 await load(page("Local"), at: "http://localhost:3000/", in: tab, expectTitle: "Local")70 XCTAssertEqual(tab.security, .local)71 }7273 func testScriptAndDataNavigationsAreBlocked() async {74 let tab = state.newTab()75 await load(page("Safe"), at: "https://test.example/", in: tab, expectTitle: "Safe")76 tab.webView?.evaluateJavaScript("location.href = 'data:text/html,<title>Evil</title>'", completionHandler: nil)77 let noticed = await waitUntil(5) { tab.notice != nil }78 XCTAssertTrue(noticed, "a top-level data: navigation is blocked and reported")79 XCTAssertEqual(tab.title, "Safe")80 XCTAssertEqual(tab.url?.absoluteString, "https://test.example/")8182 tab.notice = nil83 tab.webView?.evaluateJavaScript("location.href = 'file:///etc/hosts'", completionHandler: nil)84 _ = await waitUntil(3) { tab.notice != nil }85 XCTAssertEqual(tab.url?.absoluteString, "https://test.example/", "web content cannot navigate to local files")86 }8788 func testJavaScriptCanBeDisabledPerSite() async {89 state.profile.permissions.set(.deny, for: .javascript, host: "noscript.example")90 let tab = state.newTab()91 tab.load(URL(string: "about:blank")!)92 _ = await waitUntil { !tab.isLoading }93 // A real navigation is needed for per-site preferences to be applied by the policy delegate.94 let html = page("Static", script: "document.title = 'Scripted'")95 tab.webView?.loadSimulatedRequest(URLRequest(url: URL(string: "https://noscript.example/")!), responseHTML: html)96 _ = await waitUntil { !tab.isLoading && tab.title == "Static" }97 try? await Task.sleep(for: .milliseconds(300))98 XCTAssertEqual(tab.title, "Static", "the page script did not run")99100 let other = state.newTab()101 other.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://scripted.example/")!), responseHTML: html)102 let ran = await waitUntil { other.title == "Scripted" }103 XCTAssertTrue(ran, "other sites keep JavaScript")104 }105106 func testPopupsNeedPermission() async {107 let html = page("Opener", script: "window.open('https://popup.example/', '_blank')")108 let tab = state.newTab()109 tab.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://opener.example/")!), responseHTML: html)110 _ = await waitUntil { !tab.isLoading && tab.title == "Opener" }111 try? await Task.sleep(for: .milliseconds(500))112 XCTAssertEqual(state.tabs.count, 1, "a window opened without a click is blocked by default")113114 state.profile.permissions.set(.allow, for: .popups, host: "opener.example")115 tab.webView?.loadSimulatedRequest(URLRequest(url: URL(string: "https://opener.example/again")!), responseHTML: html)116 let opened = await waitUntil(8) { self.state.tabs.count == 2 }117 XCTAssertTrue(opened, "once allowed for the site, the pop-up opens as a tab")118 }119120 func testFailedLoadShowsErrorAndRetryClearsIt() async {121 let tab = state.newTab()122 tab.load(URL(string: "https://this-host-does-not-exist.invalid/")!)123 let failed = await waitUntil(30) { tab.error != nil }124 XCTAssertTrue(failed)125 XCTAssertNotNil(tab.error?.title)126 XCTAssertEqual(tab.url?.host, "this-host-does-not-exist.invalid", "the address bar keeps the address that failed")127 XCTAssertEqual(state.profile.history.count, 0, "failed loads are not recorded")128 }129130 func testCrashRecovery() async {131 let tab = state.newTab()132 await load(page("Stable"), at: "https://test.example/", in: tab, expectTitle: "Stable")133 tab.processTerminated()134 XCTAssertTrue(tab.crashed)135 XCTAssertEqual(tab.url?.absoluteString, "https://test.example/", "the address survives the crash")136 tab.reload()137 XCTAssertFalse(tab.crashed)138 }139140 func testMicrophoneRequestAsksThenRemembersDenial() async {141 let script = "navigator.mediaDevices.getUserMedia({ audio: true }).then(function () { document.title = 'granted'; }).catch(function (e) { document.title = 'refused:' + e.name; });"142 let tab = state.newTab()143 // Media capture is only offered to pages that are actually on screen.144 let window = NSWindow(contentRect: NSRect(x: 40, y: 40, width: 480, height: 320), styleMask: [.titled], backing: .buffered, defer: false)145 window.isReleasedWhenClosed = false146 window.contentView = tab.ensureWebView()147 window.makeKeyAndOrderFront(nil)148 defer { window.contentView = nil; window.close() }149 tab.webView?.loadSimulatedRequest(URLRequest(url: URL(string: "https://call.example/")!), responseHTML: page("Call", script: script))150 let asked = await waitUntil(10) { tab.permissionPrompt != nil || tab.title.hasPrefix("refused") }151 guard asked, let prompt = tab.permissionPrompt else {152 // No capture device (or no on-screen session) is available to this process: WebKit did not ask. Nothing was granted.153 XCTAssertNotEqual(tab.title, "granted")154 print("NOTE: media capture prompt could not be exercised in this environment (title=\(tab.title))")155 return156 }157 XCTAssertEqual(prompt.host, "call.example")158 XCTAssertEqual(prompt.permissions, [.microphone])159 XCTAssertNotEqual(tab.title, "granted", "nothing is granted before the user answers")160 prompt.resolve(false, true)161 let refused = await waitUntil(10) { tab.title.hasPrefix("refused") }162 XCTAssertTrue(refused, tab.title)163 XCTAssertNil(tab.permissionPrompt)164 XCTAssertEqual(state.profile.permissions.storedDecision(.microphone, host: "call.example"), .deny, "“remember” stores the refusal")165 XCTAssertNil(state.profile.permissions.storedDecision(.camera, host: "call.example"))166 print("NOTE: media capture prompt exercised end to end")167 }168169 // MARK: Page features170171 func testFindReaderAndMetadata() async {172 let paragraphs = (0..<12).map { "<p>Paragraph \($0) of a reasonably long article about navigation, with enough words to count as readable text for the reader.</p>" }.joined()173 let html = page("Article", body: "<nav>menu</nav><article><h1>Heading</h1>\(paragraphs)<a href='https://other.example/x' rel='nofollow'>Out</a></article>")174 let tab = state.newTab()175 await load(html, at: "https://news.example/story", in: tab, expectTitle: "Article")176177 let found = await tab.find("Paragraph 7")178 let missing = await tab.find("zebra-not-here")179 XCTAssertTrue(found)180 XCTAssertFalse(missing)181182 let metadata = await tab.pageMetadata()183 XCTAssertEqual(metadata?.title, "Article")184 XCTAssertEqual(metadata?.description, "A test page")185 XCTAssertEqual(metadata?.lang, "en")186 XCTAssertEqual(metadata?.links.first?.href, "https://other.example/x")187 XCTAssertEqual(metadata?.links.first?.external, true)188189 let readable = await tab.toggleReader()190 XCTAssertTrue(readable)191 XCTAssertEqual(tab.readerArticle?.blocks.first?.text, "Heading")192 XCTAssertFalse(tab.readerArticle?.blocks.contains { $0.text == "menu" } ?? true, "navigation chrome is left out")193194 let short = state.newTab()195 await load(page("Short"), at: "https://news.example/short", in: short, expectTitle: "Short")196 let shortReadable = await short.toggleReader()197 XCTAssertFalse(shortReadable, "reader view is not offered for pages without an article")198199 let text = await tab.pageText()200 XCTAssertTrue(text.contains("Paragraph 3"))201 }202203 func testZoomIsRememberedPerSite() async {204 let tab = state.newTab()205 await load(page("Zoom"), at: "https://zoom.example/", in: tab, expectTitle: "Zoom")206 tab.setZoom(1.5)207 XCTAssertEqual(state.profile.permissions.zoom(forHost: "zoom.example"), 1.5)208 tab.setZoom(99)209 XCTAssertEqual(tab.zoom, 5.0, accuracy: 0.001, "zoom is clamped")210 }211212 func testUserScriptsRunOnlyOnDeclaredSitesAndOnlyWhenEnabled() async {213 environment.userScripts = [UserScript(name: "t", source: "document.title = 'Modified';", hosts: ["scripts.example"], enabled: true)]214 let html = page("Original")215216 let off = state.newTab()217 off.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://scripts.example/")!), responseHTML: html)218 _ = await waitUntil { !off.isLoading && off.title == "Original" }219 try? await Task.sleep(for: .milliseconds(300))220 XCTAssertEqual(off.title, "Original", "user scripts are off until the global switch is turned on")221222 environment.settings.userScriptsEnabled = true223 let on = state.newTab()224 on.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://scripts.example/")!), responseHTML: html)225 let modified = await waitUntil { on.title == "Modified" }226 XCTAssertTrue(modified)227228 let elsewhere = state.newTab()229 elsewhere.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://elsewhere.example/")!), responseHTML: html)230 _ = await waitUntil { !elsewhere.isLoading && elsewhere.title == "Original" }231 try? await Task.sleep(for: .milliseconds(300))232 XCTAssertEqual(elsewhere.title, "Original", "the script does not run on other sites")233 }234235 // MARK: Content blocker236237 func testBlockerRulesCompileInWebKit() async {238 await environment.blocker.refresh(settings: environment.settings, lists: environment.blockLists)239 XCTAssertNil(environment.blocker.lastError)240 XCTAssertNotNil(environment.blocker.ruleList, "WebKit accepted the generated rule list")241 XCTAssertGreaterThan(environment.blocker.ruleCount, 100)242243 var settings = environment.settings244 settings.blockerDisabledHosts = ["example.com"]245 await environment.blocker.refresh(settings: settings, lists: BlockListState(sources: [BlockListSource(name: "x", url: "https://l.example/x")],246 domainsBySource: [:]))247 XCTAssertNil(environment.blocker.lastError, "the per-site exception rule is valid too")248249 settings.contentBlockerEnabled = false250 await environment.blocker.refresh(settings: settings, lists: BlockListState())251 XCTAssertNil(environment.blocker.ruleList)252 }253254 func testBlockerBlocksThirdPartyTrackerRequests() async {255 await environment.blocker.refresh(settings: environment.settings, lists: environment.blockLists)256 // The image points at a listed tracker host; with the blocker the request fails immediately (onerror),257 // without it the request would hang or resolve through the network.258 let script = "var i = new Image(); i.onerror = function () { document.title = 'blocked'; }; i.onload = function () { document.title = 'loaded'; }; i.src = 'https://www.google-analytics.com/collect?v=1';"259 let tab = state.newTab()260 tab.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://shop.example/")!), responseHTML: page("Shop", script: script))261 let blocked = await waitUntil(8) { tab.title == "blocked" }262 XCTAssertTrue(blocked, "the third-party tracker request was refused by the content rule list")263 }264265 // MARK: Downloads266267 func testDownloadIsSavedUnderASafeUniqueName() async throws {268 let directory = root.appendingPathComponent("Downloads", isDirectory: true)269 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)270 try Data("existing".utf8).write(to: directory.appendingPathComponent("report.txt"))271 environment.downloads.destinationDirectory = { directory }272273 let html = page("DL", body: "<a id='a' download='report.txt' href='data:text/plain;charset=utf-8,hello%20world'>get</a>", script: "document.getElementById('a').click()")274 let tab = state.newTab()275 tab.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://files.example/")!), responseHTML: html)276 let finished = await waitUntil(15) { self.environment.downloads.items.first?.state == .finished }277 XCTAssertTrue(finished, "state: \(String(describing: environment.downloads.items.first?.state))")278 let item = try XCTUnwrap(environment.downloads.items.first)279 let destination = try XCTUnwrap(item.destination)280 XCTAssertEqual(destination.deletingLastPathComponent().standardizedFileURL.path, directory.standardizedFileURL.path, "the file cannot escape the download folder")281 XCTAssertEqual(destination.lastPathComponent, "report (2).txt", "an existing file is never overwritten")282 XCTAssertEqual(try String(contentsOf: destination, encoding: .utf8), "hello world")283 XCTAssertEqual(try String(contentsOf: directory.appendingPathComponent("report.txt"), encoding: .utf8), "existing")284 XCTAssertEqual(tab.title, "DL", "the page itself did not navigate away")285286 environment.downloads.remove(item)287 XCTAssertTrue(environment.downloads.items.isEmpty)288 }289290 func testCancelledDownloadLeavesNoFile() async throws {291 let directory = root.appendingPathComponent("Downloads2", isDirectory: true)292 environment.downloads.destinationDirectory = { directory }293 let big = String(repeating: "x", count: 200_000)294 let html = page("DL2", body: "<a id='a' download='big.txt' href='data:text/plain,\(big)'>get</a>", script: "document.getElementById('a').click()")295 let tab = state.newTab()296 tab.ensureWebView().loadSimulatedRequest(URLRequest(url: URL(string: "https://files.example/")!), responseHTML: html)297 _ = await waitUntil(10) { !self.environment.downloads.items.isEmpty }298 let item = try XCTUnwrap(environment.downloads.items.first)299 _ = await waitUntil(10) { item.destination != nil }300 if item.state == .inProgress {301 environment.downloads.cancel(item)302 XCTAssertEqual(item.state, .cancelled)303 try? await Task.sleep(for: .milliseconds(400))304 XCTAssertEqual(item.state, .cancelled, "a late completion does not resurrect a cancelled download")305 XCTAssertFalse(item.fileExists, "a cancelled download leaves no file behind")306 } else {307 XCTAssertEqual(item.state, .finished, "the download completed before it could be cancelled (state: \(item.state))")308 }309 }310}311