forked from 1060460048/gospider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspider_test.go
122 lines (112 loc) · 2.19 KB
/
spider_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
package gospider
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/lakevilladom/goreq"
"github.com/stretchr/testify/assert"
)
func TestNewSpider(t *testing.T) {
a := 0
s := NewSpider(func(s *Spider) {
a += 1
})
s.OnTask(func(ctx *Context, t *Task) *Task {
ctx.Println("OnTask")
a += 1
return t
})
s.OnResp(func(ctx *Context) {
ctx.Println("OnResp")
a += 1
})
s.OnItem(func(ctx *Context, i interface{}) interface{} {
ctx.Println("OnItem", i)
a += 1
return i
})
s.OnRecover(func(ctx *Context, err error) {
a += 1
ctx.Println("OnRecover", err)
})
s.OnReqError(func(ctx *Context, err error) {
a += 1
ctx.Println("OnReqError", err)
})
s.OnRespError(func(ctx *Context, err error) {
a += 1
ctx.Println("OnRespError", err)
})
s.SeedTask(
goreq.Get("https://httpbin.org/get"),
func(ctx *Context) {
ctx.AddItem(ctx.Resp.Text)
panic("test panic")
},
)
r := goreq.Get("https://httpbin.org/get")
r.Err = errors.New("test error")
s.SeedTask(r)
s.SeedTask(goreq.Get("htps://httpbin.org/get"))
s.Wait()
assert.Equal(t, 9, a)
}
func TestContext_Abort(t *testing.T) {
c := make(chan struct{})
s := NewSpider()
s.SeedTask(
goreq.Get("https://httpbin.org/get"),
func(ctx *Context) {
ctx.AddItem(ctx.Resp.Text)
ctx.Abort()
c <- struct{}{}
},
func(ctx *Context) {
t.Error("abort fail")
},
)
_ = <-c
s.Wait()
}
func TestSpiderManyTask(t *testing.T) {
s := NewSpider()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "Hello")
}))
defer ts.Close()
i := 0
a := 30
for a > 0 {
s.SeedTask(
goreq.Get(ts.URL),
func(ctx *Context) {
i += 1
},
)
a -= 1
}
s.Wait()
assert.Equal(t, 30, i)
}
func BenchmarkSpider(b *testing.B) {
s := NewSpider()
s.Logging = false
req := goreq.Get("http://127.0.0.1:8080/")
b.ResetTimer()
for i := 0; i < b.N; i++ {
s.SeedTask(req)
}
s.Wait()
}
func BenchmarkGoreq(b *testing.B) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "Hello")
}))
defer ts.Close()
b.ResetTimer()
for i := 0; i < b.N; i++ {
goreq.Get(ts.URL).Do()
}
}