-
Notifications
You must be signed in to change notification settings - Fork 10
/
detector_test.go
97 lines (88 loc) · 2.01 KB
/
detector_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
package botdetector
import (
"fmt"
"net/http"
"testing"
)
func TestNew_rejectEmptyHeader(t *testing.T) {
d, err := New(Config{
Denylist: []string{"a", "b"},
Allowlist: []string{"c", "Pingdom.com_bot_version_1.1"},
Patterns: []string{
`(Pingdom.com_bot_version_)(\d+)\.(\d+)`,
`(facebookexternalhit)/(\d+)\.(\d+)`,
},
RejectIfEmpty: true,
})
if err != nil {
t.Error(err)
return
}
req, _ := http.NewRequest("GET", "https://example.com", http.NoBody) // skipcq: GO-S1028
req.Header.Add("User-Agent", "")
if !d(req) {
t.Error("req with empty User-Agent has not been detected as a bot")
}
}
func TestNew_noLRU(t *testing.T) {
d, err := New(Config{
Denylist: []string{"a", "b"},
Allowlist: []string{"c", "Pingdom.com_bot_version_1.1"},
Patterns: []string{
`(Pingdom.com_bot_version_)(\d+)\.(\d+)`,
`(facebookexternalhit)/(\d+)\.(\d+)`,
},
})
if err != nil {
t.Error(err)
return
}
if err := testDetection(d); err != nil {
t.Error(err)
}
}
func TestNew_LRU(t *testing.T) {
d, err := New(Config{
Denylist: []string{"a", "b"},
Allowlist: []string{"c", "Pingdom.com_bot_version_1.1"},
Patterns: []string{
`(Pingdom.com_bot_version_)(\d+)\.(\d+)`,
`(facebookexternalhit)/(\d+)\.(\d+)`,
},
CacheSize: 10000,
})
if err != nil {
t.Error(err)
return
}
if err := testDetection(d); err != nil {
t.Error(err)
}
}
func testDetection(f DetectorFunc) error {
for i, ua := range []string{
"abcd",
"",
"c",
"Pingdom.com_bot_version_1.1",
} {
req, _ := http.NewRequest("GET", "https://example.com", http.NoBody)
req.Header.Add("User-Agent", ua)
if f(req) {
return fmt.Errorf("the req #%d has been detected as a bot: %s", i, ua)
}
}
for i, ua := range []string{
"a",
"b",
"facebookexternalhit/1.1",
"Pingdom.com_bot_version_1.2",
} {
req, _ := http.NewRequest("GET", "https://example.com", http.NoBody)
req.Header.Add("User-Agent", ua)
if !f(req) {
return fmt.Errorf("the req #%d has not been detected as a bot: %s", i, ua)
}
}
return nil
}