github.com/ks888/tgo@v0.0.0-20190130135156-80bf89407292/lib/tracer/tracer_test.go (about) 1 package tracer 2 3 import ( 4 "fmt" 5 "os" 6 "os/exec" 7 "path/filepath" 8 "runtime" 9 "strings" 10 "testing" 11 12 "github.com/ks888/tgo/testutils" 13 ) 14 15 func TestStartStop(t *testing.T) { 16 cmd := exec.Command(testutils.ProgramStartStop) 17 out, _ := cmd.CombinedOutput() 18 19 if strings.Count(string(out), "main.tracedFunc") != 2 { 20 t.Errorf("unexpected output: %s", string(out)) 21 } 22 23 if strings.Count(string(out), "fmt.Println") == 0 { 24 // inlined 25 if strings.Count(string(out), "fmt.Fprintln") != 4 { 26 t.Errorf("unexpected output: %s", string(out)) 27 } 28 } else if strings.Count(string(out), "fmt.Println") != 4 { 29 // not inlined 30 t.Errorf("unexpected output: %s", string(out)) 31 } 32 } 33 34 func TestStart(t *testing.T) { 35 cmd := exec.Command(testutils.ProgramStartOnly) 36 out, _ := cmd.CombinedOutput() 37 38 if strings.Count(string(out), "main.f") != 2 { 39 t.Errorf("unexpected output: %s", string(out)) 40 } 41 } 42 43 func TestRecursiveStartStop(t *testing.T) { 44 cmd := exec.Command(testutils.ProgramRecursiveStartStop) 45 out, _ := cmd.CombinedOutput() 46 47 if strings.Count(string(out), "main.dec") != 6 { 48 t.Errorf("unexpected output: %s", string(out)) 49 } 50 } 51 52 func TestStart_NoTracerBinary(t *testing.T) { 53 origTracerName := tracerProgramName 54 tracerProgramName = "not-exist-tracer" 55 defer func() { tracerProgramName = origTracerName }() 56 57 if err := Start(); err == nil { 58 t.Fatalf("should return error") 59 } 60 } 61 62 func TestMain(m *testing.M) { 63 _, srcFilename, _, _ := runtime.Caller(0) 64 srcDirname := filepath.Dir(srcFilename) 65 outDirname := filepath.Join(srcDirname, "build") 66 _ = os.Mkdir(outDirname, os.FileMode(0700)) // the directory may exist already 67 68 if err := build(filepath.Join(srcDirname, "..", "..", "cmd", "tgo"), filepath.Join(outDirname, "tgo")); err != nil { 69 fmt.Fprintf(os.Stderr, "failed to build: %v\n", err) 70 } 71 72 orgPath := os.Getenv("PATH") 73 os.Setenv("PATH", outDirname+string(os.PathListSeparator)+orgPath) 74 75 exitStatus := m.Run() 76 // the deferred function is not called when os.Exit() 77 _ = os.RemoveAll(outDirname) 78 os.Setenv("PATH", orgPath) 79 os.Exit(exitStatus) 80 } 81 82 func build(mainPkgDirname, pathToBinary string) error { 83 pkgPath, err := filepath.Rel(filepath.Join(os.Getenv("GOPATH"), "src"), mainPkgDirname) 84 if err != nil { 85 return err 86 } 87 88 args := []string{"build", "-o", pathToBinary, pkgPath} 89 if out, err := exec.Command("go", args...).CombinedOutput(); err != nil { 90 return fmt.Errorf("%v\n%s", err, string(out)) 91 } 92 return nil 93 }