-
Notifications
You must be signed in to change notification settings - Fork 41
/
crawler_test.go
126 lines (116 loc) · 2.47 KB
/
crawler_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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package antch
import (
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
)
func TestCrawlerBasic(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}))
defer ts.Close()
tc := NewCrawler()
// The custom spider handler.
tc.Handle("*", HandlerFunc(func(c chan<- Item, resp *http.Response) {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("ReadAll failed: %v", err)
}
c <- string(b)
}))
c := make(chan Item)
// The custom pipeline handler.
tc.UsePipeline(func(_ PipelineHandler) PipelineHandler {
return PipelineHandlerFunc(func(v Item) {
c <- v
})
})
tc.StartURLs([]string{ts.URL})
// Waiting to receive a value from crawler tc.
if g, e := (<-c).(string), "ok"; g != e {
t.Errorf("expected %s; got %s", e, g)
}
}
func TestCrawlerSpiderMux(t *testing.T) {
var serveFakes = []struct {
host string
path string
code int
}{
{"example.com", "/", 200},
{"example.com", "/search", 201},
{"localhost", "/", 200},
}
var spiderMuxTests = []struct {
pattern string
code int
}{
{"example.com", 200},
{"example.com/search", 201},
{"localhost", 200},
}
var tc = NewCrawler()
for _, e := range spiderMuxTests {
tc.Handle(e.pattern, HandlerFunc(func(c chan<- Item, res *http.Response) {
c <- res.StatusCode
}))
}
for _, fake := range serveFakes {
r := &http.Request{
Method: "GET",
Host: fake.host,
URL: &url.URL{
Path: fake.path,
},
}
res := &http.Response{
Request: r,
StatusCode: fake.code,
}
h, _ := tc.Handler(res)
c := make(chan Item, 1)
h.ServeSpider(c, res)
if code := (<-c).(int); code != fake.code {
t.Errorf("%s expected %d; got %d", fake.host+fake.path, fake.code, code)
}
}
}
func TestSpiderIdleTimeout(t *testing.T) {
timeout := 10 * time.Millisecond
spider := &spider{
key: "test",
c: &Crawler{},
idleTimeout: timeout,
}
done := make(chan struct{})
var (
start time.Time
end time.Time
)
go func() {
defer close(done)
start = time.Now()
spider.crawlLoop()
end = time.Now()
}()
<-done
if d := end.Sub(start); d < timeout {
t.Errorf("spider's timeout expected <= %d; but %d", timeout, d)
}
}
func TestCrawlerNilLogger(t *testing.T) {
loggers := []Logger{
log.New(os.Stdout, "", log.LstdFlags),
nilLogger{},
}
tc := &Crawler{}
for _, logger := range loggers {
tc.ErrorLog = logger
tc.logf("test logging")
}
}