Repository Public License
1import Foundation2import NavigatorCore3import TestSupport4import Testing5import WebKit6@testable import WebRuntime78/// All WebKit tests live under this suite: they share the main run loop, so they run one at a time.9@Suite(.serialized) @MainActor struct WebRuntimeTests {}1011/// One fixture server plus the profiles and engines a test created, cleaned up in `tearDown()`.12@MainActor13final class Harness {14 let server = FixtureServer()15 let permissions = PermissionStore()16 let history = HistorySpy()17 let downloads: DownloadSpy18 let downloadDirectory: TemporaryDirectory19 private(set) var registry: WebProfileRegistry!20 private var engines: [WebEngine] = []21 private var profiles: [Profile] = []2223 init() async throws {24 downloadDirectory = try TemporaryDirectory(prefix: "orix-downloads")25 downloads = DownloadSpy(directory: downloadDirectory.url)26 let services = WebServices(permissions: permissions, history: history, downloads: downloads)27 registry = WebProfileRegistry { _ in services }28 try await server.start()29 }3031 func makeProfile(_ name: String = "Test", ghost: Bool = false) -> Profile {32 let profile = Profile(name: name, kind: ghost ? .ghost : .standard)33 profiles.append(profile)34 return profile35 }3637 func context(_ profile: Profile) -> ProfileContext { registry.context(for: profile) }3839 func makeEngine(profile: Profile? = nil, settings: WebEngineSettings = WebEngineSettings()) -> WebEngine {40 let engine = WebEngine(profile: context(profile ?? makeProfile()), settings: settings)41 engines.append(engine)42 return engine43 }4445 func adopt(_ engine: WebEngine) { engines.append(engine) }4647 /// Loads a fixture path and waits for the page to finish with the expected title.48 func load(_ engine: WebEngine, _ path: String, host: String = "127.0.0.1", expectingTitle title: String? = nil) async throws {49 engine.load(server.url(path, host: host))50 if let title {51 try await waitUntil("title “\(title)” for \(path) (now “\(engine.title)”)") { engine.title == title && !engine.isLoading }52 } else {53 try await waitFinished(engine, path)54 }55 }5657 func waitFinished(_ engine: WebEngine, _ what: String) async throws {58 try await waitUntil("start of \(what)", timeout: 5) { engine.isLoading || engine.loadError != nil || engine.estimatedProgress >= 1 }59 try await waitUntil("end of \(what)") { !engine.isLoading }60 }6162 /// Stores that could not be deleted, for the test that checks cleanup.63 private(set) var leakedStores: [UUID] = []6465 func tearDown() async {66 engines.forEach { $0.close() }67 engines.removeAll()68 server.stop()69 downloadDirectory.remove()70 // Dropping the registry drops the contexts and their WKWebsiteDataStore objects; only then does WebKit71 // let go of the stores on disk.72 registry = nil73 for profile in profiles where !profile.isGhost {74 do { try await WebProfileRegistry.deleteStore(identifier: profile.dataStoreIdentifier, patience: 8) } catch {75 leakedStores.append(profile.dataStoreIdentifier)76 Issue.record("Test data store \(profile.dataStoreIdentifier) was not deleted: \(error)")77 }78 }79 }80}8182/// Runs `body` with a fresh harness and always tears it down.83@MainActor84func withHarness(_ body: @MainActor (Harness) async throws -> Void) async throws {85 let harness = try await Harness()86 do { try await body(harness) } catch {87 await harness.tearDown()88 throw error89 }90 await harness.tearDown()91}9293// MARK: - Test doubles9495actor PermissionStore: PermissionProvider {96 private var verdicts: [String: PermissionDecision.Verdict] = [:]97 private(set) var queries: [(kind: PermissionKind, origin: WebOrigin)] = []98 private(set) var recorded: [(verdict: PermissionDecision.Verdict, kind: PermissionKind, origin: WebOrigin)] = []99100 func set(_ verdict: PermissionDecision.Verdict, _ kind: PermissionKind, _ origin: WebOrigin) {101 verdicts["\(kind.rawValue)|\(origin)"] = verdict102 }103104 func verdict(for kind: PermissionKind, origin: WebOrigin, profileID: ProfileID) async -> PermissionDecision.Verdict {105 queries.append((kind, origin))106 return verdicts["\(kind.rawValue)|\(origin)"] ?? .ask107 }108109 func record(_ verdict: PermissionDecision.Verdict, for kind: PermissionKind, origin: WebOrigin, profileID: ProfileID) async {110 recorded.append((verdict, kind, origin))111 verdicts["\(kind.rawValue)|\(origin)"] = verdict112 }113}114115actor HistorySpy: HistoryRecorder {116 private(set) var visits: [PageVisit] = []117 private(set) var titles: [URL: String] = [:]118119 func recordVisit(_ visit: PageVisit) async { visits.append(visit) }120 func updateTitle(_ title: String, for url: URL, profileID: ProfileID) async { titles[url] = title }121}122123actor DownloadSpy: DownloadSink {124 let directory: URL125 private(set) var candidates: [DownloadCandidate] = []126 private(set) var responses: [DownloadID: DownloadResponseInfo] = [:]127 private(set) var events: [DownloadID: [DownloadEvent]] = [:]128 private(set) var controls: [DownloadID: any DownloadControl] = [:]129 private(set) var destinations: [DownloadID: URL] = [:]130 private var refuseAll = false131132 init(directory: URL) { self.directory = directory }133134 func setRefuseAll(_ value: Bool) { refuseAll = value }135136 func downloadWillBegin(_ candidate: DownloadCandidate, control: any DownloadControl) async {137 candidates.append(candidate)138 controls[candidate.id] = control139 }140141 func destination(for candidate: DownloadCandidate, response: DownloadResponseInfo) async -> DownloadDestination {142 responses[candidate.id] = response143 if refuseAll { return .cancel }144 // The suggested name is untrusted: keep only its last path component.145 let name = (response.suggestedFilename as NSString).lastPathComponent146 let url = directory.appendingPathComponent("\(candidates.count)-\(name)")147 destinations[candidate.id] = url148 return .save(url)149 }150151 func download(_ id: DownloadID, didEmit event: DownloadEvent) async { events[id, default: []].append(event) }152153 func terminalEvent(_ id: DownloadID) -> DownloadEvent? {154 events[id]?.last { if case .progress = $0 { false } else { true } }155 }156157 func progressEvents(_ id: DownloadID) -> [Int64] {158 (events[id] ?? []).compactMap { if case .progress(let bytes, _) = $0 { bytes } else { nil } }159 }160161 func control(_ id: DownloadID) -> (any DownloadControl)? { controls[id] }162}163164@MainActor165final class NavigationSpy: WebEngineNavigationDelegate {166 var children: [(child: WebEngine, request: NewTabRequest)] = []167 var newTabRequests: [NewTabRequest] = []168 var externalRequests: [ExternalAppRequest] = []169 var acceptsChildren = true170 var closeRequests = 0171172 func webEngine(_ engine: WebEngine, didCreateChild child: WebEngine, for request: NewTabRequest) -> Bool {173 guard acceptsChildren else { return false }174 children.append((child, request))175 return true176 }177178 func webEngine(_ engine: WebEngine, requestsNewTab request: NewTabRequest) { newTabRequests.append(request) }179180 func webEngine(_ engine: WebEngine, requestsExternalApp request: ExternalAppRequest) async -> Bool {181 externalRequests.append(request)182 return false183 }184185 func webEngineDidRequestClose(_ engine: WebEngine) { closeRequests += 1 }186}187188@MainActor189final class UISpy: WebEngineUIDelegate {190 var dialogs: [JavaScriptDialog] = []191 var dialogResponse: @MainActor (JavaScriptDialog) -> JavaScriptDialogResponse = { _ in JavaScriptDialogResponse(accepted: true) }192 var authenticationRequests: [AuthenticationRequest] = []193 var authenticationResponse: @MainActor (AuthenticationRequest) -> AuthenticationResponse = { _ in .cancel }194 var permissionRequests: [PermissionRequest] = []195 var permissionResponse = PermissionPromptResponse.deny196197 func webEngine(_ engine: WebEngine, present dialog: JavaScriptDialog) async -> JavaScriptDialogResponse {198 dialogs.append(dialog)199 return dialogResponse(dialog)200 }201202 func webEngine(_ engine: WebEngine, credentialsFor request: AuthenticationRequest) async -> AuthenticationResponse {203 authenticationRequests.append(request)204 return authenticationResponse(request)205 }206207 func webEngine(_ engine: WebEngine, decide request: PermissionRequest) async -> PermissionPromptResponse {208 permissionRequests.append(request)209 return permissionResponse210 }211}212213extension WebEngine {214 /// Evaluates in an isolated world and returns the string result ("" when not a string).215 func string(_ body: String, in world: ScriptWorld = .agent) async -> String {216 (try? await evaluate(body, in: world))?.stringValue ?? ""217 }218}219