-
Notifications
You must be signed in to change notification settings - Fork 1
/
bean_test.go
285 lines (255 loc) · 6.61 KB
/
bean_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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright The RAI Inc.
// The RAI Authors
package bean
import (
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"strconv"
"syscall"
"testing"
"time"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestBean_UseErrorHandlerFuncs(t *testing.T) {
b := &Bean{}
assert.Empty(t, b.errorHandlerFuncs)
b.UseErrorHandlerFuncs(func(err error, c echo.Context) (bool, error) {
return true, nil
})
assert.Equal(t, 1, len(b.errorHandlerFuncs))
}
func TestDefaultHTTPErrorHandler(t *testing.T) {
b := &Bean{}
b.Echo = echo.New()
b.UseErrorHandlerFuncs(
func(err error, c echo.Context) (bool, error) {
he, ok := err.(*fakeError)
if !ok {
return false, nil
}
err = c.JSON(http.StatusBadRequest, map[string]interface{}{
"errorCode": "fake code",
"errors": he.Error(),
})
return ok, err
},
func(_ error, c echo.Context) (bool, error) {
err := c.JSON(http.StatusInternalServerError, map[string]interface{}{
"errorCode": "default code",
"errors": "default catched!",
})
return true, err
},
)
b.Echo.HTTPErrorHandler = b.DefaultHTTPErrorHandler()
b.Echo.Any("/fake", func(c echo.Context) error {
return newFakeError("fake error")
})
b.Echo.Any("/default", func(c echo.Context) error {
return echo.NewHTTPError(http.StatusInternalServerError, "default error")
})
// With Debug=true plain response contains error message
code, body := request(http.MethodGet, "/fake", b.Echo)
assert.Equal(t, http.StatusBadRequest, code)
assert.Equal(t, `{"errorCode":"fake code","errors":"fake error"}`+"\n", body)
// and special handling for HTTPError
code, body = request(http.MethodGet, "/default", b.Echo)
assert.Equal(t, http.StatusInternalServerError, code)
assert.Equal(t, `{"errorCode":"default code","errors":"default catched!"}`+"\n", body)
}
func request(method, path string, e *echo.Echo) (int, string) {
req := httptest.NewRequest(method, path, nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
type fakeError struct {
Message string
}
func (f *fakeError) Error() string {
return f.Message
}
func newFakeError(msg string) error {
return &fakeError{
Message: msg,
}
}
func TestBean_ServeAt(t *testing.T) {
type fields struct {
sdTimeout time.Duration
}
tests := []struct {
name string
fields fields
wantErr bool
wantLongSdn bool
wantConnErr bool
wantSuccess bool
_ struct{}
}{
{
name: "graceful shutdown success",
fields: fields{
sdTimeout: 0, // timeout will be 30s by default
},
wantErr: false,
wantLongSdn: true,
wantConnErr: false,
wantSuccess: true,
},
{
name: "graceful shutdown timeout",
fields: fields{
sdTimeout: 1 * time.Second, // Ensure timeout is less than sleep duration
},
wantErr: true,
wantLongSdn: false,
wantConnErr: false,
wantSuccess: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := &Bean{
Echo: echo.New(),
Config: Config{},
}
b.Config.HTTP.ShutdownTimeout = tt.fields.sdTimeout
sleepDur := 3 * time.Second
b.Echo.GET("/fake", func(c echo.Context) error {
ctx := c.Request().Context()
t.Logf("Sleeping for %v\n", sleepDur)
select {
case <-time.After(sleepDur):
t.Logf("Completed sleeping for %v\n", sleepDur)
return c.String(http.StatusOK, "OK")
case <-ctx.Done():
t.Logf("Request canceled: %v\n", ctx.Err())
return ctx.Err()
}
})
// for ping
b.Echo.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Pong")
})
host := "localhost"
port := strconv.Itoa(getFreePort(t))
srvErr := make(chan error, 1)
go func() {
srvErr <- b.ServeAt(host, port)
close(srvErr)
}()
ping := func() bool {
resp, err := http.Get("http://" + host + ":" + port)
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// wait for server to start
timeout := 5 * time.Second
timer := time.NewTimer(timeout)
defer timer.Stop()
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
waitSrv:
for {
select {
case <-timer.C:
t.Fatal("timeout waiting for server to start")
case <-ticker.C:
if ping() {
break waitSrv
}
}
}
// send sleep request
type result struct {
err error
success bool
}
readyToSleep := make(chan struct{}, 1)
sleepRlt := make(chan result, 1)
go func() {
readyToSleep <- struct{}{}
close(readyToSleep)
resp, err := http.Get("http://" + host + ":" + port + "/fake")
if err != nil {
sleepRlt <- result{err, false}
close(sleepRlt)
return
}
defer resp.Body.Close()
_, _ = io.ReadAll(resp.Body)
sleepRlt <- result{nil, resp.StatusCode == http.StatusOK}
close(sleepRlt)
}()
// wait for server to receive request
<-readyToSleep
time.Sleep(100 * time.Millisecond)
// measure the time taken for shutdown
start := time.Now()
// send SIGTERM to server
signalTERM(t)
// check if shutdown is successful
err := <-srvErr
gotDur := time.Since(start)
if (err != nil) != tt.wantErr {
t.Errorf("Bean.ServeAt() error = %v, wantErr %v", err, tt.wantErr)
}
if (gotDur >= sleepDur) != tt.wantLongSdn {
t.Errorf("shutdown took %v, wantLongSdn %v", gotDur, tt.wantLongSdn)
}
// check if server is down
if ping() {
t.Fatalf("server is still running after shutdown")
}
timer.Reset(timeout)
waitRlt:
for {
select {
case <-timer.C:
t.Fatal("timeout waiting for server to start")
case gotRlt := <-sleepRlt:
if (gotRlt.err != nil) != tt.wantConnErr {
t.Errorf("response error = %v, wantErr %v", gotRlt.err, tt.wantConnErr)
}
if gotRlt.success != tt.wantSuccess {
t.Errorf("response success = %v, wantSuccess %v", gotRlt.success, tt.wantSuccess)
}
break waitRlt
}
}
})
}
}
func getFreePort(t *testing.T) int {
t.Helper()
if addr, rErr := net.ResolveTCPAddr("tcp", "localhost:0"); rErr != nil {
t.Fatalf("failed to resolve tcp address: %v", rErr)
} else {
if ln, lnErr := net.ListenTCP("tcp", addr); lnErr != nil {
t.Fatalf("failed to listen on tcp address: %v", lnErr)
} else {
defer ln.Close()
return ln.Addr().(*net.TCPAddr).Port
}
}
t.Fatal("failed to get free port")
return 0
}
func signalTERM(t *testing.T) {
t.Helper()
p, err := os.FindProcess(os.Getpid())
if err != nil {
t.Fatalf("failed to find process: %v", err)
}
if err := p.Signal(syscall.SIGTERM); err != nil {
t.Fatalf("failed to send signal to process: %v", err)
}
}