summaryrefslogtreecommitdiff
path: root/internal/links/find_count_test.go
blob: 756557bbbbaf2d29f1a90df9eba97fbbf66868c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package links

import (
	"fmt"
	"log"
	"net/url"
	"strings"
	"testing"
)

type exampleType struct {
	expectedCount int
	rawBaseURL    string
	content       string
}

var examples = []exampleType{
	// Example 1
	{2, "https://example.com", `
<html>
  <head>
    <title>Ex 1</title>
  <head>
  <body>
    <a href="https://example.com/">Example Page</a>
    <a href="/posts">Posts</a>
  </body>
</html>
`},

	// Example 2
	{4, "https://example.com", `<html>
  <head>
    <title>Ex 2</title>
  <head>
  <body>
    <a href="https://example.com/">Example Page</a>
    <a href="/posts">Posts</a>
    <a href="#">A <a href="#">rouge</a> link!</a>
  </body>
</html>
`},

	// Example 3
	{2, "https://example.com", `<html>
<a href="https://example.com">Main Page</a>
<a href="/example1">Example 1</a>
<a href="https://brandonirizarry.xyz">Brandon's Blog</a>
<a href="https://brandonirizarry.xyz/post1">Post 1</a>
<a href=":foo">Bad link</a>
</html>
`},

	// Example 4
	{3, "https://example.com/example1", `<html>
<a href="/">Back to homepage</a>
<a href="#">Go to top of page</a>
<a href="/example2">Second example</a>
<a href="https://boot.dev">Boot Dev homepage</a>
</html>
`},
}

func TestFindCountHrefs(t *testing.T) {
	for i, ex := range examples {
		name := fmt.Sprintf("Example %d", i+1)
		baseURL, err := url.Parse(ex.rawBaseURL)
		if err != nil {
			t.Fatalf("can't parse %s: %v", ex.rawBaseURL, err)
		}

		t.Run(name, func(t *testing.T) {
			r := strings.NewReader(ex.content)
			hrefs, err := Parse(r, baseURL)
			if err != nil {
				t.Error(err)
			}

			if actualCount := len(hrefs); actualCount != ex.expectedCount {
				t.Errorf("got %d, want %d", actualCount, ex.expectedCount)
				log.Print(hrefs)
			}
		})
	}
}