...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package logging_test
16
17 import (
18 "bytes"
19 "encoding/json"
20 "testing"
21
22 "github.com/GoogleCloudPlatform/k8s-config-connector/operator/pkg/logging"
23 "github.com/google/go-cmp/cmp"
24 )
25
26 type ExampleError struct{}
27
28 func (e *ExampleError) Error() string {
29 return "ExampleError"
30 }
31
32
33
34 func TestBuildLoggerFormat(t *testing.T) {
35 var buffer bytes.Buffer
36 logger := logging.BuildLogger(&buffer)
37 inputInfo := "testLoggingFormat"
38 logger.Info(inputInfo)
39 logger.Error(&ExampleError{}, "test")
40 wantList := [...]map[string]interface{}{
41 map[string]interface{}{
42 "msg": inputInfo,
43 "severity": "info",
44 },
45 map[string]interface{}{
46 "error": "ExampleError",
47 "msg": "test",
48 "severity": "error",
49 },
50 }
51 for _, want := range wantList {
52 severity := want["severity"].(string)
53 t.Run(severity, func(t *testing.T) {
54 loggedLine, err := buffer.ReadString('\n')
55 if err != nil {
56 t.Fatalf("ReadString('\n') failed: %s", err)
57 }
58 var got map[string]interface{}
59 json.Unmarshal([]byte(loggedLine), &got)
60 if _, ok := got["timestamp"]; !ok {
61 t.Fatalf("the log message %v doesn't contain `timestamp`", got)
62 }
63 delete(got, "timestamp")
64 if diff := cmp.Diff(want, got); diff != "" {
65 t.Fatalf("logger %s returned unexpected diff (-want +got): \n%s", severity, diff)
66 }
67 })
68 }
69 }
70
View as plain text