-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtimeout_test.go
More file actions
76 lines (64 loc) · 1.62 KB
/
timeout_test.go
File metadata and controls
76 lines (64 loc) · 1.62 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
package gomw
import (
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type nextHandler struct {
run func()
called bool
success bool
totalCalls int
statusCode int
Mutex sync.Locker
}
func newMockNextHandler() *nextHandler {
return &nextHandler{Mutex: &sync.Mutex{}}
}
func (h *nextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.Mutex.Lock()
defer h.Mutex.Unlock()
h.called = true
if h.run != nil {
h.run()
}
h.success = true
h.totalCalls++
if h.statusCode != 0 {
w.WriteHeader(h.statusCode)
}
}
func (h *nextHandler) Called() bool {
h.Mutex.Lock()
defer h.Mutex.Unlock()
return h.called
}
func (h *nextHandler) Success() bool {
h.Mutex.Lock()
defer h.Mutex.Unlock()
return h.success
}
func TestTimeoutMiddlewareCtxDeadlineExcceeded(t *testing.T) {
next := &nextHandler{run: func() { time.Sleep(10 * time.Millisecond) }, Mutex: new(sync.Mutex)}
d := 1 * time.Millisecond
handler := Timeout(d)(next)
req, _ := http.NewRequest("GET", "/some/url", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
assert.True(t, next.Called())
assert.Equal(t, http.StatusGatewayTimeout, w.Code)
}
func TestTimeoutMiddlewareHandlerSucceedsBeforeDeadline(t *testing.T) {
next := &nextHandler{run: func() { time.Sleep(10 * time.Millisecond) }, Mutex: &sync.Mutex{}}
d := 15 * time.Millisecond
handler := Timeout(d)(next)
req, _ := http.NewRequest("GET", "/some/url/success", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
assert.True(t, next.Called())
assert.True(t, next.Success())
assert.Equal(t, http.StatusOK, w.Code)
}