gorgonia.org/gorgonia@v0.9.17/x/vm/tracer_test.go (about) 1 package xvm 2 3 import ( 4 "context" 5 "fmt" 6 "reflect" 7 "testing" 8 "time" 9 10 "gorgonia.org/gorgonia" 11 ) 12 13 func ExampleWithTracing() { 14 ctx, tracingC := WithTracing(context.Background()) 15 defer CloseTracing(ctx) 16 go func() { 17 for t := range tracingC { 18 fmt.Println(t) 19 } 20 }() 21 g := gorgonia.NewGraph() 22 // add operations etc... 23 machine := NewMachine(g) 24 defer machine.Close() 25 machine.Run(ctx) 26 } 27 28 func TestWithTracing(t *testing.T) { 29 ctx, c := WithTracing(context.Background()) 30 cn := ctx.Value(globalTracerContextKey) 31 if cn == nil { 32 t.Fail() 33 } 34 if cn.(chan Trace) != c { 35 t.Fail() 36 } 37 } 38 39 func Test_extractTracingChannel(t *testing.T) { 40 ctx, _ := WithTracing(context.Background()) 41 c := ctx.Value(globalTracerContextKey).(chan Trace) 42 type args struct { 43 ctx context.Context 44 } 45 tests := []struct { 46 name string 47 args args 48 want chan<- Trace 49 }{ 50 { 51 "nil", 52 args{ 53 context.Background(), 54 }, 55 nil, 56 }, 57 { 58 "ok", 59 args{ 60 ctx, 61 }, 62 c, 63 }, 64 } 65 for _, tt := range tests { 66 t.Run(tt.name, func(t *testing.T) { 67 if got := extractTracingChannel(tt.args.ctx); !reflect.DeepEqual(got, tt.want) { 68 t.Errorf("extractTracingChannel() = %v, want %v", got, tt.want) 69 } 70 }) 71 } 72 } 73 74 func TestCloseTracing(t *testing.T) { 75 ctx, _ := WithTracing(context.Background()) 76 type args struct { 77 ctx context.Context 78 } 79 tests := []struct { 80 name string 81 args args 82 }{ 83 { 84 "no trace", 85 args{ 86 context.Background(), 87 }, 88 }, 89 { 90 "trace", 91 args{ 92 ctx, 93 }, 94 }, 95 } 96 for _, tt := range tests { 97 t.Run(tt.name, func(t *testing.T) { 98 CloseTracing(tt.args.ctx) 99 }) 100 } 101 } 102 103 func Test_trace(t *testing.T) { 104 now = func() time.Time { return time.Date(1977, time.September, 10, 10, 25, 00, 00, time.UTC) } 105 ctx, c := WithTracing(context.Background()) 106 defer CloseTracing(ctx) 107 go func() { 108 for range c { 109 } 110 }() 111 type args struct { 112 ctx context.Context 113 t *Trace 114 n *node 115 state stateFn 116 } 117 tests := []struct { 118 name string 119 args args 120 want *Trace 121 }{ 122 { 123 "no tracing context", 124 args{ 125 context.Background(), 126 nil, 127 nil, 128 nil, 129 }, 130 nil, 131 }, 132 { 133 "Context with nil trace", 134 args{ 135 ctx, 136 nil, 137 &node{ 138 id: 0, 139 }, 140 nil, 141 }, 142 &Trace{ 143 ID: 0, 144 Start: now(), 145 }, 146 }, 147 { 148 "Context existing trace", 149 args{ 150 ctx, 151 &Trace{ 152 ID: 1, 153 Start: now(), 154 }, 155 nil, 156 nil, 157 }, 158 &Trace{ 159 ID: 1, 160 Start: now(), 161 End: now(), 162 }, 163 }, 164 } 165 for _, tt := range tests { 166 t.Run(tt.name, func(t *testing.T) { 167 if got := trace(tt.args.ctx, tt.args.t, tt.args.n, tt.args.state); !reflect.DeepEqual(got, tt.want) { 168 t.Errorf("trace() = %v, want %v", got, tt.want) 169 } 170 }) 171 } 172 }