-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_test.go
72 lines (66 loc) · 1.35 KB
/
middleware_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
package kitty
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"testing"
"github.com/go-kit/kit/log"
)
func newTestLogger(w io.Writer) log.Logger {
return &testLogger{w}
}
type testLogger struct{ w io.Writer }
func (l *testLogger) Log(keyvals ...interface{}) error {
for i := 0; i < len(keyvals); i++ {
if keyvals[i] == "duration" {
i++
continue
}
io.WriteString(l.w, fmt.Sprintf("%v,", keyvals[i]))
}
return nil
}
func TestLogEndpoint(t *testing.T) {
tcs := []struct {
opt LogOption
response interface{}
err error
log string
}{
{
opt: LogRequest,
response: "foo",
log: `msg,request: bar,`,
},
{
opt: LogResponse,
response: "foo",
log: `status,200,msg,response: foo,`,
},
{
opt: LogErrors,
response: "foo",
log: ``,
},
{
opt: LogErrors,
err: errors.New("bar"),
log: `error,bar,status,500,msg,request: bar,`,
},
}
for _, tc := range tcs {
buf := bytes.NewBuffer([]byte{})
ctx := context.WithValue(context.TODO(), logKey, newTestLogger(buf))
e := func(_ context.Context, _ interface{}) (interface{}, error) {
return tc.response, tc.err
}
LogEndpoint(tc.opt)(e)(ctx, "bar")
logged := strings.TrimSpace(buf.String())
if logged != tc.log {
t.Errorf("Invalid log `%s` should have been `%s`", logged, tc.log)
}
}
}