-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathxhandler_test.go
66 lines (55 loc) · 1.4 KB
/
xhandler_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
package xhandler
import (
"log"
"net/http"
"net/http/httptest"
"testing"
"time"
"context"
"github.com/stretchr/testify/assert"
)
type handler struct{}
type key int
const contextKey key = 0
func newContext(ctx context.Context, value string) context.Context {
return context.WithValue(ctx, contextKey, value)
}
func fromContext(ctx context.Context) (string, bool) {
value, ok := ctx.Value(contextKey).(string)
return value, ok
}
func (h handler) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// Leave other go routines a chance to run
time.Sleep(time.Nanosecond)
value, _ := fromContext(ctx)
if _, ok := ctx.Deadline(); ok {
value += " with deadline"
}
if ctx.Err() == context.Canceled {
value += " canceled"
}
w.Write([]byte(value))
}
func TestHandle(t *testing.T) {
ctx := context.WithValue(context.Background(), contextKey, "value")
h := New(ctx, &handler{})
w := httptest.NewRecorder()
r, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
log.Fatal(err)
}
h.ServeHTTP(w, r)
assert.Equal(t, "value", w.Body.String())
}
func TestHandlerFunc(t *testing.T) {
ok := false
xh := HandlerFuncC(func(context.Context, http.ResponseWriter, *http.Request) {
ok = true
})
r, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
log.Fatal(err)
}
xh.ServeHTTPC(context.Background(), nil, r)
assert.True(t, ok)
}