Skip to content

Commit

Permalink
Significantly up coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
nhooyr committed Dec 6, 2019
1 parent 6ac3e93 commit afbd64d
Show file tree
Hide file tree
Showing 7 changed files with 179 additions and 40 deletions.
6 changes: 6 additions & 0 deletions internal/assert/assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,9 @@ func ErrorContains(t testing.TB, err error, sub, name string) {
t.Fatalf("error string %q from %v does not contain %q", errs, name, sub)
}
}

// True asserts true == act.
func True(t testing.TB, act interface{}, name string) {
t.Helper()
Equal(t, true, act, name)
}
4 changes: 1 addition & 3 deletions internal/humanfmt/humanfmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,8 @@ func levelColor(level slog.Level) color.Attribute {
return color.FgYellow
case slog.LevelError:
return color.FgRed
case slog.LevelCritical, slog.LevelFatal:
return color.FgHiRed
default:
panic("humanfmt: unexpected level: " + string(level))
return color.FgHiRed
}
}

Expand Down
21 changes: 17 additions & 4 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ func (m Map) MarshalJSON() ([]byte, error) {
return b.Bytes(), nil
}

// JSON ensures the value is logged via json.Marshal even
// in the presence of the fmt.Stringer and error interfaces.
func JSON(v interface{}) interface{} {
return jsonVal{v: v}
}

type jsonVal struct {
v interface{}
}

var _ json.Marshaler = jsonVal{}

// MarshalJSON implements json.Marshaler.
func (v jsonVal) MarshalJSON() ([]byte, error) {
return json.Marshal(v.v)
}

func marshalArray(a []interface{}) []byte {
b := &bytes.Buffer{}
b.WriteByte('[')
Expand Down Expand Up @@ -97,10 +114,6 @@ type wrapError struct {
Loc string `json:"loc"`
}

func (e wrapError) LogValue() interface{} {
return JSON{e}
}

type xerrorPrinter struct {
e wrapError
}
Expand Down
29 changes: 22 additions & 7 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import (
"cdr.dev/slog/internal/assert"
)

var _, mapTestFile, _, _ = runtime.Caller(0)

func TestMap(t *testing.T) {
t.Parallel()

Expand All @@ -25,14 +27,14 @@ func TestMap(t *testing.T) {
}

t.Run("JSON", func(t *testing.T) {
t.Parallel()

type Meow struct {
Wow string `json:"meow"`
Something int `json:",omitempty"`
Ignored bool `json:"-"`
}

_, file, _, _ := runtime.Caller(0)

test(t, slog.M(
slog.Error(
xerrors.Errorf("wrap1: %w",
Expand All @@ -59,12 +61,12 @@ func TestMap(t *testing.T) {
{
"msg": "wrap1",
"fun": "cdr.dev/slog_test.TestMap.func2",
"loc": "`+file+`:38"
"loc": "`+mapTestFile+`:40"
},
{
"msg": "wrap2",
"fun": "cdr.dev/slog_test.TestMap.func2",
"loc": "`+file+`:39"
"loc": "`+mapTestFile+`:41"
},
"EOF"
],
Expand All @@ -78,8 +80,9 @@ func TestMap(t *testing.T) {
})

t.Run("badJSON", func(t *testing.T) {
_, file, _, _ := runtime.Caller(0)
file = strings.Replace(file, "_test", "", 1)
t.Parallel()

mapTestFile = strings.Replace(mapTestFile, "_test", "", 1)

test(t, slog.M(
slog.F("meow", indentJSON),
Expand All @@ -89,7 +92,7 @@ func TestMap(t *testing.T) {
{
"msg": "failed to marshal to JSON",
"fun": "cdr.dev/slog.encode",
"loc": "`+file+`:67"
"loc": "`+mapTestFile+`:84"
},
"json: unsupported type: func(*testing.T, string) string"
],
Expand Down Expand Up @@ -124,6 +127,8 @@ func TestMap(t *testing.T) {
})

t.Run("slice", func(t *testing.T) {
t.Parallel()

test(t, slog.M(
slog.F("meow", []string{
"1",
Expand All @@ -138,6 +143,16 @@ func TestMap(t *testing.T) {
]
}`)
})

t.Run("forceJSON", func(t *testing.T) {
t.Parallel()

test(t, slog.M(
slog.F("error", slog.JSON(io.EOF)),
), `{
"error": {}
}`)
})
}

func indentJSON(t *testing.T, j string) string {
Expand Down
25 changes: 2 additions & 23 deletions slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ package slog // import "cdr.dev/slog"

import (
"context"
"encoding/json"
"fmt"
"os"
"runtime"
Expand Down Expand Up @@ -111,7 +110,7 @@ var levelStrings = map[Level]string{
func (l Level) String() string {
s, ok := levelStrings[l]
if !ok {
return fmt.Sprintf(`"unknown_level: %v"`, int(l))
return fmt.Sprintf("slog.Level(%v)", int(l))
}
return s
}
Expand Down Expand Up @@ -309,10 +308,6 @@ func (ent SinkEntry) fillLoc(skip int) SinkEntry {
// Skip two extra frames to account for this function
// and runtime.Callers itself.
n := runtime.Callers(skip+2, pc[:])
if n == 0 {
panic("slog: zero callers found")
}

frames := runtime.CallersFrames(pc[:n])
first, more := frames.Next()
if !more {
Expand Down Expand Up @@ -344,10 +339,7 @@ func (s sink) entry(ctx context.Context, ent SinkEntry) SinkEntry {
}

func location(skip int) (file string, line int, fn string) {
pc, file, line, ok := runtime.Caller(skip + 1)
if !ok {
panic("slog: zero callers found")
}
pc, file, line, _ := runtime.Caller(skip + 1)
f := runtime.FuncForPC(pc)
return file, line, f.Name()
}
Expand All @@ -360,16 +352,3 @@ func Tee(ls ...Logger) Logger {
}
return l
}

// JSON ensures the value is logged via json.Marshal even
// in the presence of the fmt.Stringer and error interfaces.
type JSON struct {
V interface{}
}

var _ json.Marshaler = JSON{}

// MarshalJSON implements json.Marshaler.
func (v JSON) MarshalJSON() ([]byte, error) {
return json.Marshal(v.V)
}
130 changes: 130 additions & 0 deletions slog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package slog_test

import (
"context"
"io"
"runtime"
"testing"

"go.opencensus.io/trace"

"cdr.dev/slog"
"cdr.dev/slog/internal/assert"
)

var _, slogTestFile, _, _ = runtime.Caller(0)

type fakeSink struct {
entries []slog.SinkEntry
logEntryErr error

synced bool
syncErr error
}

func (s *fakeSink) LogEntry(_ context.Context, e slog.SinkEntry) error {
s.entries = append(s.entries, e)
return s.logEntryErr
}

func (s *fakeSink) Sync() error {
s.synced = true
return s.syncErr
}

var bg = context.Background()

func TestLogger(t *testing.T) {
t.Parallel()

t.Run("basic", func(t *testing.T) {
t.Parallel()

s1 := &fakeSink{}
s2 := &fakeSink{}
l := slog.Tee(slog.Make(s1), slog.Make(s2))

l.SetLevel(slog.LevelError)

l.Info(bg, "wow", slog.Error(io.EOF))
l.Error(bg, "meow", slog.Error(io.ErrUnexpectedEOF))

assert.True(t, s1.synced, "synced")
assert.Equal(t, 1, len(s1.entries), "len(entries)")

assert.Equal(t, s1, s2, "sinks")
})

t.Run("helper", func(t *testing.T) {
t.Parallel()

s := &fakeSink{}
l := slog.Make(s)
h := func(ctx context.Context) {
slog.Helper()
l.Debug(ctx, "logging in helper")
}

ctx := slog.Context(bg, slog.F(
"ctx", 1024),
)
h(ctx)

assert.Equal(t, slog.SinkEntry{
Time: s.entries[0].Time,

Level: slog.LevelDebug,
Message: "logging in helper",

File: slogTestFile,
Func: "cdr.dev/slog_test.TestLogger.func2",
Line: 71,

Fields: slog.M(
slog.F("ctx", 1024),
),
}, s.entries[0], "entry")
})

t.Run("entry", func(t *testing.T) {
t.Parallel()

s := &fakeSink{}
l := slog.Make(s)
l = l.Named("hello")
l = l.Named("hello2")

ctx, span := trace.StartSpan(bg, "trace")
ctx = slog.Context(ctx, slog.F("ctx", io.EOF))
l = l.With(slog.F("with", 2))

l.Info(ctx, "meow", slog.F("hi", "xd"))

assert.Equal(t, slog.SinkEntry{
Time: s.entries[0].Time,

Level: slog.LevelInfo,
Message: "meow",

LoggerName: "hello.hello2",

File: slogTestFile,
Func: "cdr.dev/slog_test.TestLogger.func3",
Line: 101,

SpanContext: span.SpanContext(),

Fields: slog.M(
slog.F("with", 2),
slog.F("ctx", io.EOF),
slog.F("hi", "xd"),
),
}, s.entries[0], "entry")
})
}

func TestLevel_String(t *testing.T) {
t.Parallel()

assert.Equal(t, "slog.Level(12)", slog.Level(12).String(), "level string")
}
4 changes: 1 addition & 3 deletions sloggers/slogstackdriver/slogstackdriver.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,8 @@ func sev(level slog.Level) logpbtype.LogSeverity {
return logpbtype.LogSeverity_WARNING
case slog.LevelError:
return logpbtype.LogSeverity_ERROR
case slog.LevelCritical, slog.LevelFatal:
return logpbtype.LogSeverity_CRITICAL
default:
panic(fmt.Sprintf("slogstackdriver: unexpected level %v", level))
return logpbtype.LogSeverity_CRITICAL
}
}

Expand Down

0 comments on commit afbd64d

Please sign in to comment.