Skip to content
This repository has been archived by the owner on Apr 22, 2024. It is now read-only.

Commit

Permalink
add more tests
Browse files Browse the repository at this point in the history
Signed-off-by: huabing zhao <[email protected]>
  • Loading branch information
zhaohuabing committed Feb 28, 2024
1 parent 01e9b78 commit 310ed12
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/logr.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (

var _ logr.LogSink = (*logrAdapter)(nil)

const debugLevelThreshold = 3
const debugLevelThreshold = 5

// logrAdapter is a type that adapts the log.Logger interface so it can be used with our loggers
type logrAdapter struct {
Expand Down
80 changes: 80 additions & 0 deletions internal/logr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@
package internal

import (
"errors"
"io"
"os"
"testing"

"github.com/go-logr/logr"
"github.com/stretchr/testify/require"
"github.com/tetratelabs/log"
"github.com/tetratelabs/telemetry"
)

func TestWithValues(t *testing.T) {
Expand All @@ -28,3 +33,78 @@ func TestWithValues(t *testing.T) {

require.Equal(t, map[string]interface{}{"one": 1, "two": 2, "three": "(MISSING)"}, a.(*logrAdapter).kvs)
}

func TestWithName(t *testing.T) {
var a logr.LogSink = &logrAdapter{}
n := a.WithName("test")

require.Equal(t, a, n)
}

func TestEnable(t *testing.T) {
logger := log.New()
logger.SetLevel(telemetry.LevelInfo)
a := logrAdapter{
scope: logger,
}
require.False(t, a.Enabled(int(telemetry.LevelDebug)))
require.True(t, a.Enabled(int(telemetry.LevelInfo)))
require.True(t, a.Enabled(int(telemetry.LevelError)))
}

func TestInfo(t *testing.T) {
rescueStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w

logger := log.New()
logger.SetLevel(telemetry.LevelInfo)
a := logrAdapter{
scope: logger,
}

a.Info(0, "test", "one", 1, "two", 2)

_ = w.Close()
out, _ := io.ReadAll(r)
os.Stdout = rescueStdout
require.Contains(t, string(out), "level=info msg=\"test\" one=1 two=2")
}

func TestError(t *testing.T) {
rescueStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w

logger := log.New()
logger.SetLevel(telemetry.LevelError)
a := logrAdapter{
scope: logger,
}

a.Error(errors.New("error"), "test", "one", 1, "two", 2)

_ = w.Close()
out, _ := io.ReadAll(r)
os.Stdout = rescueStdout
require.Contains(t, string(out), "level=error msg=\"test\" one=1 two=2 error=\"error\"")
}

func TestMissingKV(t *testing.T) {
rescueStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w

logger := log.New()
logger.SetLevel(telemetry.LevelInfo)
a := logrAdapter{
scope: logger,
}

a.Info(0, "test", "one", 1, "two")

_ = w.Close()
out, _ := io.ReadAll(r)
os.Stdout = rescueStdout
require.Contains(t, string(out), "level=info msg=\"test\" one=1 two=\"(MISSING)\"")
}

0 comments on commit 310ed12

Please sign in to comment.