-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext_handler_test.go
More file actions
67 lines (58 loc) · 1.97 KB
/
context_handler_test.go
File metadata and controls
67 lines (58 loc) · 1.97 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
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func Test_ContextExceeder(t *testing.T) {
t.Run("should send an error when the context is canceled", func(t *testing.T) {
w := httptest.NewRecorder()
r, _ := http.NewRequest("", "", nil)
ctx, fn := context.WithCancel(context.Background())
r = r.WithContext(ctx)
fn()
handler := ContextHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second)
}))
handler.ServeHTTP(w, r)
if w.Code != StatusNoResponse {
t.Errorf("response code was expected to be 444, got %d", w.Code)
}
if w.Body.String() != "context canceled\n" {
t.Errorf("the response %q was expected to be \"context canceled\n\"", w.Body.String())
}
})
t.Run("should send an error when the context deadline exceeded", func(t *testing.T) {
w := httptest.NewRecorder()
r, _ := http.NewRequest("", "", nil)
ctx, fn := context.WithDeadline(context.Background(), time.Time{})
r = r.WithContext(ctx)
defer fn()
handler := ContextHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second)
}))
handler.ServeHTTP(w, r)
if w.Code != http.StatusRequestTimeout {
t.Errorf("response code was expected to be 408, got %d", w.Code)
}
if w.Body.String() != "context deadline exceeded\n" {
t.Errorf("the response %q was expected to be \"context canceled\n\"", w.Body.String())
}
})
t.Run("should not return an error if request was processed in given time", func(t *testing.T) {
w := httptest.NewRecorder()
r, _ := http.NewRequest("", "", nil)
handler := ContextHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("success\n"))
}))
handler.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("response code was expected to be 200, got %d", w.Code)
}
if w.Body.String() != "success\n" {
t.Errorf("the response %q was expected to be \"success\n\"", w.Body.String())
}
})
}