github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/strace/tracer_test.go (about) 1 // Copyright 2018 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package strace 6 7 import ( 8 "bytes" 9 "context" 10 "os" 11 "os/exec" 12 "testing" 13 "time" 14 15 "github.com/u-root/u-root/pkg/testutil" 16 "github.com/u-root/u-root/pkg/uio/uiotest" 17 ) 18 19 func prepareTestCmd(t *testing.T, cmd string) { 20 // VM environment doesn't have makefiles or whatever. Just skip it. 21 testutil.SkipIfInVMTest(t) 22 23 if _, err := os.Stat(cmd); !os.IsNotExist(err) { 24 if err != nil { 25 t.Fatalf("Failed to find test program %q: %v", cmd, err) 26 } 27 return 28 } 29 30 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) 31 defer cancel() 32 w := uiotest.TestLineWriter(t, "make all") 33 34 c := exec.CommandContext(ctx, "make", "all") 35 c.Stdout = w 36 c.Stderr = w 37 c.Dir = "./test" 38 if err := c.Run(); err != nil { 39 t.Fatalf("make failed: %v", err) 40 } 41 } 42 43 func runAndCollectTrace(t *testing.T, cmd *exec.Cmd) []*TraceRecord { 44 // Write strace logs to t.Logf. 45 w := uiotest.TestLineWriter(t, "") 46 traceChan := make(chan *TraceRecord) 47 done := make(chan error, 1) 48 49 go func() { 50 done <- Trace(cmd, PrintTraces(w), RecordTraces(traceChan)) 51 close(traceChan) 52 }() 53 54 var events []*TraceRecord 55 for r := range traceChan { 56 events = append(events, r) 57 } 58 59 if err := <-done; err != nil { 60 if os.IsNotExist(err) { 61 t.Errorf("Trace exited with error -- did you compile the test programs? (cd ./test && make all): %v", err) 62 } else { 63 t.Errorf("Trace exited with error: %v", err) 64 } 65 } 66 return events 67 } 68 69 func TestSingleThreaded(t *testing.T) { 70 prepareTestCmd(t, "./test/hello") 71 72 var b bytes.Buffer 73 cmd := exec.Command("./test/hello") 74 cmd.Stdout = &b 75 76 runAndCollectTrace(t, cmd) 77 } 78 79 func TestMultiProcess(t *testing.T) { 80 prepareTestCmd(t, "./test/fork") 81 82 var b bytes.Buffer 83 cmd := exec.Command("./test/fork") 84 cmd.Stdout = &b 85 86 runAndCollectTrace(t, cmd) 87 }