SPB Git

Repository Public License

BookmarkTests.swift 22.0 KB 348 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import Persistence56@Suite struct BookmarkTests {7    private func link(_ fixture: Fixture, _ title: String, _ address: String, parent: BookmarkID? = nil,8                      tags: [String] = [], favorite: Bool = false) -> Bookmark {9        Bookmark(profileID: fixture.profile.id, parentID: parent, title: title, url: url(address), tags: tags,10                 isFavorite: favorite, createdAt: day(), updatedAt: day())11    }1213    private func folder(_ fixture: Fixture, _ title: String, parent: BookmarkID? = nil) -> Bookmark {14        Bookmark(profileID: fixture.profile.id, parentID: parent, kind: .folder, title: title, createdAt: day(), updatedAt: day())15    }1617    /// Titles of a tree, indented, for readable assertions.18    private func outline(_ nodes: [BookmarkNode], depth: Int = 0) -> [String] {19        nodes.flatMap { [String(repeating: "  ", count: depth) + $0.bookmark.title] + outline($0.children, depth: depth + 1) }20    }2122    @Test func treeMoveAndReorder() async throws {23        let fixture = try await Fixture.make()24        let store = fixture.database.bookmarks25        let profile = fixture.profile.id26        let dev = try await store.append(folder(fixture, "Dev"))27        let news = try await store.append(folder(fixture, "News"))28        let swift = try await store.append(link(fixture, "Swift", "https://swift.org/", parent: dev.id))29        let rust = try await store.append(link(fixture, "Rust", "https://rust-lang.org/", parent: dev.id))30        let tools = try await store.append(folder(fixture, "Tools", parent: dev.id))31        let git = try await store.append(link(fixture, "Git", "https://git-scm.com/", parent: tools.id))32        let loose = try await store.append(link(fixture, "Loose", "https://example.com/"))33        #expect([dev, news, loose].map(\.order) == [0, 1, 2])34        #expect([swift, rust, tools].map(\.order) == [0, 1, 2])35        #expect(try await store.bookmark(git.id) == git)3637        #expect(outline(try await store.tree(profile: profile)) == ["Dev", "  Swift", "  Rust", "  Tools", "    Git", "News", "Loose"])38        #expect(try await store.children(of: dev.id, profile: profile).map(\.title) == ["Swift", "Rust", "Tools"])39        #expect(try await store.children(of: nil, profile: profile).map(\.title) == ["Dev", "News", "Loose"])4041        // Move to another folder at a position, to the top level, and to the end.42        try await store.move(rust.id, to: tools.id, index: 0)43        try await store.move(loose.id, to: dev.id, index: 1)44        try await store.move(swift.id, to: nil, index: 0)45        try await store.move(git.id, to: news.id)46        #expect(outline(try await store.tree(profile: profile)) == ["Swift", "Dev", "  Loose", "  Tools", "    Rust", "News", "  Git"])47        // Orders are dense after every move.48        #expect(try await store.children(of: nil, profile: profile).map(\.order) == [0, 1, 2])4950        try await store.reorder(parent: nil, profile: profile, [news.id, swift.id])51        #expect(try await store.children(of: nil, profile: profile).map(\.title) == ["News", "Swift", "Dev"])5253        // A folder cannot go into its own subtree, a parent must be a folder.54        await #expect(throws: PersistenceError.conflict("a folder cannot be moved into itself")) {55            try await store.move(dev.id, to: tools.id)56        }57        await #expect(throws: PersistenceError.conflict("a folder cannot be moved into itself")) {58            try await store.move(dev.id, to: dev.id)59        }60        await #expect(throws: PersistenceError.self) { try await store.move(rust.id, to: swift.id) }61        await #expect(throws: PersistenceError.self) { try await store.save(self.link(fixture, "Bad parent", "https://x.example/", parent: swift.id)) }62        await #expect(throws: PersistenceError.self) {63            try await store.save(Bookmark(profileID: profile, title: "No URL", createdAt: day(), updatedAt: day()))64        }65        var cyclic = dev66        cyclic.parentID = tools.id67        await #expect(throws: PersistenceError.self) { try await store.save(cyclic) }68        #expect(outline(try await store.tree(profile: profile)) == ["News", "  Git", "Swift", "Dev", "  Loose", "  Tools", "    Rust"])6970        // Deleting a folder deletes its whole subtree.71        #expect(try await store.delete(dev.id) == 4)72        #expect(outline(try await store.tree(profile: profile)) == ["News", "  Git", "Swift"])73        #expect(try await store.bookmark(rust.id) == nil)74    }7576    @Test func favouritesTagsAndSearch() async throws {77        let fixture = try await Fixture.make()78        let store = fixture.database.bookmarks79        let profile = fixture.profile.id80        var swift = try await store.append(link(fixture, "Swift.org", "https://swift.org/", tags: ["dev", "language", "dev"], favorite: true))81        let cafe = try await store.append(link(fixture, "Café 100% arabica", "https://cafe.example.com/menu_du_jour", tags: ["food"]))82        let rust = try await store.append(link(fixture, "Rust", "https://rust-lang.org/", tags: ["language"]))8384        // Duplicate tags collapse, order is kept.85        swift.tags = ["dev", "language"]86        #expect(try await store.bookmark(swift.id) == swift)87        #expect(try await store.favorites(profile: profile) == [swift])88        try await store.setFavorite(rust.id, true, at: day(1))89        try await store.setFavorite(swift.id, false, at: day(1))90        #expect(try await store.favorites(profile: profile).map(\.title) == ["Rust"])9192        #expect(try await store.bookmarks(taggedWith: "language", profile: profile).map(\.title) == ["Rust", "Swift.org"])93        #expect(try await store.tags(profile: profile).map { "\($0.tag):\($0.count)" } == ["dev:1", "food:1", "language:2"])94        try await store.setTags(rust.id, ["systems", "language", "Été"], at: day(2))95        #expect(try await store.bookmark(rust.id)?.tags == ["systems", "language", "Été"])96        #expect(try await store.bookmark(rust.id)?.updatedAt == day(2))97        #expect(try await store.bookmarks(taggedWith: "systems", profile: profile).map(\.title) == ["Rust"])9899        #expect(try await store.bookmarks(for: url("https://swift.org/"), profile: profile).map(\.id) == [swift.id])100        #expect(try await store.bookmarks(for: url("https://nowhere.example/"), profile: profile).isEmpty)101102        // Search is literal: %, _ and quotes in user text are not patterns.103        #expect(try await store.search("swift", profile: profile).map(\.title) == ["Swift.org"])104        #expect(try await store.search("LANG", profile: profile).map(\.title) == ["Rust", "Swift.org"])      // URL and tag, favourite first105        #expect(try await store.search("100%", profile: profile) == [cafe])106        #expect(try await store.search("menu_du", profile: profile) == [cafe])107        #expect(try await store.search("%", profile: profile) == [cafe])108        #expect(try await store.search("_", profile: profile) == [cafe])109        #expect(try await store.search("' OR '1'='1", profile: profile).isEmpty)110        #expect(try await store.search("   ", profile: profile).isEmpty)111112        // Bookmarks are per profile.113        let other = Profile(name: "Other", createdAt: day())114        try await fixture.database.profiles.save(other)115        #expect(try await store.all(profile: other.id).isEmpty)116        let foreignFolder = try await store.append(Bookmark(profileID: other.id, kind: .folder, title: "Foreign", createdAt: day(), updatedAt: day()))117        await #expect(throws: PersistenceError.self) { try await store.move(swift.id, to: foreignFolder.id) }118    }119120    // MARK: Netscape HTML121122    /// Written by hand after a real Safari "Export Bookmarks…" file: no outer <DL>, <H3 FOLDED>, lower-case123    /// attribute-less anchors, the Reading List folder with its id attribute, <DT> never closed.124    static let safariSample = """125    <!DOCTYPE NETSCAPE-Bookmark-file-1>126    \t<HTML>127    \t<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">128    \t<Title>Bookmarks</Title>129    \t<H1>Bookmarks</H1>130    \t<DT><H3 FOLDED>Favorites</H3>131    \t<DL><p>132    \t\t<DT><A HREF="https://www.apple.com/ca/fr/">Apple (Français)</A>133    \t\t<DT><A HREF="https://www.icloud.com/">iCloud</A>134    \t\t<DT><H3 FOLDED>Journaux &amp; actualités</H3>135    \t\t<DL><p>136    \t\t\t<DT><A HREF="https://www.lemonde.fr/">Le Monde.fr - Actualit&eacute;s et Infos en France et dans le monde</A>137    \t\t\t<DT><A HREF="https://ici.radio-canada.ca/info?x=1&amp;y=2">Info | Radio-Canada.ca</A>138    \t\t</DL><p>139    \t</DL><p>140    \t<DT><H3 FOLDED>Bookmarks Menu</H3>141    \t<DL><p>142    \t</DL><p>143    \t<DT><A HREF="https://developer.apple.com/documentation/webkit/wkwebview">WKWebView | Apple Developer Documentation</A>144    \t<DT><A HREF="https://fr.wikipedia.org/wiki/Qu%C3%A9bec">Québec — Wikipédia</A>145    \t<DT><A HREF="javascript:void(window.open('https://example.com/?u='+location.href))">Share bookmarklet</A>146    \t<DT><H3 FOLDED>Recherche</H3>147    \t<DL><p>148    \t\t<DT><A HREF="https://arxiv.org/abs/1706.03762">[1706.03762] Attention Is All You Need</A>149    \t\t<DT><A HREF="https://www.sqlite.org/fts5.html">SQLite FTS5 Extension</A>150    \t</DL><p>151    \t<DT><H3 FOLDED id="com.apple.ReadingList">Reading List</H3>152    \t<DL><p>153    \t\t<DT><A HREF="https://example.com/long-read">A long read &lt;part 1&gt; &quot;quoted&quot;</A>154    \t</DL><p>155    \t</HTML>156    """157158    @Test func parsesSafariExport() throws {159        let parsed = NetscapeBookmarks.parse(Self.safariSample)160        #expect(parsed.skippedLinks == 1)   // the bookmarklet161        #expect(parsed.roots.map(\.title) == ["Favorites", "Bookmarks Menu", "WKWebView | Apple Developer Documentation",162                                              "Québec — Wikipédia", "Recherche", "Reading List"])163        let favorites = parsed.roots[0]164        #expect(favorites.kind == .folder)165        #expect(favorites.children.map(\.title) == ["Apple (Français)", "iCloud", "Journaux & actualités"])166        let papers = favorites.children[2]167        #expect(papers.children.map(\.title) == ["Le Monde.fr - Actualités et Infos en France et dans le monde", "Info | Radio-Canada.ca"])168        #expect(papers.children[1].url == url("https://ici.radio-canada.ca/info?x=1&y=2"))169        #expect(parsed.roots[1].kind == .folder)170        #expect(parsed.roots[1].children.isEmpty)171        #expect(parsed.roots[3].url == url("https://fr.wikipedia.org/wiki/Qu%C3%A9bec"))172        #expect(parsed.roots[4].children.map(\.url) == [url("https://arxiv.org/abs/1706.03762"), url("https://www.sqlite.org/fts5.html")])173        #expect(parsed.roots[5].children.map(\.title) == ["A long read <part 1> \"quoted\""])174        #expect(parsed.linkCount == 9)175        #expect(parsed.folderCount == 5)176    }177178    /// Chrome/Edge/Brave shape: outer <DL>, dates, a huge ICON data URL, the bookmarks bar flag.179    @Test func parsesChromeExport() throws {180        let icon = "data:image/png;base64," + String(repeating: "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQ>CAYAAAAf8/9hAAAA\"x'", count: 400)181            .replacingOccurrences(of: "\"", with: "")182        let html = """183        <!DOCTYPE NETSCAPE-Bookmark-file-1>184        <!-- This is an automatically generated file.185             It will be read and overwritten.186             DO NOT EDIT! -->187        <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">188        <TITLE>Bookmarks</TITLE>189        <H1>Bookmarks</H1>190        <DL><p>191            <DT><H3 ADD_DATE="1700000000" LAST_MODIFIED="1700000500" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>192            <DL><p>193                <DT><A HREF="https://github.com/" ADD_DATE="1700000100" ICON="\(icon)">GitHub: Let’s build from here</A>194                <DT><H3 ADD_DATE="1700000200" LAST_MODIFIED="0">Work</H3>195                <DL><p>196                    <DT><A HREF="https://mail.example.com/u/0/#inbox" ADD_DATE="1700000300">Inbox (3)</A>197                    <DT><A HREF="chrome://settings/" ADD_DATE="1700000301">Settings</A>198                </DL><p>199            </DL><p>200            <DT><H3 ADD_DATE="1700000400" LAST_MODIFIED="1700000400">Other bookmarks</H3>201            <DL><p>202                <DT><A HREF="https://example.com/a>b" ADD_DATE="1700000401000">Odd &gt; URL</A>203            </DL><p>204        </DL><p>205        """206        let parsed = NetscapeBookmarks.parse(html)207        #expect(parsed.roots.map(\.title) == ["Bookmarks bar", "Other bookmarks"])208        let bar = parsed.roots[0]209        #expect(bar.isToolbarFolder)210        #expect(bar.addedAt == Date(timeIntervalSince1970: 1_700_000_000))211        #expect(bar.modifiedAt == Date(timeIntervalSince1970: 1_700_000_500))212        #expect(bar.children.map(\.title) == ["GitHub: Let’s build from here", "Work"])213        // Links directly on the bar are favourites; links in sub-folders are not.214        #expect(bar.children[0].isFavorite)215        #expect(bar.children[0].addedAt == Date(timeIntervalSince1970: 1_700_000_100))216        #expect(bar.children[1].children.map(\.title) == ["Inbox (3)"])217        #expect(bar.children[1].children[0].isFavorite == false)218        #expect(bar.children[1].modifiedAt == nil)219        #expect(parsed.skippedLinks == 1)   // chrome://settings220        // Milliseconds are recognised; '>' inside a quoted attribute does not end the tag.221        let odd = parsed.roots[1].children[0]222        #expect(odd.title == "Odd > URL")223        #expect(odd.addedAt == Date(timeIntervalSince1970: 1_700_000_401))224        #expect(odd.url?.host() == "example.com")225    }226227    /// Firefox shape: tags, descriptions (<DD>), separators (<HR>), place: queries, unfiled folder.228    @Test func parsesFirefoxExport() throws {229        let html = """230        <!DOCTYPE NETSCAPE-Bookmark-file-1>231        <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">232        <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'none'; img-src data: *; object-src 'none'"></meta>233        <TITLE>Bookmarks</TITLE>234        <H1>Bookmarks Menu</H1>235236        <DL><p>237            <DT><A HREF="place:sort=8&maxResults=10" ADD_DATE="1600000000" LAST_MODIFIED="1600000000">Most Visited</A>238            <DT><A HREF="https://www.mozilla.org/en-US/firefox/" ADD_DATE="1600000001" LAST_MODIFIED="1600000002" TAGS="mozilla, browser,open source">Firefox</A>239            <DD>Get Firefox, a free web browser backed by Mozilla240            <HR>    <DT><H3 ADD_DATE="1600000003" LAST_MODIFIED="1600000004" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks Toolbar</H3>241            <DD>Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar242            <DL><p>243                <DT><A HREF="https://news.ycombinator.com/" ADD_DATE="1600000005" SHORTCUTURL="hn">Hacker News</A>244            </DL><p>245            <DT><H3 ADD_DATE="1600000006" LAST_MODIFIED="1600000007" UNFILED_BOOKMARKS_FOLDER="true">Other Bookmarks</H3>246            <DL><p>247                <DT><a href='ftp://ftp.example.org/pub/' add_date=1600000008>lower-case tag, single quotes, bare value</a>248                <DT><A HREF="https://example.org/untitled"></A>249            </DL><p>250        </DL>251        """252        let parsed = NetscapeBookmarks.parse(html)253        #expect(parsed.skippedLinks == 1)254        #expect(parsed.roots.map(\.title) == ["Firefox", "Bookmarks Toolbar", "Other Bookmarks"])255        #expect(parsed.roots[0].tags == ["mozilla", "browser", "open source"])256        #expect(parsed.roots[0].modifiedAt == Date(timeIntervalSince1970: 1_600_000_002))257        #expect(parsed.roots[1].children.map(\.title) == ["Hacker News"])258        #expect(parsed.roots[1].children[0].isFavorite)259        let other = parsed.roots[2].children260        #expect(other.map(\.title) == ["lower-case tag, single quotes, bare value", "example.org"])   // untitled → host261        #expect(other[0].url == url("ftp://ftp.example.org/pub/"))262        #expect(other[0].addedAt == Date(timeIntervalSince1970: 1_600_000_008))263    }264265    @Test func malformedInputNeverCrashes() {266        let inputs = [267            "", "plain text, no markup", "<", ">", "<<<<>>>>", "<DL>", "</DL></DL></DL>", "<DT><A HREF=", "<DT><A HREF=\"https://a.example/",268            "<DT><A HREF=\"https://a.example/\">never closed", "<H3>Folder without list", "<H3>One<H3>Two<DL><DT><A HREF=https://b.example/>B",269            "<!-- unterminated comment <DT><A HREF=\"https://c.example/\">C</A>", "<DL><p><DT><A>no href</A></DL>",270            "<A HREF=\"https://d.example/\">&#xZZ; &#99999999999; &unknown; & alone &amp</A>", String(repeating: "<DL><p><DT><H3>x</H3>", count: 2_000),271            "\u{0}\u{1}<DT>\u{0}<A HREF=\"https://e.example/\">\u{0}E</A>", "<A HREF='https://f.example/' ICON=\"data:" + String(repeating: "A", count: 100_000),272        ]273        for input in inputs { _ = NetscapeBookmarks.parse(input) }274        // Absurd nesting is flattened at the depth limit instead of building a 2 000-level tree.275        func depth(_ nodes: [BookmarkFileNode]) -> Int { nodes.map { 1 + depth($0.children) }.max() ?? 0 }276        let deep = NetscapeBookmarks.parse(String(repeating: "<DL><p><DT><H3>x</H3>", count: 2_000) + "<DL><DT><A HREF=\"https://deep.example/\">deep</A>")277        #expect(depth(deep.roots) <= NetscapeBookmarks.maximumDepth + 2)278        #expect(deep.folderCount == 2_000)279        #expect(deep.linkCount == 1)280        #expect(NetscapeBookmarks.parse("<DT><A HREF=\"https://a.example/\">never closed").roots.map(\.title) == ["never closed"])281        #expect(NetscapeBookmarks.parse("<H3>Folder without list").roots.map(\.kind) == [.folder])282        let nested = NetscapeBookmarks.parse("<H3>One<H3>Two<DL><DT><A HREF=https://b.example/>B")283        #expect(nested.roots.map(\.title) == ["One", "Two"])284        #expect(nested.roots[1].children.map(\.title) == ["B"])285        #expect(NetscapeBookmarks.parse("<A HREF=\"https://d.example/\">&#x41;&#66; &unknown; & alone &amp</A>").roots.first?.title == "AB &unknown; & alone &amp")286        // Encodings: UTF-16 with a byte-order mark and a legacy single-byte file.287        let utf16 = "<DT><A HREF=\"https://g.example/\">Été à Québec</A>".data(using: .utf16)!288        #expect(NetscapeBookmarks.parse(data: utf16).roots.first?.title == "Été à Québec")289        let latin = "<DT><A HREF=\"https://h.example/\">Été</A>".data(using: .windowsCP1252)!290        #expect(NetscapeBookmarks.parse(data: latin).roots.first?.title == "Été")291    }292293    @Test func exportImportRoundTripThroughTheStore() async throws {294        let fixture = try await Fixture.make()295        let store = fixture.database.bookmarks296        let profile = fixture.profile.id297        let dev = try await store.append(folder(fixture, "Dev & <Tools> \"quoted\""))298        let empty = try await store.append(folder(fixture, "Empty folder"))299        _ = try await store.append(link(fixture, "Swift — “the” language", "https://swift.org/?a=1&b=2#frag", parent: dev.id,300                                        tags: ["dev", "apple, inc", "été"], favorite: true))301        let deep = try await store.append(folder(fixture, "Deep", parent: dev.id))302        _ = try await store.append(link(fixture, "日本語のタイトル 🚀", "https://ja.example.com/%E6%9D%B1%E4%BA%AC", parent: deep.id))303        _ = try await store.append(link(fixture, "Top <b>level</b>", "https://example.com/"))304        try await store.setFavorite(empty.id, true, at: day())305306        let html = try await store.exportHTML(profile: profile)307        #expect(html.hasPrefix("<!DOCTYPE NETSCAPE-Bookmark-file-1>"))308        #expect(html.contains("<DT><H3 ADD_DATE=\"1780000000\" LAST_MODIFIED=\"1780000000\">Dev &amp; &lt;Tools&gt; &quot;quoted&quot;</H3>"))309        #expect(html.contains("HREF=\"https://swift.org/?a=1&amp;b=2#frag\""))310311        // Import into a second profile and compare the trees field by field.312        let other = Profile(name: "Other", createdAt: day())313        try await fixture.database.profiles.save(other)314        let report = try await store.importHTML(Data(html.utf8), profile: other.id)315        #expect(report == BookmarkImportReport(foldersCreated: 3, linksCreated: 3, linksSkipped: 0))316317        struct Shape: Equatable { var kind: Bookmark.Kind; var title: String; var url: URL?; var tags: [String]; var favorite: Bool318                                 var created: Date; var order: Int; var children: [Shape] }319        func shape(_ nodes: [BookmarkNode]) -> [Shape] {320            nodes.map { Shape(kind: $0.bookmark.kind, title: $0.bookmark.title, url: $0.bookmark.url,321                              // The file format separates tags with commas, so a comma inside a tag becomes a space.322                              tags: $0.bookmark.tags.map { $0.replacingOccurrences(of: ",", with: " ") },323                              favorite: $0.bookmark.isFavorite, created: $0.bookmark.createdAt, order: $0.bookmark.order,324                              children: shape($0.children)) }325        }326        let original = shape(try await store.tree(profile: profile))327        let imported = shape(try await store.tree(profile: other.id))328        #expect(imported == original)329        #expect(original.count == 3)330331        // A second export of the imported tree is byte-identical: the format round-trips.332        #expect(try await store.exportHTML(profile: other.id) == html.replacingOccurrences(of: "apple, inc", with: "apple  inc"))333334        // Importing under a folder appends after the existing children and rolls back on a bad target.335        let target = try await store.append(Bookmark(profileID: other.id, kind: .folder, title: "Imported from Safari", createdAt: day(), updatedAt: day()))336        let safari = try await store.importHTML(Self.safariSample, profile: other.id, into: target.id, at: day(7))337        #expect(safari == BookmarkImportReport(foldersCreated: 5, linksCreated: 9, linksSkipped: 1))338        let children = try await store.children(of: target.id, profile: other.id)339        #expect(children.map(\.title).first == "Favorites")340        #expect(children.map(\.order) == Array(0..<6))341        #expect(children.allSatisfy { $0.createdAt == day(7) })   // Safari writes no dates: the import date is used342        await #expect(throws: PersistenceError.self) {343            _ = try await store.importHTML(Self.safariSample, profile: other.id, into: BookmarkID())344        }345        #expect(try await store.all(profile: other.id).count == 6 + 1 + 14)346    }347}348
Files main
Menu

Theme