This repository has been archived by the owner on Nov 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_test.go
73 lines (64 loc) · 1.7 KB
/
extract_test.go
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
package main
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
// NewTestServer allocates a testing server that serves up content
// to try to extract links from
func NewTestServer() *httptest.Server {
m := http.NewServeMux()
m.HandleFunc("/1", func(w http.ResponseWriter, r *http.Request) {
body := []byte(`
<html>
<body>
<a>This shouldn't work</a>
<a href="#bad"></a>
<a href="/rel-endpoint"></a>
<a href="http://youtube.com/external-link"></a>
</body>
</html>`)
w.Write(body)
})
return httptest.NewServer(m)
}
func TestFetchAndWriteHrefAttrs(t *testing.T) {
s := NewTestServer()
cases := []struct {
endpoint string
selector string
fetchError error
stats *Stats
}{
{"/1", "a", nil, &Stats{Elements: 4, WithHref: 3, ValidUrl: 2, Duplicates: 1}},
}
for i, c := range cases {
w := &bytes.Buffer{}
root := fmt.Sprintf("%s%s", s.URL, c.endpoint)
stats, err := FetchAndWriteHrefAttrs(root, "a", w)
if err != c.fetchError {
t.Errorf("case %d fetch error mismatch: %s != %s", err, c.fetchError)
}
if err := CompareStats(c.stats, stats); err != nil {
t.Errorf("case %d stats error: %s", i, err.Error())
continue
}
}
}
func CompareStats(a, b *Stats) error {
if a.Elements != b.Elements {
return fmt.Errorf("element count mismatch: %d != %d", a.Elements, b.Elements)
}
if a.WithHref != b.WithHref {
return fmt.Errorf("WithHref count mismatch: %d != %d", a.WithHref, b.WithHref)
}
if a.Duplicates != b.Duplicates {
return fmt.Errorf("Duplicate count mismatch: %d != %d", a.Duplicates, b.Duplicates)
}
if a.ValidUrl != b.ValidUrl {
return fmt.Errorf("valid url count mismatch: %d != %d", a.ValidUrl, b.ValidUrl)
}
return nil
}