Repository Public
1import XCTest2@testable import SPBrowserCore34private func tempDirectory() -> URL {5 let url = FileManager.default.temporaryDirectory.appendingPathComponent("spb-tests-" + UUID().uuidString, isDirectory: true)6 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)7 return url8}910final class SQLiteAndMigrationTests: XCTestCase {11 func testFreshDatabaseReachesCurrentSchema() throws {12 let db = try ProfileSchema.open(at: nil)13 XCTAssertEqual(db.userVersion, ProfileSchema.migrations.count)14 XCTAssertNoThrow(try db.query("SELECT tags FROM bookmarks"))15 XCTAssertNoThrow(try db.query("SELECT body FROM notes"))16 }1718 func testV1DatabaseIsMigratedWithoutDataLoss() throws {19 let dir = tempDirectory(); defer { try? FileManager.default.removeItem(at: dir) }20 let path = dir.appendingPathComponent("profile.sqlite")21 do {22 let old = try SQLiteDatabase(path: path.path)23 try old.migrate([ProfileSchema.migrations[0]])24 XCTAssertEqual(old.userVersion, 1)25 try old.execute("INSERT INTO bookmarks(id, is_folder, title, url, position, created_at) VALUES('a', 0, 'Old', 'https://old.example/', 0, 1)")26 try old.execute("INSERT INTO history(url, title, visited_at) VALUES('https://old.example/', 'Old', 5)")27 }28 let db = try ProfileSchema.open(at: path)29 XCTAssertEqual(db.userVersion, 2)30 let bookmark = try XCTUnwrap(BookmarkStore(db: db).bookmark(id: "a"))31 XCTAssertEqual(bookmark.title, "Old")32 XCTAssertEqual(bookmark.tags, [])33 XCTAssertEqual(HistoryStore(db: db).count, 1)34 }3536 func testFailedMigrationRollsBack() throws {37 let db = try SQLiteDatabase(path: nil)38 XCTAssertThrowsError(try db.migrate([["CREATE TABLE t(a)", "THIS IS NOT SQL"]]))39 XCTAssertEqual(db.userVersion, 0)40 XCTAssertThrowsError(try db.query("SELECT * FROM t"), "the partial migration must not leave its table behind")41 }4243 func testParametersAreBoundNotInterpolated() throws {44 let db = try ProfileSchema.open(at: nil)45 let history = HistoryStore(db: db)46 history.record(url: URL(string: "https://example.com/?q='%3B%20DROP%20TABLE%20history%3B--")!, title: "'; DROP TABLE history;--")47 XCTAssertEqual(history.count, 1)48 XCTAssertEqual(history.search("'; DROP").count, 1)49 }50}5152final class HistoryTests: XCTestCase {53 private var history: HistoryStore!54 override func setUpWithError() throws { history = HistoryStore(db: try ProfileSchema.open(at: nil)) }5556 func testOnlyWebPagesAreRecorded() {57 XCTAssertTrue(history.record(url: URL(string: "https://example.com/")!, title: "Example"))58 XCTAssertFalse(history.record(url: URL(string: "file:///tmp/a.html")!, title: "Local"))59 XCTAssertFalse(history.record(url: URL(string: "about:blank")!, title: ""))60 XCTAssertFalse(history.record(url: URL(string: "data:text/html,x")!, title: ""))61 XCTAssertEqual(history.count, 1)62 }6364 func testReloadsCollapseIntoOneVisit() {65 let url = URL(string: "https://example.com/")!66 let t0 = Date(timeIntervalSince1970: 1_000_000)67 history.record(url: url, title: "", at: t0)68 history.record(url: url, title: "Example", at: t0.addingTimeInterval(5))69 XCTAssertEqual(history.count, 1)70 XCTAssertEqual(history.recent().first?.title, "Example")71 history.record(url: url, title: "Example", at: t0.addingTimeInterval(120))72 XCTAssertEqual(history.count, 2)73 }7475 func testSearchSuggestionsAndTopSites() {76 let base = Date(timeIntervalSince1970: 2_000_000)77 for i in 0..<3 { history.record(url: URL(string: "https://swift.org/")!, title: "Swift", at: base.addingTimeInterval(Double(i) * 100)) }78 history.record(url: URL(string: "https://webkit.org/")!, title: "WebKit", at: base.addingTimeInterval(1000))79 history.record(url: URL(string: "https://example.com/100%25_off")!, title: "100% off", at: base.addingTimeInterval(2000))8081 XCTAssertEqual(history.search("webkit").map(\.url), ["https://webkit.org/"])82 XCTAssertEqual(history.suggestions(for: "swi").first?.visitCount, 3)83 XCTAssertEqual(history.topSites(limit: 1).first?.url, "https://swift.org/")84 XCTAssertEqual(history.search("100%").count, 1, "% is matched literally")85 XCTAssertEqual(history.search("_").count, 1, "_ is matched literally, not as a wildcard")86 XCTAssertTrue(history.suggestions(for: " ").isEmpty)87 }8889 func testDeleteByHostIncludesSubdomainsOnly() {90 for s in ["https://example.com/a", "http://example.com:8080/b", "https://www.example.com/c", "https://notexample.com/", "https://example.com.evil.test/"] {91 history.record(url: URL(string: s)!, title: s, at: Date(timeIntervalSince1970: Double(history.count) * 100 + 1))92 }93 XCTAssertEqual(history.delete(host: "example.com"), 3)94 XCTAssertEqual(Set(history.recent().map(\.url)), ["https://notexample.com/", "https://example.com.evil.test/"])95 }9697 func testClearSinceAndAll() {98 history.record(url: URL(string: "https://old.example/")!, title: "", at: Date(timeIntervalSince1970: 100))99 history.record(url: URL(string: "https://new.example/")!, title: "", at: Date(timeIntervalSince1970: 10_000))100 XCTAssertEqual(history.clear(since: Date(timeIntervalSince1970: 5_000)), 1)101 XCTAssertEqual(history.recent().map(\.url), ["https://old.example/"])102 history.clear()103 XCTAssertEqual(history.count, 0)104 }105}106107final class BookmarkTests: XCTestCase {108 private var store: BookmarkStore!109 override func setUpWithError() throws { store = BookmarkStore(db: try ProfileSchema.open(at: nil)) }110111 func testFoldersTagsAndSearch() throws {112 let folder = try XCTUnwrap(store.addFolder("Dev"))113 store.add(title: "Swift", url: "https://swift.org/", parentID: folder.id, tags: ["Lang", " lang ", "apple"])114 store.add(title: "WebKit", url: "https://webkit.org/", tags: ["engine"])115 XCTAssertEqual(store.children(of: nil).map(\.title), ["Dev", "WebKit"])116 XCTAssertEqual(store.children(of: folder.id).first?.tags, ["lang", "apple"])117 XCTAssertEqual(store.search("swift").map(\.title), ["Swift"])118 XCTAssertEqual(store.search("#engine").map(\.title), ["WebKit"])119 XCTAssertEqual(store.search("engine").map(\.title), ["WebKit"])120 XCTAssertEqual(store.allTags(), ["apple", "engine", "lang"])121 XCTAssertTrue(store.isBookmarked("https://swift.org/"))122 XCTAssertFalse(store.isBookmarked("https://swift.org"))123 }124125 func testDeletingFolderDeletesContents() throws {126 let folder = try XCTUnwrap(store.addFolder("A"))127 let sub = try XCTUnwrap(store.addFolder("B", parentID: folder.id))128 store.add(title: "x", url: "https://x.example/", parentID: sub.id)129 store.delete(id: folder.id)130 XCTAssertTrue(store.all().isEmpty)131 }132133 func testMoveReordersAndRefusesCycles() throws {134 let a = try XCTUnwrap(store.addFolder("A"))135 let b = try XCTUnwrap(store.addFolder("B", parentID: a.id))136 let x = try XCTUnwrap(store.add(title: "x", url: "https://x.example/"))137 let y = try XCTUnwrap(store.add(title: "y", url: "https://y.example/"))138 XCTAssertFalse(store.move(id: a.id, toParent: b.id), "a folder cannot move into its own descendant")139 XCTAssertFalse(store.move(id: a.id, toParent: a.id))140 XCTAssertFalse(store.move(id: x.id, toParent: y.id), "the target must be a folder")141 XCTAssertTrue(store.move(id: y.id, toParent: nil, at: 0))142 XCTAssertEqual(store.children(of: nil).map(\.title), ["y", "A", "x"])143 XCTAssertTrue(store.move(id: x.id, toParent: b.id))144 XCTAssertEqual(store.children(of: b.id).map(\.title), ["x"])145 }146147 func testNetscapeRoundTrip() throws {148 let folder = try XCTUnwrap(store.addFolder("R&D <lab>"))149 store.add(title: "A \"quoted\" & <b>title</b>", url: "https://example.com/?a=1&b=2", parentID: folder.id, tags: ["x", "y"])150 store.add(title: "Top", url: "https://top.example/")151 let html = NetscapeBookmarkCodec.export(store.tree())152 XCTAssertTrue(html.hasPrefix("<!DOCTYPE NETSCAPE-Bookmark-file-1>"))153 XCTAssertFalse(html.contains("<b>title</b>"), "titles must be escaped")154155 let parsed = NetscapeBookmarkCodec.parse(html)156 XCTAssertEqual(parsed.count, 2)157 XCTAssertEqual(parsed[0].bookmark.title, "R&D <lab>")158 XCTAssertTrue(parsed[0].bookmark.isFolder)159 XCTAssertEqual(parsed[0].children.first?.bookmark.title, "A \"quoted\" & <b>title</b>")160 XCTAssertEqual(parsed[0].children.first?.bookmark.url, "https://example.com/?a=1&b=2")161 XCTAssertEqual(parsed[0].children.first?.bookmark.tags, ["x", "y"])162 XCTAssertEqual(parsed[1].bookmark.url, "https://top.example/")163164 let other = BookmarkStore(db: try ProfileSchema.open(at: nil))165 XCTAssertEqual(other.importNodes(parsed), 2)166 XCTAssertEqual(other.tree().map(\.bookmark.title), ["R&D <lab>", "Top"])167 }168169 func testImportFromOtherBrowsersAndHostileFiles() {170 let html = """171 <!DOCTYPE NETSCAPE-Bookmark-file-1>172 <DL><p>173 <DT><H3 ADD_DATE="1700000000" PERSONAL_TOOLBAR_FOLDER="true">Bar</H3>174 <DL><p>175 <DT><A HREF="https://a.example/" ADD_DATE="1700000001" ICON="data:image/png;base64,AAAA">A</A>176 <DT><a href='https://b.example/'>b</a>177 <DT><A HREF="javascript:alert(1)">bad</A>178 <DT><A data-href="https://wrong.example/" HREF="https://right.example/">attr</A>179 <DT><H3>Nested</H3>180 <DL><p>181 <DT><A HREF="https://c.example/"></A>182 </DL><p>183 <DT><A HREF="https://after.example/">After</A>184 """185 let nodes = NetscapeBookmarkCodec.parse(html)186 XCTAssertEqual(nodes.count, 1, "unclosed lists are closed at end of file")187 let bar = nodes[0]188 XCTAssertEqual(bar.bookmark.createdAt, Date(timeIntervalSince1970: 1_700_000_000))189 // The single </DL> closes "Nested"; "After" therefore belongs to "Bar", which is closed at end of file.190 XCTAssertEqual(bar.children.map(\.bookmark.title), ["A", "b", "attr", "Nested", "After"])191 XCTAssertEqual(bar.children.compactMap(\.bookmark.url), ["https://a.example/", "https://b.example/", "https://right.example/", "https://after.example/"])192 XCTAssertEqual(bar.children[3].children.map(\.bookmark.title), ["https://c.example/"])193 XCTAssertTrue(NetscapeBookmarkCodec.parse("<<<>>> not html <A HREF=").isEmpty)194 XCTAssertTrue(NetscapeBookmarkCodec.parse("").isEmpty)195 }196}197198final class NotesTests: XCTestCase {199 func testNotesIgnoreFragmentAndEmptyDeletes() throws {200 let notes = NotesStore(db: try ProfileSchema.open(at: nil))201 let url = URL(string: "https://example.com/doc#intro")!202 notes.save("remember this", for: url)203 XCTAssertEqual(notes.note(for: URL(string: "https://example.com/doc#other")!)?.body, "remember this")204 XCTAssertNil(notes.note(for: URL(string: "https://example.com/other")!))205 notes.save(" ", for: url)206 XCTAssertNil(notes.note(for: url))207 XCTAssertTrue(notes.all().isEmpty)208 }209}210211final class SessionStoreTests: XCTestCase {212 private var dir: URL!213 override func setUp() { dir = tempDirectory() }214 override func tearDown() { try? FileManager.default.removeItem(at: dir) }215216 private func snapshot(_ urls: [String]) -> SessionSnapshot {217 SessionSnapshot(windows: [WindowSnapshot(tabs: urls.map { TabSnapshot(url: $0, title: $0) })])218 }219220 func testRoundTrip() throws {221 let store = SessionStore(directory: dir)222 XCTAssertEqual(store.load(), .empty)223 var snap = snapshot(["https://a.example/", "https://b.example/"])224 snap.windows[0].tabs[0].isPinned = true225 snap.windows[0].tabs[1].interactionState = Data([1, 2, 3])226 snap.windows[0].selectedTabID = snap.windows[0].tabs[1].id227 try store.save(snap)228 guard case .loaded(let loaded) = store.load() else { return XCTFail("expected a session") }229 XCTAssertEqual(loaded.windows, snap.windows)230 XCTAssertEqual(loaded.tabCount, 2)231 }232233 func testCorruptFileFallsBackToBackup() throws {234 let store = SessionStore(directory: dir)235 try store.save(snapshot(["https://first.example/"]))236 try store.save(snapshot(["https://second.example/"]))237 try Data("{ truncated".utf8).write(to: store.currentURL)238 guard case .recoveredFromBackup(let recovered) = store.load() else { return XCTFail("expected recovery from backup") }239 XCTAssertEqual(recovered.windows.first?.tabs.first?.url, "https://first.example/")240 XCTAssertFalse(FileManager.default.fileExists(atPath: store.currentURL.path), "the damaged file is moved aside")241 let leftovers = try FileManager.default.contentsOfDirectory(atPath: dir.path)242 XCTAssertTrue(leftovers.contains { $0.contains(".corrupt-") })243 }244245 func testFullyCorruptSessionIsQuarantinedNotFatal() throws {246 let store = SessionStore(directory: dir)247 try Data([0xFF, 0x00, 0x13]).write(to: store.currentURL)248 try Data("[]".utf8).write(to: store.backupURL)249 XCTAssertEqual(store.load(), .corrupt)250 XCTAssertEqual(store.load(), .empty, "after quarantine the next launch starts clean")251 XCTAssertNoThrow(try store.save(snapshot(["https://ok.example/"])))252 }253254 func testCorruptWriteNeverReplacesGoodBackup() throws {255 let store = SessionStore(directory: dir)256 try store.save(snapshot(["https://good.example/"]))257 try Data("garbage".utf8).write(to: store.currentURL)258 try store.save(snapshot(["https://newer.example/"]))259 // The garbage file must not have been copied over the (absent) backup as if it were valid.260 XCTAssertNil(try? JSONFile.read(SessionSnapshot.self, from: store.backupURL))261 guard case .loaded(let loaded) = store.load() else { return XCTFail() }262 XCTAssertEqual(loaded.windows.first?.tabs.first?.url, "https://newer.example/")263 }264265 func testNamedSessions() throws {266 let store = SessionStore(directory: dir)267 let saved = try store.saveNamed(" Research trip ", snapshot: snapshot(["https://a.example/", "https://b.example/"]))268 try store.saveNamed("", snapshot: snapshot([]))269 let list = store.listNamed()270 XCTAssertEqual(list.count, 2)271 let found = try XCTUnwrap(list.first { $0.fileName == saved.fileName })272 XCTAssertEqual(found.name, "Research trip")273 XCTAssertEqual(found.tabCount, 2)274 XCTAssertEqual(store.loadNamed(found)?.tabCount, 2)275 store.deleteNamed(found)276 XCTAssertEqual(store.listNamed().count, 1)277 }278}279280final class SettingsAndProfileTests: XCTestCase {281 private var dir: URL!282 override func setUp() { dir = tempDirectory() }283 override func tearDown() { try? FileManager.default.removeItem(at: dir) }284285 func testDefaultsArePrivacyFriendly() {286 let s = AppSettings()287 XCTAssertFalse(s.aiEnabled)288 XCTAssertFalse(s.userScriptsEnabled)289 XCTAssertFalse(s.diagnosticsEnabled)290 XCTAssertTrue(s.contentBlockerEnabled)291 XCTAssertTrue(s.blockPopups)292 XCTAssertTrue(s.aiProviders.isEmpty)293 XCTAssertEqual(s.activeSearchEngine().id, "spsearch")294 }295296 func testSettingsPersist() {297 let url = dir.appendingPathComponent("settings.json")298 let store = SettingsStore(url: url)299 var s = store.settings300 s.tabLayout = .vertical301 s.searchEngineID = "wikipedia"302 s.shortcutOverrides[CommandID.newTab.rawValue] = KeyCombo("y", shift: true)303 store.settings = s304 let reloaded = SettingsStore(url: url).settings305 XCTAssertEqual(reloaded, s)306 XCTAssertEqual(reloaded.activeSearchEngine().name, "Wikipedia")307 }308309 func testOlderFileKeepsDefaultsForNewFieldsAndIsMigrated() throws {310 let url = dir.appendingPathComponent("settings.json")311 let old = #"{"schemaVersion":1,"homepage":"https://home.example/","blockerDisabledHosts":["WWW.Example.com","example.com"],"startPage":{"showGreeting":false}}"#312 try Data(old.utf8).write(to: url)313 let s = SettingsStore(url: url).settings314 XCTAssertEqual(s.schemaVersion, AppSettings.currentSchema)315 XCTAssertEqual(s.homepage, "https://home.example/")316 XCTAssertEqual(s.blockerDisabledHosts, ["example.com"])317 XCTAssertFalse(s.startPage.showGreeting)318 XCTAssertTrue(s.startPage.showFavorites, "fields absent from the old file keep their default")319 XCTAssertEqual(s.suspendTabsAfterMinutes, 30)320 XCTAssertTrue(s.isBlockerDisabled(forHost: "shop.example.com"))321 XCTAssertFalse(s.isBlockerDisabled(forHost: "notexample.com"))322 }323324 func testCorruptSettingsAreSetAsideAndDefaultsUsed() throws {325 let url = dir.appendingPathComponent("settings.json")326 try Data("{{{".utf8).write(to: url)327 let store = SettingsStore(url: url)328 XCTAssertTrue(store.recoveredFromCorruption)329 XCTAssertEqual(store.settings, AppSettings())330 XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: dir.path).contains { $0.contains(".corrupt-") })331 }332333 func testUnknownEngineFallsBack() {334 var s = AppSettings()335 s.searchEngineID = "gone"336 XCTAssertEqual(s.activeSearchEngine(), SearchEngine.fallback)337 s.customSearchEngines = [SearchEngine(id: "bad", name: "Bad", template: "no placeholder", shortcut: "x")]338 XCTAssertFalse(s.allSearchEngines().contains { $0.id == "bad" })339 }340341 func testProfiles() {342 let store = ProfileStore(root: dir)343 XCTAssertEqual(store.profiles.map(\.id), [store.defaultID])344 XCTAssertNotEqual(ProfileStore(root: tempDirectory()).defaultID, store.defaultID, "each data folder gets its own default profile identifier")345 XCTAssertEqual(ProfileStore(root: dir).defaultID, store.defaultID, "and keeps it across launches")346 let work = store.create(name: " Work ", colorIndex: 2)347 XCTAssertEqual(work.name, "Work")348 XCTAssertNotEqual(store.directory(for: work), store.directory(for: store.defaultProfile))349 XCTAssertEqual(ProfileStore(root: dir).profiles.count, 2, "profiles persist")350 XCTAssertFalse(store.delete(store.defaultProfile), "the default profile cannot be deleted")351 try? FileManager.default.createDirectory(at: store.directory(for: work), withIntermediateDirectories: true)352 XCTAssertTrue(store.delete(work))353 XCTAssertFalse(FileManager.default.fileExists(atPath: store.directory(for: work).path))354 XCTAssertEqual(store.profiles.count, 1)355 }356357 func testProfileDatabasesAreIndependent() throws {358 let store = ProfileStore(root: dir)359 let work = store.create(name: "Work")360 let a = HistoryStore(db: try ProfileSchema.open(at: store.directory(for: store.defaultProfile).appendingPathComponent("profile.sqlite")))361 let b = HistoryStore(db: try ProfileSchema.open(at: store.directory(for: work).appendingPathComponent("profile.sqlite")))362 a.record(url: URL(string: "https://personal.example/")!, title: "p")363 XCTAssertEqual(a.count, 1)364 XCTAssertEqual(b.count, 0)365 }366367 func testLogRedactsURLs() {368 XCTAssertEqual(Log.redact(URL(string: "https://user:pw@example.com/secret/path?token=abc")), "https://example.com")369 XCTAssertEqual(Log.redact(nil), "<none>")370 }371}372