-
Notifications
You must be signed in to change notification settings - Fork 11
/
http_test.go
75 lines (65 loc) · 1.75 KB
/
http_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
package debug
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"goa.design/clue/log"
)
func TestHTTP(t *testing.T) {
// Create log context
var buf bytes.Buffer
ctx := log.Context(context.Background(),
log.WithOutput(&buf),
log.WithFormat(logKeyValsOnly))
log.FlushAndDisableBuffering(ctx)
// Create HTTP handler
mux := http.NewServeMux()
var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
log.Info(r.Context(), log.KV{K: "test", V: "info"})
log.Debug(r.Context(), log.KV{K: "test", V: "debug"})
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK")) // nolint: errcheck
})
// Mount debug handler and log middleware
MountDebugLogEnabler(mux)
handler = HTTP()(handler)
handler = log.HTTP(ctx,
log.WithDisableRequestLogging(),
log.WithDisableRequestID())(handler)
// Start test server
mux.Handle("/", handler)
ts := httptest.NewServer(mux)
defer ts.Close()
steps := []struct {
name string
on bool
off bool
wantLog string
}{
{"start", false, false, "test=info "},
{"turn debug logs on", true, false, "test=info test=debug "},
{"with debug logs on", false, false, "test=info test=debug "},
{"turn debug logs off", false, true, "test=info "},
{"with debug logs off", false, false, "test=info "},
}
for _, step := range steps {
if step.on {
makeRequest(t, ts.URL+"/debug?debug-logs=on")
}
if step.off {
makeRequest(t, ts.URL+"/debug?debug-logs=off")
}
status, resp := makeRequest(t, ts.URL)
assert.Equal(t, http.StatusOK, status)
assert.Equal(t, "OK", resp)
assert.Equal(t, step.wantLog, buf.String())
buf.Reset()
}
}