-
Notifications
You must be signed in to change notification settings - Fork 79
/
json_logger_test.go
99 lines (84 loc) · 2.21 KB
/
json_logger_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package tigertonic
import (
"bytes"
"encoding/json"
"log"
"net/http"
"net/url"
"reflect"
"strings"
"testing"
)
func TestJSONLogger(t *testing.T) {
w := &testResponseWriter{}
r, _ := http.NewRequest(
"POST",
"http://example.com/foo?bar=baz",
bytes.NewBufferString(`{"foo":"bar"}`),
)
r.Header.Set("Accept", "application/json")
r.Header.Set("Content-Type", "application/json")
logger := JSONLogged(Marshaled(func(u *url.URL, h http.Header, rq *testRequest) (int, http.Header, *testResponse, error) {
return http.StatusOK, nil, &testResponse{"bar"}, nil
}), nil)
logger.RequestIDCreator = func(r *http.Request) RequestID {
return "request-id"
}
b := &bytes.Buffer{}
logger.Logger = log.New(b, "", 0)
logger.ServeHTTP(w, r)
var m jsonLog
err := json.Unmarshal(b.Bytes()[6:], &m)
if err != nil {
t.Fatal(err)
}
expected := jsonLog{
Message: "POST /foo?bar=baz HTTP/1.1\nHTTP/1.1 200 OK",
Type: "http",
RequestID: "request-id",
Duration: 0,
HTTP: jsonLogHTTP{
Request: jsonLogHTTPRequest{
Body: "{\"foo\":\"bar\"}",
Header: map[string]string{
"accept": "application/json",
"content-type": "application/json",
},
Method: "POST",
Path: "/foo?bar=baz",
},
Response: jsonLogHTTPResponse{
Body: "{\"foo\":\"bar\"}\n",
Header: map[string]string{
"content-type": "application/json",
},
StatusCode: 200,
StatusText: "OK",
},
Version: "1.1",
},
}
if reflect.DeepEqual(expected, m) == false {
t.Fatalf("Log object was incorrect\nExpected\n%+v\nGot\n%+v", expected, m)
}
}
func TestJSONLoggerRedactor(t *testing.T) {
w := &testResponseWriter{}
r, _ := http.NewRequest("GET", "http://example.com/foo", nil)
r.Header.Set("Accept", "application/json")
logger := JSONLogged(Marshaled(func(u *url.URL, h http.Header, rq *testRequest) (int, http.Header, *testResponse, error) {
return http.StatusOK, nil, &testResponse{"SECRET"}, nil
}), func(s string) string {
return strings.Replace(s, "SECRET", "REDACTED", -1)
})
b := &bytes.Buffer{}
logger.Logger = log.New(b, "", 0)
logger.ServeHTTP(w, r)
s := b.String()
if strings.Contains(s, "SECRET") {
t.Fatal(s)
}
if !strings.Contains(s, "REDACTED") {
t.Fatal(s)
}
}