1
2
3
4
5 package trace_test
6
7 import (
8 "bytes"
9 "flag"
10 "os"
11 . "runtime/trace"
12 "testing"
13 "time"
14 )
15
16 var saveTraces = flag.Bool("savetraces", false, "save traces collected by tests")
17
18 func TestTraceStartStop(t *testing.T) {
19 if IsEnabled() {
20 t.Skip("skipping because -test.trace is set")
21 }
22 buf := new(bytes.Buffer)
23 if err := Start(buf); err != nil {
24 t.Fatalf("failed to start tracing: %v", err)
25 }
26 Stop()
27 size := buf.Len()
28 if size == 0 {
29 t.Fatalf("trace is empty")
30 }
31 time.Sleep(100 * time.Millisecond)
32 if size != buf.Len() {
33 t.Fatalf("trace writes after stop: %v -> %v", size, buf.Len())
34 }
35 saveTrace(t, buf, "TestTraceStartStop")
36 }
37
38 func TestTraceDoubleStart(t *testing.T) {
39 if IsEnabled() {
40 t.Skip("skipping because -test.trace is set")
41 }
42 Stop()
43 buf := new(bytes.Buffer)
44 if err := Start(buf); err != nil {
45 t.Fatalf("failed to start tracing: %v", err)
46 }
47 if err := Start(buf); err == nil {
48 t.Fatalf("succeed to start tracing second time")
49 }
50 Stop()
51 Stop()
52 }
53
54 func saveTrace(t *testing.T, buf *bytes.Buffer, name string) {
55 if !*saveTraces {
56 return
57 }
58 if err := os.WriteFile(name+".trace", buf.Bytes(), 0600); err != nil {
59 t.Errorf("failed to write trace file: %s", err)
60 }
61 }
62
View as plain text