-
Notifications
You must be signed in to change notification settings - Fork 6
/
response_replace_test.go
78 lines (64 loc) · 2.14 KB
/
response_replace_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
// Copyright (c) 2021, Janoš Guljaš <[email protected]>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web_test
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"resenje.org/web"
)
func TestResponseReplaceHanlder(t *testing.T) {
handler := web.ResponseReplaceHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
fmt.Fprint(w, "OK")
return
}
if r.URL.Path == "/broken" {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "sensitive information")
return
}
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "this should never be seen")
}), map[int]http.Handler{
http.StatusNotFound: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound) // keep the same status
fmt.Fprint(w, "the page is not here")
}),
http.StatusInternalServerError: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot) // set a different status
fmt.Fprint(w, "have some tea")
}),
})
t.Run("no replace", func(t *testing.T) {
r := httptest.NewRequest("", "/", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
assertResponse(t, w, http.StatusOK, "OK")
})
t.Run("replace with the same status code", func(t *testing.T) {
r := httptest.NewRequest("", "/password", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
assertResponse(t, w, http.StatusNotFound, "the page is not here")
})
t.Run("replace with a different status code", func(t *testing.T) {
r := httptest.NewRequest("", "/broken", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
assertResponse(t, w, http.StatusTeapot, "have some tea")
})
}
func assertResponse(t *testing.T, r *httptest.ResponseRecorder, wantStatusCode int, wantBody string) {
gotStatusCode := r.Result().StatusCode
if gotStatusCode != wantStatusCode {
t.Errorf("got status code %v, want %v", gotStatusCode, wantStatusCode)
}
gotBody := r.Body.String()
if gotBody != wantBody {
t.Errorf("got body %q, want %q", gotBody, wantBody)
}
}