github.com/pingcap/br@v5.3.0-alpha.0.20220125034240-ec59c7b6ce30+incompatible/pkg/trace/tracing_test.go (about) 1 // Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0. 2 3 package trace 4 5 import ( 6 "context" 7 "os" 8 "path" 9 "testing" 10 "time" 11 12 "github.com/opentracing/opentracing-go" 13 . "github.com/pingcap/check" 14 ) 15 16 type testTracingSuite struct{} 17 18 var _ = Suite(&testTracingSuite{}) 19 20 func TestT(t *testing.T) { 21 TestingT(t) 22 } 23 24 func jobA(ctx context.Context) { 25 if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil { 26 span1 := span.Tracer().StartSpan("jobA", opentracing.ChildOf(span.Context())) 27 defer span1.Finish() 28 ctx = opentracing.ContextWithSpan(ctx, span1) 29 } 30 jobB(ctx) 31 time.Sleep(time.Second) 32 } 33 34 func jobB(ctx context.Context) { 35 if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil { 36 span1 := span.Tracer().StartSpan("jobB", opentracing.ChildOf(span.Context())) 37 defer span1.Finish() 38 } 39 time.Sleep(time.Second) 40 } 41 42 func (t *testTracingSuite) TestSpan(c *C) { 43 filename := path.Join(c.MkDir(), "br.trace") 44 getTraceFileName = func() string { 45 return filename 46 } 47 defer func() { 48 getTraceFileName = timestampTraceFileName 49 }() 50 ctx, store := TracerStartSpan(context.Background()) 51 jobA(ctx) 52 TracerFinishSpan(ctx, store) 53 content, err := os.ReadFile(filename) 54 c.Assert(err, IsNil) 55 s := string(content) 56 // possible result: 57 // "jobA 18:00:30.745723 2.009301253s\n" 58 // " └─jobB 18:00:30.745724 1.003791041s\n" 59 c.Assert(s, Matches, `jobA.*2\.[0-9]+s\n └─jobB.*1\.[0-9]+s\n`) 60 }