Skip to content

Commit 510eea1

Browse files
committed
test: new test file
1 parent ea13d34 commit 510eea1

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

crawler_test.go

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package antch
2+
3+
import (
4+
"io/ioutil"
5+
"net/http"
6+
"net/http/httptest"
7+
"net/url"
8+
"testing"
9+
)
10+
11+
func TestCrawlerBasic(t *testing.T) {
12+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
13+
w.Write([]byte("ok"))
14+
}))
15+
defer ts.Close()
16+
17+
tc := NewCrawler()
18+
// The custom spider handler.
19+
tc.Handle("*", HandlerFunc(func(c chan<- Item, resp *http.Response) {
20+
b, err := ioutil.ReadAll(resp.Body)
21+
if err != nil {
22+
t.Fatalf("ReadAll failed: %v", err)
23+
}
24+
c <- string(b)
25+
}))
26+
27+
c := make(chan Item)
28+
// The custom pipeline handler.
29+
tc.UsePipeline(func(_ PipelineHandler) PipelineHandler {
30+
return PipelineHandlerFunc(func(v Item) {
31+
c <- v
32+
})
33+
})
34+
35+
tc.StartURLs([]string{ts.URL})
36+
// Waiting to receive a value from crawler tc.
37+
if g, e := (<-c).(string), "ok"; g != e {
38+
t.Errorf("expected %s; got %s", e, g)
39+
}
40+
}
41+
42+
func TestCrawlerSpiderMux(t *testing.T) {
43+
var serveFakes = []struct {
44+
host string
45+
path string
46+
code int
47+
}{
48+
{"example.com", "/", 200},
49+
{"example.com", "/search", 201},
50+
{"localhost", "/", 200},
51+
}
52+
53+
var spiderMuxTests = []struct {
54+
pattern string
55+
code int
56+
}{
57+
{"example.com", 200},
58+
{"example.com/search", 201},
59+
{"localhost", 200},
60+
}
61+
62+
var tc = NewCrawler()
63+
tc.Handle("*", HandlerFunc(func(c chan<- Item, res *http.Response) {
64+
c <- 0
65+
}))
66+
for _, e := range spiderMuxTests {
67+
tc.Handle(e.pattern, HandlerFunc(func(c chan<- Item, res *http.Response) {
68+
c <- res.StatusCode
69+
}))
70+
}
71+
for _, fake := range serveFakes {
72+
r := &http.Request{
73+
Method: "GET",
74+
Host: fake.host,
75+
URL: &url.URL{
76+
Path: fake.path,
77+
},
78+
}
79+
res := &http.Response{
80+
Request: r,
81+
StatusCode: fake.code,
82+
}
83+
h, _ := tc.Handler(res)
84+
c := make(chan Item, 1)
85+
h.ServeSpider(c, res)
86+
if code := (<-c).(int); code != fake.code {
87+
t.Errorf("%s expected %d; got %d", fake.host+fake.path, fake.code, code)
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)