Repository Public License
1import Foundation2import NavigatorCore3import TestSupport4import Testing5import WebKit6@testable import WebRuntime78extension WebRuntimeTests {9 @Suite struct Loading {10 @Test func loadsPageAndPublishesState() async throws {11 try await withHarness { harness in12 let engine = harness.makeEngine()13 #expect(engine.lifecycle == .live)14 try await harness.load(engine, "/", expectingTitle: "Fixture Home")15 #expect(engine.url == harness.server.url("/"))16 #expect(engine.estimatedProgress == 1)17 #expect(!engine.canGoBack && !engine.canGoForward)18 #expect(engine.loadError == nil)19 #expect(engine.processState == .running)20 // Until the page declares an icon, the origin's /favicon.ico is the candidate.21 #expect(engine.faviconURL == harness.server.url("/favicon.ico"))22 #expect(harness.server.requests(path: "/").count == 1)23 }24 }2526 @Test func followsRedirectChain() async throws {27 try await withHarness { harness in28 let engine = harness.makeEngine()29 try await harness.load(engine, "/redirect/chain/3", expectingTitle: "Fixture final")30 #expect(engine.url == harness.server.url("/page/final"))31 for hop in ["/redirect/chain/3", "/redirect/chain/2", "/redirect/chain/1", "/page/final"] {32 #expect(harness.server.requests(path: hop).count == 1, "hop \(hop)")33 }34 // The redirecting URLs never become history entries of the tab.35 #expect(!engine.canGoBack)36 }37 }3839 @Test func redirectLoopEndsInError() async throws {40 try await withHarness { harness in41 let engine = harness.makeEngine()42 engine.load(harness.server.url("/redirect/loop"))43 try await waitUntil("redirect loop error") { engine.loadError != nil }44 #expect(engine.loadError?.kind == .tooManyRedirects)45 #expect(!engine.isLoading)46 }47 }4849 @Test func serverRedirectToPrivilegedSchemesIsBlocked() async throws {50 try await withHarness { harness in51 let engine = harness.makeEngine()52 try await harness.load(engine, "/", expectingTitle: "Fixture Home")5354 engine.load(harness.server.url("/redirect/cross-scheme?to=orix://newtab/"))55 try await waitUntil("orix redirect blocked") { engine.blockedNavigations.first?.reason == .internalPageFromWeb }56 // WebKit refuses an http → file redirect by itself, before the policy is even asked.57 engine.load(harness.server.url("/redirect/cross-scheme?to=file:///etc/hosts"))58 try await waitUntil("file redirect refused") { engine.loadError != nil }59 #expect(engine.loadError?.code == NSURLErrorNoPermissionsToReadFile)60 await settle()61 #expect(engine.title == "Fixture Home")62 #expect(await engine.string("return document.title;") == "Fixture Home")63 }64 }6566 @Test func backForwardAndList() async throws {67 try await withHarness { harness in68 let engine = harness.makeEngine()69 try await harness.load(engine, "/", expectingTitle: "Fixture Home")70 try await harness.load(engine, "/page/a", expectingTitle: "Fixture a")71 try await harness.load(engine, "/page/b", expectingTitle: "Fixture b")72 #expect(engine.canGoBack && !engine.canGoForward)7374 engine.goBack()75 try await waitUntil("back to a") { engine.title == "Fixture a" && !engine.isLoading }76 #expect(engine.canGoBack && engine.canGoForward)7778 let list = engine.backForwardList()79 #expect(list.back.map(\.offset) == [-1])80 #expect(list.back.first?.url == harness.server.url("/"))81 #expect(list.current?.title == "Fixture a")82 #expect(list.forward.map(\.url) == [harness.server.url("/page/b")])8384 engine.goForward()85 try await waitUntil("forward to b") { engine.title == "Fixture b" && !engine.isLoading }86 engine.go(toOffset: -2)87 try await waitUntil("jump to home") { engine.title == "Fixture Home" && !engine.isLoading }88 #expect(!engine.canGoBack && engine.canGoForward)89 }90 }9192 @Test func pushStateUpdatesURLTitleAndHistory() async throws {93 try await withHarness { harness in94 let engine = harness.makeEngine()95 try await harness.load(engine, "/app", expectingTitle: "App · home")96 try await engine.evaluate("document.getElementById('go-settings').click();")97 try await waitUntil("pushState reflected") { engine.url == harness.server.url("/app/settings") }98 try await waitUntil("title after pushState") { engine.title == "App · settings" }99 #expect(engine.canGoBack)100 try await waitUntilAsync("pushState visit recorded") {101 await harness.history.visits.contains { $0.url == harness.server.url("/app/settings") }102 }103 engine.goBack()104 try await waitUntil("popstate") { engine.title == "App · home" }105 // No network request was made for the pushed address.106 #expect(harness.server.requests(path: "/app/settings").isEmpty)107 }108 }109110 @Test func unicodePath() async throws {111 try await withHarness { harness in112 let engine = harness.makeEngine()113 let path = "/unicode/héllo wörld/日本語".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!114 try await harness.load(engine, path, expectingTitle: "Unicode ✓ 日本語")115 #expect(await engine.string("return document.getElementById('path').textContent;") == "/unicode/héllo wörld/日本語")116 }117 }118119 @Test func httpErrorsAndConnectionFailures() async throws {120 try await withHarness { harness in121 let engine = harness.makeEngine()122 // An HTTP error status is a page like any other.123 try await harness.load(engine, "/error/404", expectingTitle: "Not Found Fixture")124 #expect(engine.loadError == nil)125 try await harness.load(engine, "/error/500", expectingTitle: "Server Error Fixture")126127 engine.load(harness.server.url("/error/reset"))128 try await waitUntil("connection reset error") { engine.loadError != nil }129 #expect(engine.loadError?.domain == NSURLErrorDomain)130 #expect(engine.loadError?.url == harness.server.url("/error/reset"))131 // The failed address stays in the address bar so it can be corrected or retried.132 #expect(engine.url == harness.server.url("/error/reset"))133 #expect(engine.title == "Server Error Fixture")134135 // Reload retries the failed address rather than the page still displayed.136 let before = harness.server.requests(path: "/error/reset").count137 engine.reload()138 try await waitUntil("retry reached the server") { harness.server.requests(path: "/error/reset").count > before }139 }140 }141142 @Test func connectionRefused() async throws {143 try await withHarness { harness in144 let engine = harness.makeEngine()145 let port = harness.server.port146 harness.server.stop()147 try await Task.sleep(for: .milliseconds(100))148 engine.load(URL(string: "http://127.0.0.1:\(port)/")!)149 try await waitUntil("refused") { engine.loadError != nil }150 #expect(engine.loadError?.kind == .connectionFailed)151 }152 }153154 @Test func stopCancelsSlowLoadWithoutError() async throws {155 try await withHarness { harness in156 let engine = harness.makeEngine()157 try await harness.load(engine, "/", expectingTitle: "Fixture Home")158 engine.load(harness.server.url("/slow?ms=4000"))159 try await waitUntil("slow request received") { !harness.server.requests(path: "/slow").isEmpty }160 #expect(engine.isLoading)161 engine.stop()162 try await waitUntil("stopped") { !engine.isLoading }163 await settle()164 #expect(engine.loadError == nil)165 #expect(engine.title == "Fixture Home")166 }167 }168169 @Test func slowResponseEventuallyLoads() async throws {170 try await withHarness { harness in171 let engine = harness.makeEngine()172 try await harness.load(engine, "/slow?ms=400", expectingTitle: "Slow Fixture")173 try await harness.load(engine, "/slow/drip", expectingTitle: "Drip Fixture")174 }175 }176177 @Test func formsGetAndPost() async throws {178 try await withHarness { harness in179 let engine = harness.makeEngine()180 try await harness.load(engine, "/form", expectingTitle: "Form Fixture")181 try await engine.evaluate("document.getElementById('get-submit').click();")182 try await waitUntil("GET echo") { engine.title == "Echo GET" && !engine.isLoading }183 #expect(harness.server.requests(path: "/echo").last?.query == ["q": "hello world", "lang": "fr"])184185 try await harness.load(engine, "/form", expectingTitle: "Form Fixture")186 try await engine.evaluate("document.getElementById('post-submit').click();")187 try await waitUntil("POST echo") { engine.title == "Echo POST" && !engine.isLoading }188 let request = try #require(harness.server.requests(path: "/echo").last)189 #expect(request.method == "POST")190 #expect(HTTPRequestParserProbe.form(request.bodyText) == ["name": "Ada Lovelace", "note": "é ü 日本"])191 #expect(await engine.string("return document.getElementById('echo').textContent;").contains("Ada Lovelace"))192 }193 }194195 @Test func omniboxInput() async throws {196 try await withHarness { harness in197 let engine = harness.makeEngine()198 try await harness.load(engine, "/", expectingTitle: "Fixture Home")199200 // Script and opaque schemes typed in the omnibox are refused, never run.201 #expect(engine.load(input: "javascript:document.title='pwned'") == .navigationBlocked(.scriptScheme))202 #expect(engine.load(input: "data:text/html,<title>x</title>") == .navigationBlocked(.opaqueTopLevelDocument))203 #expect(engine.load(URL(string: "javascript:document.title='pwned'")!) == .navigationBlocked(.scriptScheme))204 #expect(engine.load(URL(string: "data:text/html,<title>x</title>")!) == .navigationBlocked(.opaqueTopLevelDocument))205 #expect(engine.load(URL(string: "blob:http://127.0.0.1/abc")!) == .navigationBlocked(.opaqueTopLevelDocument))206 // The omnibox does not launch other applications either.207 #expect(engine.load(URL(string: "mailto:someone@example.invalid")!) == .navigationBlocked(.externalAppUnavailable))208 await settle()209 #expect(engine.title == "Fixture Home")210 #expect(engine.blockedNavigations.count == 6)211212 // host:port is an address.213 #expect(engine.load(input: "127.0.0.1:\(harness.server.port)/page/typed") == nil)214 try await waitUntil("typed address") { engine.title == "Fixture typed" && !engine.isLoading }215216 // Anything else is a search with the chosen engine.217 let search = SearchEngine(id: "fixture", name: "Fixture", template: harness.server.url("/echo").absoluteString + "?q={query}")218 #expect(engine.load(input: "night trains & sleepers", searchEngine: search) == nil)219 try await waitUntil("search") { engine.title == "Echo GET" && !engine.isLoading }220 #expect(harness.server.requests(path: "/echo").last?.query["q"] == "night trains & sleepers")221 }222 }223224 @Test func historyIsRecordedForStandardProfilesOnly() async throws {225 try await withHarness { harness in226 let engine = harness.makeEngine()227 try await harness.load(engine, "/page/a", expectingTitle: "Fixture a")228 try await engine.evaluate("document.getElementById('next').click();")229 try await waitUntil("link followed") { engine.title == "Fixture a-next" && !engine.isLoading }230 try await waitUntilAsync("visits recorded") { await harness.history.visits.count == 2 }231 let visits = await harness.history.visits232 #expect(visits.map(\.url) == [harness.server.url("/page/a"), harness.server.url("/page/a-next")])233 #expect(visits.map(\.transition) == [.typed, .link])234 #expect(visits.allSatisfy { $0.tabID == engine.id })235 try await waitUntilAsync("title recorded") { await harness.history.titles[harness.server.url("/page/a-next")] == "Fixture a-next" }236237 let ghost = harness.makeEngine(profile: harness.makeProfile("Ghost", ghost: true))238 try await harness.load(ghost, "/page/ghost", expectingTitle: "Fixture ghost")239 await settle()240 #expect(await harness.history.visits.count == 2)241 }242 }243244 @Test func localFilesOpenOnlyWhenTheUserAsks() async throws {245 try await withHarness { harness in246 let directory = try TemporaryDirectory(prefix: "orix-files")247 defer { directory.remove() }248 let file = directory.url.appendingPathComponent("local page.html")249 try "<!doctype html><title>Local File</title><a id=\"web\" href=\"\(harness.server.url("/page/from-file"))\">web</a>"250 .write(to: file, atomically: true, encoding: .utf8)251252 let engine = harness.makeEngine()253 #expect(engine.load(file) == nil)254 try await waitUntil("local file shown") { engine.title == "Local File" && !engine.isLoading }255 #expect(engine.webView?.url?.isFileURL == true)256 // Local pages are history like any other; they may link to the web.257 try await engine.evaluate("document.getElementById('web').click();")258 try await waitUntil("link from file to web") { engine.title == "Fixture from-file" && !engine.isLoading }259 // Back to the local page the user opened is allowed (it is an existing history entry)…260 engine.goBack()261 try await waitUntil("back to file") { engine.title == "Local File" && !engine.isLoading }262263 // …and a profile configured without file access refuses even the user.264 var settings = WebEngineSettings()265 settings.navigation.allowsFileURLs = false266 let locked = harness.makeEngine(settings: settings)267 #expect(locked.load(file) == .navigationBlocked(.localFileFromWeb))268 #expect(locked.load(input: file.absoluteString) == .navigationBlocked(.localFileFromWeb))269 }270 }271272 @Test func bundledScriptsAreAllPresent() async {273 await BundledScript.preload()274 for script in BundledScript.allCases {275 #expect(script.source.count > 200, "\(script.rawValue).js is missing or empty")276 #expect(script.source.contains("ORIX Navigator"))277 }278 // Only the console mirror targets the page world.279 #expect(BundledScript.allCases.filter { $0.source.contains("World: PAGE") } == [.devConsole])280 }281282 @Test func externalSchemeGoesToDelegateAndNeverNavigates() async throws {283 try await withHarness { harness in284 let engine = harness.makeEngine()285 let spy = NavigationSpy()286 engine.navigationDelegate = spy287 engine.load(harness.server.url("/adversarial?nav=external"))288 try await waitUntil("external request") { spy.externalRequests.count == 1 }289 let request = try #require(spy.externalRequests.first)290 #expect(request.scheme == "mailto")291 #expect(request.url.absoluteString == "mailto:someone@example.invalid")292 // The page did it on its own: no trusted input preceded it.293 #expect(!request.isUserGesture)294 #expect(request.sourceURL == harness.server.url("/adversarial?nav=external"))295 #expect(engine.webView?.url == harness.server.url("/adversarial?nav=external"))296 }297 }298 }299}300301/// Access to the fixture's form parser for assertions.302enum HTTPRequestParserProbe {303 static func form(_ text: String) -> [String: String] {304 var result: [String: String] = [:]305 for pair in text.split(separator: "&") {306 let parts = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false).map {307 $0.replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? String($0)308 }309 if let key = parts.first { result[key] = parts.count > 1 ? parts[1] : "" }310 }311 return result312 }313}314