-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbanlist_test.go
More file actions
101 lines (85 loc) · 2.48 KB
/
banlist_test.go
File metadata and controls
101 lines (85 loc) · 2.48 KB
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
package banlist
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBanlistMissingFile(t *testing.T) {
bl := newBanlist(tl(t), "not a path")
require.Error(t, bl.update())
}
func TestBanlistInvalidFileContents(t *testing.T) {
path, err := ioutil.TempFile("", "")
require.NoError(t, err)
defer os.Remove(path.Name())
_, err = path.WriteString("this isn't valid json")
require.NoError(t, err)
bl := newBanlist(tl(t), path.Name())
require.Error(t, bl.update())
}
func TestBanlistNoPaths(t *testing.T) {
bl := testList(t, &Config{
Domains: []string{"something.com"},
})
assert.Empty(t, bl.urls())
domains := bl.domains()
assert.Len(t, domains, 1)
_, ok := domains["something.com"]
assert.True(t, ok)
}
func TestBanlistNoDomains(t *testing.T) {
bl := testList(t, &Config{
URLs: []string{"something.com/path/to/thing"},
})
urls := bl.urls()
assert.Len(t, urls, 1)
_, ok := urls["something.com/path/to/thing"]
assert.True(t, ok)
assert.Empty(t, bl.domains())
}
func TestBanlistBanning(t *testing.T) {
bl := testList(t, &Config{
URLs: []string{"villians.com/the/joker"},
Domains: []string{"sick.com"},
})
tests := []struct {
url string
isBanned bool
name string
}{
{"http://heros.com", false, "completely unbanned"},
{"http://sick.com:12345", true, "banned domain with port"},
{"http://sick.com", true, "banned domain without port"},
{"http://siCK.com", true, "banned domain mixed case"},
{"http://villians.com:12354/the/joker", true, "banned path with port"},
{"http://villians.com/the/joker", true, "banned path without port"},
{"http://villians.com/the/Joker", true, "banned path mixed case"},
{"http://villians.com/the/joker?query=param", true, "banned path with query params"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, test.url, nil)
assert.Equal(t, test.isBanned, bl.CheckRequest(req))
})
}
}
func tl(t *testing.T) logrus.FieldLogger {
l := logrus.New()
l.SetLevel(logrus.DebugLevel)
return l.WithField("test", t.Name())
}
func testList(t *testing.T, config *Config) *Banlist {
path, err := ioutil.TempFile("", "")
require.NoError(t, err)
defer os.Remove(path.Name())
require.NoError(t, json.NewEncoder(path).Encode(config))
bl := newBanlist(tl(t), path.Name())
require.NoError(t, bl.update())
return bl
}