-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
103 lines (79 loc) · 2.53 KB
/
server_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
package healthcheck_test
import (
"context"
"github.com/kazhuravlev/healthcheck"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"io"
"math/rand"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
)
//go:generate mockgen -destination server_mock_test.go -package healthcheck_test . IHealthcheck
func TestReadyHandler(t *testing.T) {
ctrl := gomock.NewController(t)
hc := NewMockIHealthcheck(ctrl)
f := func(status healthcheck.Status, expStatus int, expBody string) {
t.Run("", func(t *testing.T) {
ctx := context.Background()
hc.
EXPECT().
RunAllChecks(gomock.Eq(ctx)).
Return(healthcheck.Report{
Status: status,
Checks: []healthcheck.Check{},
})
req := httptest.NewRequest(http.MethodGet, "/ready", nil)
w := httptest.NewRecorder()
handler := healthcheck.ReadyHandler(hc)
handler(w, req)
res := w.Result()
defer res.Body.Close()
require.Equal(t, expStatus, res.StatusCode)
require.Equal(t, "application/json", res.Header.Get("Content-Type"))
bb, err := io.ReadAll(res.Body)
require.NoError(t, err)
require.Equal(t, expBody, string(bb))
})
}
f(healthcheck.StatusUp, http.StatusOK, `{"status":"up","checks":[]}`)
f(healthcheck.StatusDown, http.StatusInternalServerError, `{"status":"down","checks":[]}`)
f("i_do_not_know", http.StatusInternalServerError, `{"status":"unknown","checks":[]}`)
}
func TestServer(t *testing.T) {
ctrl := gomock.NewController(t)
hc := NewMockIHealthcheck(ctrl)
port := rand.Intn(1000) + 8000
srv, err := healthcheck.NewServer(hc, healthcheck.WithPort(port))
require.NoError(t, err)
ctx := context.Background()
require.NoError(t, srv.Run(ctx))
// FIXME: fix crunch
time.Sleep(time.Second)
t.Run("live_returns_200", func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:"+strconv.Itoa(port)+"/live", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
})
t.Run("ready_always_call_healthcheck", func(t *testing.T) {
hc.
EXPECT().
RunAllChecks(gomock.Any()).
Return(healthcheck.Report{
Status: healthcheck.StatusDown,
Checks: []healthcheck.Check{},
})
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:"+strconv.Itoa(port)+"/ready", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, http.StatusInternalServerError, resp.StatusCode)
})
}