-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseatbelt_test.go
141 lines (122 loc) · 2.51 KB
/
seatbelt_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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package seatbelt
import (
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
)
func TestOptions(t *testing.T) {
o := &Option{}
t.Run("a master.key file should be present after calling setDefaults", func(t *testing.T) {
o.setDefaults()
data, err := os.ReadFile("master.key")
if err != nil {
t.Fatalf("failed to read master.key file: %v", err)
}
if data == nil {
t.Fatal("file is empty")
}
})
}
func TestSubRouter(t *testing.T) {
app := New()
app.Get("/", func(c *Context) error {
return c.String(200, "home")
})
app.Namespace("/admin", func(app *App) {
app.Get("/home", func(c *Context) error {
return c.String(200, "ok")
})
})
srv := httptest.NewServer(app)
defer srv.Close()
t.Run("GET /", func(t *testing.T) {
resp, err := http.Get(srv.URL + "/")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(data) != "home" {
t.Fatalf("expected home but got %s", data)
}
})
t.Run("GET /admin/home", func(t *testing.T) {
resp, err := http.Get(srv.URL + "/admin/home")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(data) != "ok" {
t.Fatalf("expected ok but got %s", data)
}
})
}
func TestCSRFSkipPaths(t *testing.T) {
app := New(Option{
SkipCSRFPaths: []string{"/api", "/skip-me"},
})
app.Get("/", func(c *Context) error {
return c.JSON(200, map[string]string{"message": "ok"})
})
app.Post("/", func(c *Context) error {
return c.NoContent()
})
app.Post("/api", func(c *Context) error {
return c.NoContent()
})
app.Put("/skip-me/test", func(c *Context) error {
return c.NoContent()
})
srv := httptest.NewServer(app)
defer srv.Close()
cases := []struct {
path string
method string
status int
}{
{
path: "/",
method: http.MethodGet,
status: 200,
},
{
path: "/",
method: http.MethodPost,
status: 403,
},
{
path: "/api",
method: http.MethodPost,
status: 204,
},
{
path: "/skip-me/test",
method: http.MethodPut,
status: 204,
},
}
for _, c := range cases {
t.Run(c.method+" "+c.path, func(t *testing.T) {
req, err := http.NewRequest(c.method, srv.URL+c.path, nil)
if err != nil {
t.Fatal(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != c.status {
t.Fatalf("expected %d but got %d", c.status, resp.StatusCode)
}
})
}
}