| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "net/url" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | |
| 8 | "golang.org/x/net/html" |
| 9 | ) |
| 10 | |
| 11 | func parseDoc(t *testing.T, s string) *html.Node { |
| 12 | t.Helper() |
| 13 | doc, err := html.Parse(strings.NewReader(s)) |
| 14 | if err != nil { |
| 15 | t.Fatal(err) |
| 16 | } |
| 17 | return doc |
| 18 | } |
| 19 | |
| 20 | func TestFaviconExtractionPriorityAndFallback(t *testing.T) { |
| 21 | base, _ := url.Parse("https://example.com/path/page") |
| 22 | cases := []struct{ name, html, want string }{ |
| 23 | {"icon", `<head><link rel="icon" href="/icon.png"></head>`, "https://example.com/icon.png"}, |
| 24 | {"shortcut", `<head><link rel="shortcut icon" href="shortcut.ico"></head>`, "https://example.com/path/shortcut.ico"}, |
| 25 | {"apple", `<head><link rel="apple-touch-icon" href="https://cdn.test/apple.png"></head>`, "https://cdn.test/apple.png"}, |
| 26 | {"priority", `<head><link rel="apple-touch-icon" href="/apple.png"><link rel="shortcut icon" href="/shortcut.ico"><link rel="icon" href="/icon.png"></head>`, "https://example.com/icon.png"}, |
| 27 | {"fallback", `<head></head>`, "https://example.com/favicon.ico"}, |
| 28 | } |
| 29 | for _, tc := range cases { |
| 30 | t.Run(tc.name, func(t *testing.T) { |
| 31 | if got := extractFavicon(parseDoc(t, tc.html), base); got != tc.want { |
| 32 | t.Fatalf("got %q want %q", got, tc.want) |
| 33 | } |
| 34 | }) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func TestExtractLinkTags(t *testing.T) { |
| 39 | base, _ := url.Parse("https://example.com/dir/page") |
| 40 | doc := parseDoc(t, `<html><head><link rel="preload" href="/style.css" as="style"><link rel="canonical" href="canonical"></head><body><link rel="ignored" href="/body"></body></html>`) |
| 41 | links := extractLinkTags(doc, base) |
| 42 | if len(links) != 2 { |
| 43 | t.Fatalf("links %#v", links) |
| 44 | } |
| 45 | if links[0].Rel != "preload" || links[0].Href != "https://example.com/style.css" || links[0].Extra != `as="style"` { |
| 46 | t.Fatalf("first link %#v", links[0]) |
| 47 | } |
| 48 | if links[1].Href != "https://example.com/dir/canonical" { |
| 49 | t.Fatalf("relative href %q", links[1].Href) |
| 50 | } |
| 51 | if got := extractLinkTags(parseDoc(t, `<html><body></body></html>`), base); got != nil { |
| 52 | t.Fatalf("expected nil without head, got %#v", got) |
| 53 | } |
| 54 | } |