1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
package slogcommon
import (
"context"
"log/slog"
"testing"
"github.com/stretchr/testify/assert"
)
type ctxKey string
func TestContextExtractor(t *testing.T) {
tests := map[string]struct {
ctx context.Context
fns []func(ctx context.Context) []slog.Attr
expected []slog.Attr
}{
"NoFunctions": {
ctx: context.Background(),
fns: []func(ctx context.Context) []slog.Attr{},
expected: []slog.Attr{},
},
"SingleFunction": {
ctx: context.Background(),
fns: []func(ctx context.Context) []slog.Attr{
func(ctx context.Context) []slog.Attr {
return []slog.Attr{slog.String("key1", "value1")}
},
},
expected: []slog.Attr{slog.String("key1", "value1")},
},
"MultipleFunctions": {
ctx: context.Background(),
fns: []func(ctx context.Context) []slog.Attr{
func(ctx context.Context) []slog.Attr {
return []slog.Attr{slog.String("key1", "value1")}
},
func(ctx context.Context) []slog.Attr {
return []slog.Attr{slog.String("key2", "value2")}
},
},
expected: []slog.Attr{slog.String("key1", "value1"), slog.String("key2", "value2")},
},
"FunctionWithContext": {
ctx: context.WithValue(context.Background(), ctxKey("userID"), "1234"),
fns: []func(ctx context.Context) []slog.Attr{
func(ctx context.Context) []slog.Attr {
if userID, ok := ctx.Value(ctxKey("userID")).(string); ok {
return []slog.Attr{slog.String("userID", userID)}
}
return []slog.Attr{}
},
},
expected: []slog.Attr{slog.String("userID", "1234")},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
actual := ContextExtractor(tc.ctx, tc.fns)
assert.Equal(t, tc.expected, actual)
})
}
}
|