github.com/thanos-io/thanos@v0.32.5/internal/cortex/util/spanlogger/spanlogger_test.go (about) 1 // Copyright (c) The Cortex Authors. 2 // Licensed under the Apache License 2.0. 3 4 package spanlogger 5 6 import ( 7 "context" 8 "testing" 9 10 "github.com/go-kit/log" 11 "github.com/opentracing/opentracing-go" 12 "github.com/opentracing/opentracing-go/mocktracer" 13 "github.com/pkg/errors" 14 "github.com/stretchr/testify/require" 15 "github.com/weaveworks/common/user" 16 ) 17 18 func TestSpanLogger_Log(t *testing.T) { 19 span, ctx := New(context.Background(), "test", "bar") 20 _ = span.Log("foo") 21 newSpan := FromContext(ctx) 22 require.Equal(t, span.Span, newSpan.Span) 23 _ = newSpan.Log("bar") 24 noSpan := FromContext(context.Background()) 25 _ = noSpan.Log("foo") 26 require.Error(t, noSpan.Error(errors.New("err"))) 27 require.NoError(t, noSpan.Error(nil)) 28 } 29 30 func TestSpanLogger_CustomLogger(t *testing.T) { 31 var logged [][]interface{} 32 var logger funcLogger = func(keyvals ...interface{}) error { 33 logged = append(logged, keyvals) 34 return nil 35 } 36 span, ctx := NewWithLogger(context.Background(), logger, "test") 37 _ = span.Log("msg", "original spanlogger") 38 39 span = FromContextWithFallback(ctx, log.NewNopLogger()) 40 _ = span.Log("msg", "restored spanlogger") 41 42 span = FromContextWithFallback(context.Background(), logger) 43 _ = span.Log("msg", "fallback spanlogger") 44 45 expect := [][]interface{}{ 46 {"method", "test", "msg", "original spanlogger"}, 47 {"msg", "restored spanlogger"}, 48 {"msg", "fallback spanlogger"}, 49 } 50 require.Equal(t, expect, logged) 51 } 52 53 func TestSpanCreatedWithTenantTag(t *testing.T) { 54 mockSpan := createSpan(user.InjectOrgID(context.Background(), "team-a")) 55 56 require.Equal(t, []string{"team-a"}, mockSpan.Tag(TenantIDTagName)) 57 } 58 59 func TestSpanCreatedWithoutTenantTag(t *testing.T) { 60 mockSpan := createSpan(context.Background()) 61 62 _, exist := mockSpan.Tags()[TenantIDTagName] 63 require.False(t, exist) 64 } 65 66 func createSpan(ctx context.Context) *mocktracer.MockSpan { 67 mockTracer := mocktracer.New() 68 opentracing.SetGlobalTracer(mockTracer) 69 70 logger, _ := New(ctx, "name") 71 return logger.Span.(*mocktracer.MockSpan) 72 } 73 74 type funcLogger func(keyvals ...interface{}) error 75 76 func (f funcLogger) Log(keyvals ...interface{}) error { 77 return f(keyvals...) 78 }