-
Notifications
You must be signed in to change notification settings - Fork 11
/
httphandlers_test.go
88 lines (78 loc) · 1.98 KB
/
httphandlers_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
// httphandlers_test.go
package main
import (
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestHealthzHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/healthz", nil)
if err != nil {
t.Fatal(err)
}
// test HTTP status OK
rr := httptest.NewRecorder()
handler := http.HandlerFunc(healthzHandler)
handler.ServeHTTP(rr, req)
if !assert.Equal(t, http.StatusOK, rr.Code) {
t.Errorf("handler returned wrong status code: got %v want %v",
rr.Code, http.StatusOK)
}
// test HTTP body
expected := `{"alive": true}`
if !assert.Equal(t, expected, rr.Body.String()) {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), expected)
}
}
func TestReadyzHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/readyz", nil)
if err != nil {
t.Fatal(err)
}
ready := &atomic.Value{}
ready.Store(true)
notReady := &atomic.Value{}
notReady.Store(false)
tests := []struct {
name string
isReady *atomic.Value
expectedStatus int
expectedBody string
}{
{
name: "test_503",
isReady: notReady,
expectedStatus: 503,
expectedBody: "Service Unavailable\n",
},
{
name: "test_200",
isReady: ready,
expectedStatus: 200,
expectedBody: `{"ready": true}`,
},
}
// test HTTP status OK
for _, tt := range tests {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(readyzHandler(tt.isReady))
handler.ServeHTTP(rr, req)
if !assert.Equal(t, tt.expectedStatus, rr.Code) {
t.Errorf("handler returned wrong status code: got %v want %v",
rr.Code, tt.expectedStatus)
}
}
// test HTTP body
for _, tt := range tests {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(readyzHandler(tt.isReady))
handler.ServeHTTP(rr, req)
if !assert.Equal(t, tt.expectedBody, rr.Body.String()) {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), tt.expectedBody)
}
}
}