go.undefinedlabs.com/scopeagent@v0.4.2/instrumentation/process/process_test.go (about) 1 package process 2 3 import ( 4 "fmt" 5 "os" 6 "os/exec" 7 "testing" 8 9 "github.com/opentracing/opentracing-go" 10 11 "go.undefinedlabs.com/scopeagent" 12 "go.undefinedlabs.com/scopeagent/agent" 13 "go.undefinedlabs.com/scopeagent/instrumentation" 14 "go.undefinedlabs.com/scopeagent/tracer" 15 ) 16 17 var r *tracer.InMemorySpanRecorder 18 19 func TestMain(m *testing.M) { 20 // Test tracer 21 r = tracer.NewInMemoryRecorder() 22 os.Exit(scopeagent.Run(m, agent.WithRecorders(r))) 23 } 24 25 func TestProcessContextInjection(t *testing.T) { 26 ctx := scopeagent.GetContextFromTest(t) 27 r.Reset() 28 29 // Create command and inject the context 30 cmd := exec.Command("/usr/local/my-cli", "FirstArg", "SecondArg") 31 cmd.Dir = "/home" 32 pSpan, _ := InjectToCmdWithSpan(ctx, cmd) 33 34 // Simulate process context extraction 35 cCtx, err := Extract(&cmd.Env) 36 if err != nil { 37 panic(err) 38 } 39 cSpan := instrumentation.Tracer().StartSpan(getOperationNameFromArgs(cmd.Args), opentracing.ChildOf(cCtx)) 40 cSpan.Finish() 41 pSpan.Finish() 42 43 spans := r.GetSpans() 44 if len(spans) != 2 { 45 t.Fatalf("there aren't the right number of spans: %d", len(spans)) 46 } 47 48 if spans[0].Operation != "my-cli FirstArg SecondArg " { 49 t.Fatal("the operation name of the Cmd span is invalid") 50 } 51 checkTags(t, spans[1].Tags, map[string]string{ 52 "Args": "[/usr/local/my-cli FirstArg SecondArg]", 53 "Path": "/usr/local/my-cli", 54 "Dir": "/home", 55 }) 56 } 57 58 func checkTags(t *testing.T, tags map[string]interface{}, expected map[string]string) { 59 for eK, eV := range expected { 60 if ok, aV := checkTag(tags, eK, eV); !ok { 61 if aV == "" { 62 t.Fatalf("the tag with key = '%s' was not found in the span tags", eK) 63 } else { 64 t.Fatalf("the tag with key = '%s' has a different value in the span tags. Expected = '%s', Actual = '%s'", eK, eV, aV) 65 } 66 } 67 } 68 } 69 70 func checkTag(tags map[string]interface{}, key string, expectedValue string) (bool, string) { 71 if val, ok := tags[key]; ok { 72 sVal := fmt.Sprint(val) 73 return expectedValue == sVal, sVal 74 } 75 return false, "" 76 }