-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathredirecterrors_test.go
More file actions
105 lines (80 loc) · 2.46 KB
/
redirecterrors_test.go
File metadata and controls
105 lines (80 loc) · 2.46 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
102
103
104
105
package redirecterrors_test
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/indivisible/redirecterrors"
)
func TestBadConfig(t *testing.T) {
cfg := redirecterrors.CreateConfig()
cfg.Status = []string{}
cfg.Target = ""
ctx := context.Background()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {})
_, err := redirecterrors.New(ctx, next, cfg, "redirecterrors-plugin")
if !assert(t, err != nil) {
return
}
assert(t, err.Error() == "target url must be set")
}
// TODO: more tests: config parsing & non-intercepted response
func TestRedirect(t *testing.T) {
cfg := redirecterrors.CreateConfig()
cfg.Status = []string{"401", "402"}
cfg.Target = "http://target/?status={status}&url={url}"
ctx := context.Background()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(401) })
handler, err := redirecterrors.New(ctx, next, cfg, "redirecterrors-plugin")
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
if err != nil {
t.Fatal(err)
}
handler.ServeHTTP(recorder, req)
resp := recorder.Result()
assertHeader(t, resp, "Location", "http://target/?status=401&url=http%3A%2F%2Flocalhost")
assertCode(t, resp, 302)
}
func TestNoRedirect(t *testing.T) {
cfg := redirecterrors.CreateConfig()
cfg.Status = []string{}
cfg.Target = "http://target/?status={status}&url={url}"
ctx := context.Background()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {})
handler, err := redirecterrors.New(ctx, next, cfg, "redirecterrors-plugin")
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
if err != nil {
t.Fatal(err)
}
handler.ServeHTTP(recorder, req)
resp := recorder.Result()
assertCode(t, resp, 200)
assertHeader(t, resp, "Location", "")
}
func assertCode(t *testing.T, resp *http.Response, expected int) {
t.Helper()
if resp.StatusCode != expected {
t.Errorf("invalid status value: %d", resp.StatusCode)
}
}
func assert(t *testing.T, condition bool) bool {
t.Helper()
if !condition {
t.Error("Assertation failed")
}
return condition
}
func assertHeader(t *testing.T, resp *http.Response, key, expected string) {
t.Helper()
if resp.Header.Get(key) != expected {
t.Errorf("invalid header value: %s", resp.Header.Get(key))
}
}