...
1
16
17 package klog_test
18
19 import (
20 "encoding/json"
21 "fmt"
22 "strings"
23 "testing"
24
25 "k8s.io/klog/v2"
26
27 "github.com/go-logr/logr"
28 )
29
30 func TestFormat(t *testing.T) {
31 obj := config{
32 TypeMeta: TypeMeta{
33 Kind: "config",
34 },
35 RealField: 42,
36 }
37
38 assertEqual(t, "kind is config", obj.String(), "config.String()")
39 assertEqual(t, `{
40 "Kind": "config",
41 "RealField": 42
42 }
43 `, klog.Format(obj).(fmt.Stringer).String(), "Format(config).String()")
44
45 str := fmt.Sprintf("%s", klog.Format(obj).(logr.Marshaler).MarshalLog())
46 if strings.Contains(str, "kind is config") {
47 t.Errorf("fmt.Sprintf called TypeMeta.String for klog.Format(obj).MarshalLog():\n%s", str)
48 }
49
50 structured, err := json.Marshal(klog.Format(obj).(logr.Marshaler).MarshalLog())
51 if err != nil {
52 t.Errorf("JSON Marshal: %v", err)
53 } else {
54 assertEqual(t, `{"Kind":"config","RealField":42}`, string(structured), "json.Marshal(klog.Format(obj).MarshalLog())")
55 }
56 }
57
58 func assertEqual(t *testing.T, expected, actual, what string) {
59 if expected != actual {
60 t.Errorf("%s:\nExpected\n%s\nActual\n%s\n", what, expected, actual)
61 }
62 }
63
64 type TypeMeta struct {
65 Kind string
66 }
67
68 func (t TypeMeta) String() string {
69 return "kind is " + t.Kind
70 }
71
72 func (t TypeMeta) MarshalLog() interface{} {
73 return t.Kind
74 }
75
76 type config struct {
77 TypeMeta
78
79 RealField int
80 }
81
View as plain text