Skip to content

Commit

Permalink
Add unit tests for klogr Info function
Browse files Browse the repository at this point in the history
  • Loading branch information
munnerz committed Feb 25, 2019
1 parent 8145543 commit 8d8f7b5
Showing 1 changed file with 91 additions and 0 deletions.
91 changes: 91 additions & 0 deletions klogr/klogr_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package klogr

import (
"bytes"
"flag"
"testing"

"k8s.io/klog"

"github.com/go-logr/logr"
)

func TestInfo(t *testing.T) {
klog.InitFlags(nil)
flag.CommandLine.Set("v", "10")
flag.CommandLine.Set("skip_headers", "true")
flag.CommandLine.Set("logtostderr", "false")
flag.CommandLine.Set("alsologtostderr", "false")
flag.Parse()

tests := map[string]struct {
klogr logr.InfoLogger
text string
keysAndValues []interface{}
expectedOutput string
}{
"should log with values passed to keysAndValues": {
klogr: New().V(0),
text: "test",
keysAndValues: []interface{}{"akey", "avalue"},
expectedOutput: ` "level"=0 "msg"="test" "akey"="avalue"
`,
},
"should print duplicate keys with the same value": {
klogr: New().V(0),
text: "test",
keysAndValues: []interface{}{"akey", "avalue", "akey", "avalue"},
expectedOutput: ` "level"=0 "msg"="test" "akey"="avalue" "akey"="avalue"
`,
},
"should print duplicate keys with different values when all values are passed to Info": {
klogr: New().V(0),
text: "test",
keysAndValues: []interface{}{"akey", "avalue", "akey", "avalue2"},
expectedOutput: ` "level"=0 "msg"="test" "akey"="avalue" "akey"="avalue2"
`,
},
"should print duplicate keys with the same value when one is set on logger": {
klogr: New().WithValues("akey", "avalue"),
text: "test",
keysAndValues: []interface{}{"akey", "avalue"},
expectedOutput: ` "level"=0 "msg"="test" "akey"="avalue" "akey"="avalue"
`,
},
"should print duplicate keys with different values when one is set on logger": {
klogr: New().WithValues("akey", "avalue"),
text: "test",
keysAndValues: []interface{}{"akey", "avalue2"},
expectedOutput: ` "level"=0 "msg"="test" "akey"="avalue" "akey"="avalue2"
`,
},
"should print different log level if set": {
klogr: New().V(4),
text: "test",
expectedOutput: ` "level"=4 "msg"="test"
`,
},
}

for n, test := range tests {
t.Run(n, func(t *testing.T) {
klogr := test.klogr
if klogr == nil {
klogr = New()
}

// hijack the klog output
tmpWriteBuffer := bytes.NewBuffer(nil)
klog.SetOutput(tmpWriteBuffer)

klogr.Info(test.text, test.keysAndValues...)
// call Flush to ensure the text isn't still buffered
klog.Flush()

actual := tmpWriteBuffer.String()
if actual != test.expectedOutput {
t.Errorf("expected %q did not match actual %q", test.expectedOutput, actual)
}
})
}
}

0 comments on commit 8d8f7b5

Please sign in to comment.