Best Gauge code snippet using reporter.Test
trigger_trace_test.go
Source:trigger_trace_test.go
...11 "github.com/appoptics/appoptics-apm-go/v1/ao/internal/reporter"12 "github.com/stretchr/testify/assert"13)14// trigger trace enabled, unsigned TT request with duplicate custom key: custom-key115func TestTriggerTrace(t *testing.T) {16 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))17 hd := map[string]string{18 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123;custom-key1=hello;custom-key2=world;custom-key1=hi",19 }20 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)21 r.Close(2)22 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{23 // entry event should have no edges24 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{}, Callback: func(n g.Node) {25 assert.Equal(t, true, n.Map["TriggeredTrace"])26 assert.Equal(t, "hello", n.Map["custom-key1"])27 assert.Equal(t, "world", n.Map["custom-key2"])28 assert.Equal(t, "lo:se,check-id:123", n.Map["PDKeys"])29 }},30 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {31 }},32 })33 rHeader := rr.Header()34 assert.EqualValues(t, "trigger-trace=ok", rHeader.Get("X-Trace-Options-Response"))35 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))36}37// trigger trace enabled, no available settings, unsigned TT request38func TestUnsignedTriggerTraceNoSetting(t *testing.T) {39 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.NoSettingST))40 hd := map[string]string{41 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123",42 }43 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)44 r.Close(0)45 rHeader := rr.Header()46 assert.EqualValues(t, "trigger-trace=settings-not-available", rHeader.Get("X-Trace-Options-Response"))47 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))48}49// trigger trace enabled, no available settings, signed TT request50func TestSignedTriggerTraceNoSetting(t *testing.T) {51 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.NoSettingST))52 ts := time.Now().Unix()53 opts := fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;ts=%d", ts)54 hd := map[string]string{55 "X-Trace-Options": opts,56 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),57 }58 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)59 r.Close(0)60 rHeader := rr.Header()61 assert.EqualValues(t, "trigger-trace=settings-not-available;auth=no-signature-key", rHeader.Get("X-Trace-Options-Response"))62 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))63}64// only trigger trace enabled, TT request with custom key/value surrounded by spaces65func TestTriggerTraceWithCustomKey(t *testing.T) {66 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.TriggerTraceOnlyST))67 hd := map[string]string{68 "X-Trace-Options": "trigger-trace; custom-key1 = \tvalue1 ",69 }70 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)71 r.Close(2)72 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{73 // entry event should have no edges74 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{}, Callback: func(n g.Node) {75 assert.Equal(t, "value1", n.Map["custom-key1"])76 assert.Equal(t, true, n.Map["TriggeredTrace"])77 }},78 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {79 }},80 })81 rHeader := rr.Header()82 assert.EqualValues(t, "trigger-trace=ok", rHeader.Get("X-Trace-Options-Response"))83 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))84}85// limited trigger trace token bucket, unsigned TT requests86func TestTriggerTraceRateLimited(t *testing.T) {87 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.LimitedTriggerTraceST))88 hd := map[string]string{89 "X-Trace-Options": "trigger-trace;custom-key1=value1",90 }91 var rrs []*httptest.ResponseRecorder92 numRequests := 593 for i := 0; i < numRequests; i++ {94 rrs = append(rrs, httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd))95 }96 r.Close(0) // Don't check number of events here97 numEvts := len(r.EventBufs)98 assert.True(t, numEvts < 10)99 limited := 0100 triggerTraced := 0101 for _, rr := range rrs {102 rsp := rr.Header().Get("X-Trace-Options-Response")103 if rsp == "trigger-trace=ok" {104 triggerTraced++105 } else if rsp == "trigger-trace=rate-exceeded" {106 limited++107 }108 }109 assert.True(t, (limited+triggerTraced) == numRequests)110 assert.True(t, triggerTraced*2 == numEvts,111 fmt.Sprintf("triggerTraced=%d, numEvts=%d", triggerTraced, numEvts))112}113// limited trigger trace token bucket, signed TT requests114func TestRelaxedTriggerTraceRateLimited(t *testing.T) {115 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.LimitedTriggerTraceST))116 ts := time.Now().Unix()117 opts := fmt.Sprintf("trigger-trace;custom-key1=value1;ts=%d", ts)118 hd := map[string]string{119 "X-Trace-Options": opts,120 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),121 }122 var rrs []*httptest.ResponseRecorder123 numRequests := 5124 for i := 0; i < numRequests; i++ {125 rrs = append(rrs, httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd))126 }127 r.Close(0) // Don't check number of events here128 numEvts := len(r.EventBufs)129 assert.True(t, numEvts < 10)130 limited := 0131 triggerTraced := 0132 for _, rr := range rrs {133 rsp := rr.Header().Get("X-Trace-Options-Response")134 if rsp == "trigger-trace=ok;auth=ok" {135 triggerTraced++136 } else if rsp == "trigger-trace=rate-exceeded;auth=ok" {137 limited++138 }139 }140 assert.True(t, (limited+triggerTraced) == numRequests)141 assert.True(t, triggerTraced*2 == numEvts,142 fmt.Sprintf("triggerTraced=%d, numEvts=%d", triggerTraced, numEvts))143}144// trigger trace: local disabled, remote enabled, unsigned TT request145func TestTriggerTraceLocalDisabledRemoteEnabled(t *testing.T) {146 _ = os.Setenv("APPOPTICS_TRIGGER_TRACE", "false")147 _ = config.Load()148 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))149 hd := map[string]string{150 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123",151 }152 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)153 r.Close(0)154 rHeader := rr.Header()155 assert.EqualValues(t, "trigger-trace=trigger-tracing-disabled", rHeader.Get("X-Trace-Options-Response"))156 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))157 _ = os.Unsetenv("APPOPTICS_TRIGGER_TRACE")158 _ = config.Load()159}160// trigger trace: local enabled, remote disabled, unsigned TT request161func TestTriggerTraceLocalEnabledRemoteDisabled(t *testing.T) {162 _ = os.Setenv("APPOPTICS_TRIGGER_TRACE", "true")163 _ = config.Load()164 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.NoTriggerTraceST))165 hd := map[string]string{166 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123",167 }168 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)169 r.Close(0)170 rHeader := rr.Header()171 assert.EqualValues(t, "trigger-trace=trigger-tracing-disabled", rHeader.Get("X-Trace-Options-Response"))172 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))173 _ = os.Unsetenv("APPOPTICS_TRIGGER_TRACE")174 _ = config.Load()175}176// trigger trace enabled but tracing mode disabled locally177func TestTriggerTraceEnabledTracingModeDisabled(t *testing.T) {178 _ = os.Setenv("APPOPTICS_TRACING_MODE", "disabled")179 _ = config.Load()180 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))181 hd := map[string]string{182 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123",183 }184 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)185 r.Close(0)186 rHeader := rr.Header()187 assert.EqualValues(t, "trigger-trace=tracing-disabled", rHeader.Get("X-Trace-Options-Response"))188 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))189 _ = os.Unsetenv("APPOPTICS_TRACING_MODE")190 _ = config.Load()191}192// trigger trace with service/URL based trace filtering193func TestTriggerTraceWithURLFiltering(t *testing.T) {194 reporter.ReloadURLsConfig([]config.TransactionFilter{195 {"url", `hello`, nil, "disabled"}, // trace is disabled for this URL pattern196 })197 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))198 hd := map[string]string{199 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123",200 }201 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)202 r.Close(0)203 rHeader := rr.Header()204 assert.EqualValues(t, "trigger-trace=tracing-disabled", rHeader.Get("X-Trace-Options-Response"))205 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))206 reporter.ReloadURLsConfig(nil)207}208// no trigger trace enabled, unsigned TT request, invalid key (contains spaces)209func TestNoTriggerTrace(t *testing.T) {210 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))211 hd := map[string]string{212 "X-Trace-Options": "pd keys=lo:se,check-id:123;custom-key1=value1",213 }214 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)215 r.Close(2)216 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{217 // entry event should have no edges218 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{}, Callback: func(n g.Node) {219 assert.Equal(t, "value1", n.Map["custom-key1"])220 assert.Nil(t, n.Map["TriggeredTrace"])221 }},222 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {223 }},224 })225 rHeader := rr.Header()226 assert.EqualValues(t, "trigger-trace=not-requested;ignored=pd keys", rHeader.Get("X-Trace-Options-Response"))227 assert.NotEmpty(t, rHeader.Get("X-Trace"))228}229// trigger trace enabled, invalid trigger trace flag in TT request230func TestNoTriggerTraceInvalidFlag(t *testing.T) {231 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))232 hd := map[string]string{233 "X-Trace-Options": "trigger-trace=1;tigger_trace",234 }235 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)236 r.Close(2)237 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{238 // entry event should have no edges239 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{}, Callback: func(n g.Node) {240 assert.Nil(t, n.Map["TriggeredTrace"])241 }},242 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {243 }},244 })245 rHeader := rr.Header()246 assert.EqualValues(t, "trigger-trace=not-requested;ignored=tigger_trace,trigger-trace", rHeader.Get("X-Trace-Options-Response"))247 assert.NotEmpty(t, rHeader.Get("X-Trace"))248}249// trigger trace enabled, unsigned TT request, invalid custom keys250func TestTriggerTraceInvalidFlag(t *testing.T) {251 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))252 hd := map[string]string{253 "X-Trace-Options": "trigger-trace;foo=bar;app_id=123",254 }255 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)256 r.Close(2)257 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{258 // entry event should have no edges259 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{}, Callback: func(n g.Node) {260 assert.Equal(t, true, n.Map["TriggeredTrace"])261 }},262 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {263 }},264 })265 rHeader := rr.Header()266 assert.EqualValues(t, "trigger-trace=ok;ignored=foo,app_id", rHeader.Get("X-Trace-Options-Response"))267 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))268}269// trigger trace enabled, unsigned TT request with not-traced X-Trace ID (obey the X-Trace ID)270func TestTriggerTraceWithNotTracedXTrace(t *testing.T) {271 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))272 hd := map[string]string{273 "X-Trace-Options": "trigger-trace;not-valid-opt=value2",274 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF00",275 }276 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)277 r.Close(0)278 rHeader := rr.Header()279 assert.EqualValues(t, "trigger-trace=ignored;ignored=not-valid-opt", rHeader.Get("X-Trace-Options-Response"))280 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))281}282// trigger trace enabled, non-TT request, not-traced X-Trace ID283func TestNoTriggerTraceWithNotTracedXTrace(t *testing.T) {284 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))285 hd := map[string]string{286 "X-Trace-Options": "custom-key1=value1;not-valid-opt=value2",287 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF00",288 }289 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)290 r.Close(0)291 rHeader := rr.Header()292 assert.EqualValues(t, "trigger-trace=not-requested;ignored=not-valid-opt", rHeader.Get("X-Trace-Options-Response"))293 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))294}295// non-TT request with traced X-Trace ID296func TestNoTriggerTraceWithXTrace(t *testing.T) {297 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))298 hd := map[string]string{299 "X-Trace-Options": "pd-keys=lo:se,check-id:123;custom-key1=value1;not-valid-opt=value2",300 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF01",301 }302 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)303 r.Close(2)304 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{305 // entry event should have no edges306 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{{"Edge", "2C5EFEA7749039AF"}}, Callback: func(n g.Node) {307 assert.Equal(t, "value1", n.Map["custom-key1"])308 assert.Equal(t, "lo:se,check-id:123", n.Map["PDKeys"])309 assert.Nil(t, n.Map["TriggeredTrace"])310 }},311 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {312 }},313 })314 rHeader := rr.Header()315 assert.EqualValues(t, "trigger-trace=not-requested;ignored=not-valid-opt", rHeader.Get("X-Trace-Options-Response"))316 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))317}318// TT request with traced X-Trace ID319func TestTriggerTraceWithXTrace(t *testing.T) {320 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))321 hd := map[string]string{322 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123;custom-key1=value1;not-valid-opt=value2",323 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF01",324 }325 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)326 r.Close(2)327 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{328 // entry event should have no edges329 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{{"Edge", "2C5EFEA7749039AF"}}, Callback: func(n g.Node) {330 assert.Equal(t, "value1", n.Map["custom-key1"])331 assert.Equal(t, "lo:se,check-id:123", n.Map["PDKeys"])332 assert.Nil(t, n.Map["TriggeredTrace"])333 }},334 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {335 }},336 })337 rHeader := rr.Header()338 assert.EqualValues(t, "trigger-trace=ignored;ignored=not-valid-opt", rHeader.Get("X-Trace-Options-Response"))339 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))340}341// TT request with invalid X-Trace ID (obey trigger trace flag)342func TestTriggerTraceInvalidXTrace(t *testing.T) {343 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))344 hd := map[string]string{345 "X-Trace-Options": "trigger-trace;pd-keys=lo:se,check-id:123",346 "X-Trace": "invalid-value",347 }348 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)349 r.Close(2)350 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{351 // entry event should have no edges352 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{}, Callback: func(n g.Node) {353 assert.Equal(t, true, n.Map["TriggeredTrace"])354 }},355 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {356 }},357 })358 rHeader := rr.Header()359 assert.EqualValues(t, "trigger-trace=ok", rHeader.Get("X-Trace-Options-Response"))360 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))361}362// signed TT request363func TestRelaxedTriggerTrace(t *testing.T) {364 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.RelaxedTriggerTraceOnlyST))365 ts := time.Now().Unix()366 opts := fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;ts=%d", ts)367 hd := map[string]string{368 "X-Trace-Options": opts,369 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),370 }371 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)372 r.Close(2)373 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{374 // entry event should have no edges375 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{}, Callback: func(n g.Node) {376 assert.Equal(t, true, n.Map["TriggeredTrace"])377 }},378 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {379 }},380 })381 rHeader := rr.Header()382 assert.EqualValues(t, "trigger-trace=ok;auth=ok", rHeader.Get("X-Trace-Options-Response"))383 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))384}385// signed TT request with invalid timestamp386func TestRelaxedTriggerTraceTSNotInScope(t *testing.T) {387 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))388 ts := time.Now().Unix() - 60*6389 opts := fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;ts=%d", ts)390 hd := map[string]string{391 "X-Trace-Options": opts,392 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),393 }394 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)395 r.Close(0)396 rHeader := rr.Header()397 assert.EqualValues(t, "auth=bad-timestamp", rHeader.Get("X-Trace-Options-Response"))398 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))399}400// signed TT request with invalid signature401func TestRelaxedTriggerTraceInvalidSignature(t *testing.T) {402 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))403 hd := map[string]string{404 "X-Trace-Options": fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;ts=%d", time.Now().Unix()),405 "X-Trace-Options-Signature": "invalidSignature",406 }407 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)408 r.Close(0)409 rHeader := rr.Header()410 assert.EqualValues(t, "auth=bad-signature", rHeader.Get("X-Trace-Options-Response"))411 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))412}413// signed TT request with traced X-Trace414func TestRelaxedTriggerTraceWithTracedXTrace(t *testing.T) {415 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))416 ts := time.Now().Unix()417 opts := fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;custom-key1=value1;not-valid-opt=value2;ts=%d", ts)418 hd := map[string]string{419 "X-Trace-Options": opts,420 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),421 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF01",422 }423 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)424 r.Close(2)425 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{426 // entry event should have no edges427 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{{"Edge", "2C5EFEA7749039AF"}}, Callback: func(n g.Node) {428 assert.Nil(t, n.Map["TriggeredTrace"])429 assert.Equal(t, "value1", n.Map["custom-key1"])430 assert.Equal(t, "lo:se,check-id:123", n.Map["PDKeys"])431 }},432 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {433 }},434 })435 rHeader := rr.Header()436 assert.EqualValues(t, "trigger-trace=ignored;auth=ok;ignored=not-valid-opt", rHeader.Get("X-Trace-Options-Response"))437 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))438}439// signed TT request with not-traced X-Trace440func TestRelaxedTriggerTraceWithNotTracedXTrace(t *testing.T) {441 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))442 ts := time.Now().Unix()443 opts := fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;custom-key1=value1;not-valid-opt=value2;ts=%d", ts)444 hd := map[string]string{445 "X-Trace-Options": opts,446 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),447 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF00",448 }449 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)450 r.Close(0)451 rHeader := rr.Header()452 assert.EqualValues(t, "trigger-trace=ignored;auth=ok;ignored=not-valid-opt", rHeader.Get("X-Trace-Options-Response"))453 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))454}455// signed TT request with bad timestamp and traced X-Trace456func TestRelaxedTriggerTraceWithBadTsAndTracedXTrace(t *testing.T) {457 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))458 ts := time.Now().Unix() - 360459 opts := fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;custom-key1=value1;not-valid-opt=value2;ts=%d", ts)460 hd := map[string]string{461 "X-Trace-Options": opts,462 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),463 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF01",464 }465 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)466 r.Close(2)467 g.AssertGraph(t, r.EventBufs, 2, g.AssertNodeMap{468 // entry event should have no edges469 {"http.HandlerFunc", "entry"}: {Edges: g.Edges{{"Edge", "2C5EFEA7749039AF"}}, Callback: func(n g.Node) {470 assert.Nil(t, n.Map["TriggeredTrace"])471 }},472 {"http.HandlerFunc", "exit"}: {Edges: g.Edges{{"http.HandlerFunc", "entry"}}, Callback: func(n g.Node) {473 }},474 })475 rHeader := rr.Header()476 assert.EqualValues(t, "trigger-trace=ignored;auth=bad-timestamp", rHeader.Get("X-Trace-Options-Response"))477 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "01"))478}479// signed TT request with bad timestamp and not-traced X-Trace480func TestRelaxedTriggerTraceWithBadTsAndNotTracedXTrace(t *testing.T) {481 r := reporter.SetTestReporter(reporter.TestReporterSettingType(reporter.DefaultST))482 ts := time.Now().Unix() - 360483 opts := fmt.Sprintf("trigger-trace;pd-keys=lo:se,check-id:123;custom-key1=value1;not-valid-opt=value2;ts=%d", ts)484 hd := map[string]string{485 "X-Trace-Options": opts,486 "X-Trace-Options-Signature": reporter.HmacHash([]byte(reporter.TestToken), []byte(opts)),487 "X-Trace": "2B987445277543FF9C151D0CDE6D29B6E21603D5DB2C5EFEA7749039AF00",488 }489 rr := httpTestWithEndpointWithHeaders(handler200, "http://test.com/hello", hd)490 r.Close(0)491 rHeader := rr.Header()492 assert.EqualValues(t, "trigger-trace=ignored;auth=bad-timestamp", rHeader.Get("X-Trace-Options-Response"))493 assert.True(t, strings.HasSuffix(rHeader.Get("X-Trace"), "00"))494}...
test_reporter.go
Source:test_reporter.go
...8 "sync/atomic"9 "time"10 "github.com/appoptics/appoptics-apm-go/v1/ao/internal/metrics"11)12// TestReporter appends reported events to Bufs if ShouldTrace is true.13type TestReporter struct {14 EventBufs [][]byte15 SpanMessages []metrics.SpanMessage16 ShouldTrace bool17 ShouldError bool18 UseSettings bool19 SettingType int20 CaptureMetrics bool21 ErrorEvents map[int]bool // whether to drop an event22 eventCount int6423 done chan int24 wg sync.WaitGroup25 eventChan chan []byte26 spanMsgChan chan metrics.SpanMessage27 Timeout time.Duration28}29const (30 defaultTestReporterTimeout = 2 * time.Second31 TestToken = "TOKEN"32)33var usingTestReporter = false34var oldReporter reporter = &nullReporter{}35// TestReporterOption values may be passed to SetTestReporter.36type TestReporterOption func(*TestReporter)37// TestReporterDisableDefaultSetting disables the default 100% test sampling rate and leaves settings state empty.38func TestReporterDisableDefaultSetting(val bool) TestReporterOption {39 return func(r *TestReporter) {40 if val {41 r.SettingType = NoSettingST42 } else {43 r.SettingType = DefaultST44 }45 }46}47// TestReporterTimeout sets a timeout for the TestReporter to wait before shutting down its writer.48func TestReporterTimeout(timeout time.Duration) TestReporterOption {49 return func(r *TestReporter) { r.Timeout = timeout }50}51func TestReporterSettingType(tp int) TestReporterOption {52 return func(r *TestReporter) { r.SettingType = tp }53}54// TestReporterDisableTracing turns off settings lookup and ensures oboeSampleRequest returns false.55func TestReporterDisableTracing() TestReporterOption {56 return func(r *TestReporter) {57 r.SettingType = NoSettingST58 r.ShouldTrace = false59 r.UseSettings = false60 }61}62// TestReporterShouldTrace sets the first argument of the return value of oboeSampleRequest().63func TestReporterShouldTrace(val bool) TestReporterOption {64 return func(r *TestReporter) {65 r.ShouldTrace = val66 }67}68// TestReporterUseSettings sets whether to look up settings lookup or return the value of r.ShouldTrace.69func TestReporterUseSettings(val bool) TestReporterOption {70 return func(r *TestReporter) { r.UseSettings = val }71}72// SetTestReporter sets and returns a test reporter that captures raw event bytes73// for making assertions about using the graphtest package.74func SetTestReporter(options ...TestReporterOption) *TestReporter {75 r := &TestReporter{76 ShouldTrace: true,77 UseSettings: true,78 Timeout: defaultTestReporterTimeout,79 done: make(chan int),80 eventChan: make(chan []byte),81 spanMsgChan: make(chan metrics.SpanMessage),82 }83 for _, option := range options {84 option(r)85 }86 r.wg.Add(1)87 go r.resultWriter()88 if _, ok := oldReporter.(*nullReporter); ok {89 oldReporter = globalReporter90 }91 globalReporter = r92 usingTestReporter = true93 // start with clean slate94 resetSettings()95 r.updateSetting()96 return r97}98func (r *TestReporter) Flush() error {99 // do nothing100 return nil101}102func (r *TestReporter) SetServiceKey(key string) {103 // do nothing104}105func (r *TestReporter) resultWriter() {106 var numBufs int107 for {108 select {109 case numBufs = <-r.done:110 if len(r.EventBufs)+len(r.SpanMessages) >= numBufs {111 r.wg.Done()112 return113 }114 r.done = nil115 case <-time.After(r.Timeout):116 r.wg.Done()117 return118 case buf := <-r.eventChan:119 r.EventBufs = append(r.EventBufs, buf)120 if r.done == nil && len(r.EventBufs)+len(r.SpanMessages) >= numBufs {121 r.wg.Done()122 return123 }124 case buf := <-r.spanMsgChan:125 r.SpanMessages = append(r.SpanMessages, buf)126 if r.done == nil && len(r.EventBufs)+len(r.SpanMessages) >= numBufs {127 r.wg.Done()128 return129 }130 }131 }132}133// Close stops the test reporter from listening for events; r.EventBufs will no longer be updated and any134// calls to WritePacket() will panic.135func (r *TestReporter) Close(numBufs int) {136 r.done <- numBufs137 // wait for reader goroutine to receive numBufs events, or timeout.138 r.wg.Wait()139 close(r.eventChan)140 received := len(r.EventBufs) + len(r.SpanMessages)141 if received < numBufs {142 log.Printf("# FIX: TestReporter.Close() waited for %d events, got %d", numBufs, received)143 }144 usingTestReporter = false145 if _, ok := oldReporter.(*nullReporter); !ok {146 globalReporter = oldReporter147 oldReporter = &nullReporter{}148 }149}150// Shutdown closes the Test reporter TODO: not supported151func (r *TestReporter) Shutdown(ctx context.Context) error {152 // return r.conn.Close()153 return errors.New("shutdown is not supported by TestReporter")154}155// ShutdownNow closes the Test reporter immediately156func (r *TestReporter) ShutdownNow() error { return nil }157// Closed returns if the reporter is closed or not TODO: not supported158func (r *TestReporter) Closed() bool {159 return false160}161// WaitForReady checks the state of the reporter and may wait for up to the specified162// duration until it becomes ready.163func (r *TestReporter) WaitForReady(ctx context.Context) bool {164 return true165}166func (r *TestReporter) report(ctx *oboeContext, e *event) error {167 if err := prepareEvent(ctx, e); err != nil {168 // don't continue if preparation failed169 return err170 }171 atomic.AddInt64(&r.eventCount, 1)172 if r.ShouldError || // error all events173 (r.ErrorEvents != nil && r.ErrorEvents[(int(r.eventCount)-1)]) { // error certain specified events174 return errors.New("TestReporter error")175 }176 r.eventChan <- (*e).bbuf.GetBuf() // a send to a closed channel panics.177 return nil178}179func (r *TestReporter) reportEvent(ctx *oboeContext, e *event) error {180 return r.report(ctx, e)181}182func (r *TestReporter) reportStatus(ctx *oboeContext, e *event) error {183 return r.report(ctx, e)184}185func (r *TestReporter) reportSpan(span metrics.SpanMessage) error {186 r.spanMsgChan <- span187 return nil188}189func (r *TestReporter) addDefaultSetting() {190 // add default setting with 100% sampling191 updateSetting(int32(TYPE_DEFAULT), "",192 []byte("SAMPLE_START,SAMPLE_THROUGH_ALWAYS,TRIGGER_TRACE"),193 1000000, 120, argsToMap(1000000, 1000000, 1000000, 1000000, 1000000, 1000000, -1, -1, []byte(TestToken)))194}195func (r *TestReporter) addNoTriggerTrace() {196 updateSetting(int32(TYPE_DEFAULT), "",197 []byte("SAMPLE_START,SAMPLE_THROUGH_ALWAYS"),198 1000000, 120, argsToMap(1000000, 1000000, 0, 0, 0, 0, -1, -1, []byte(TestToken)))199}200func (r *TestReporter) addTriggerTraceOnly() {201 updateSetting(int32(TYPE_DEFAULT), "",202 []byte("TRIGGER_TRACE"),203 0, 120, argsToMap(0, 0, 1000000, 1000000, 1000000, 1000000, -1, -1, []byte(TestToken)))204}205func (r *TestReporter) addRelaxedTriggerTraceOnly() {206 updateSetting(int32(TYPE_DEFAULT), "",207 []byte("TRIGGER_TRACE"),208 0, 120, argsToMap(0, 0, 1000000, 1000000, 0, 0, -1, -1, []byte(TestToken)))209}210func (r *TestReporter) addStrictTriggerTraceOnly() {211 updateSetting(int32(TYPE_DEFAULT), "",212 []byte("TRIGGER_TRACE"),213 0, 120, argsToMap(0, 0, 0, 0, 1000000, 1000000, -1, -1, []byte(TestToken)))214}215func (r *TestReporter) addLimitedTriggerTrace() {216 updateSetting(int32(TYPE_DEFAULT), "",217 []byte("SAMPLE_START,SAMPLE_THROUGH_ALWAYS,TRIGGER_TRACE"),218 1000000, 120, argsToMap(1000000, 1000000, 1, 1, 1, 1, -1, -1, []byte(TestToken)))219}220// Setting types221const (222 DefaultST = iota223 NoTriggerTraceST224 TriggerTraceOnlyST225 RelaxedTriggerTraceOnlyST226 StrictTriggerTraceOnlyST227 LimitedTriggerTraceST228 NoSettingST229)230func (r *TestReporter) updateSetting() {231 switch r.SettingType {232 case DefaultST:233 r.addDefaultSetting()234 case NoTriggerTraceST:235 r.addNoTriggerTrace()236 case TriggerTraceOnlyST:237 r.addTriggerTraceOnly()238 case RelaxedTriggerTraceOnlyST:239 r.addRelaxedTriggerTraceOnly()240 case StrictTriggerTraceOnlyST:241 r.addStrictTriggerTraceOnly()242 case LimitedTriggerTraceST:243 r.addLimitedTriggerTrace()244 case NoSettingST:245 // Nothing to do246 default:247 panic("No such setting type.")248 }249}250func (r *TestReporter) CustomSummaryMetric(name string, value float64, opts metrics.MetricOptions) error {251 return nil252}253func (r *TestReporter) CustomIncrementMetric(name string, opts metrics.MetricOptions) error {254 return nil255}...
esreporter_test.go
Source:esreporter_test.go
...20 . "github.com/onsi/ginkgo/v2"21 "github.com/onsi/ginkgo/v2/types"22 . "github.com/onsi/gomega"23)24func TestGardenerESReporter(t *testing.T) {25 RegisterFailHandler(Fail)26 RunSpecs(t, "Gardener ES Reporter Test Suite")27}28const (29 reportFileName = "/tmp/report_test.json"30 indexName = "test-index"31 mockReportSuiteDescription = "mock report suite"32 testCaseName = "[DEFAULT] [REPORT] Should complete successfully"33)34var _ = Describe("processReport tests", func() {35 var (36 reporter *GardenerESReporter37 mockReport Report38 mockContainerHierarchyTexts []string39 suiteDuration float6440 testCaseDuration float6441 )42 BeforeEach(func() {43 reporter = newGardenerESReporter(reportFileName, indexName)44 mockReport.SuiteDescription = mockReportSuiteDescription45 mockContainerHierarchyTexts = []string{"DESCRIBE"}46 mockReport.RunTime = time.Duration(2000000000)47 mockReport.SpecReports = []SpecReport{48 {49 ContainerHierarchyTexts: mockContainerHierarchyTexts,50 LeafNodeText: testCaseName,51 RunTime: time.Duration(1000000000),52 Failure: types.Failure{},53 CapturedGinkgoWriterOutput: "",54 CapturedStdOutErr: "",55 },56 }57 suiteDuration = math.Trunc(mockReport.RunTime.Seconds()*1000) / 100058 testCaseDuration = time.Duration(1000000000).Seconds()59 })60 It("should setup test suite metadata correctly", func() {61 expectedIndex := append([]byte(fmt.Sprintf(`{ "index": { "_index": "%s", "_type": "_doc" } }`, indexName)), []byte("\n")...)62 mockReport.PreRunStats.SpecsThatWillRun = 063 reporter.processReport(mockReport)64 Expect(reporter.filename).To(Equal(reportFileName))65 Expect(reporter.index).To(Equal(expectedIndex))66 Expect(reporter.testSuiteName).To(Equal(mockReportSuiteDescription))67 Expect(reporter.suite.Name).To(Equal(mockReportSuiteDescription))68 Expect(reporter.suite.Failures).To(Equal(0))69 Expect(reporter.suite.Phase).To(Equal(SpecPhaseSucceeded))70 Expect(reporter.suite.Tests).To(Equal(0))71 Expect(reporter.suite.Duration).To(Equal(suiteDuration))72 Expect(reporter.suite.Errors).To(Equal(0))73 })74 It("should process one successful test correctly", func() {75 mockReport.PreRunStats.SpecsThatWillRun = 176 mockReport.SpecReports[0].State = types.SpecStatePassed77 reporter.processReport(mockReport)78 Expect(reporter.suite.Tests).To(Equal(1))79 Expect(reporter.suite.Failures).To(Equal(0))80 Expect(reporter.suite.Phase).To(Equal(SpecPhaseSucceeded))81 Expect(len(reporter.testCases)).To(Equal(1))82 Expect(reporter.testCases[0].Metadata.Name).To(Equal(mockReportSuiteDescription))83 Expect(reporter.testCases[0].Name).To(Equal(testCaseName))84 Expect(reporter.testCases[0].ShortName).To(Equal(testCaseName))85 Expect(reporter.testCases[0].Phase).To(Equal(SpecPhaseSucceeded))86 Expect(reporter.testCases[0].Duration).To(Equal(testCaseDuration))87 })88 It("should process one failed test correctly", func() {89 stderr := "stderr - something failed"90 failureMessage := "something went wrong"91 location := types.CodeLocation{92 FileName: "test.go",93 LineNumber: 10,94 FullStackTrace: "some text",95 }96 failureLocation := types.CodeLocation{97 FileName: "error.go",98 LineNumber: 20,99 FullStackTrace: "some error",100 }101 mockReport.PreRunStats.SpecsThatWillRun = 1102 mockReport.SpecReports[0].State = types.SpecStateFailed103 mockReport.SpecReports[0].Failure = types.Failure{104 Message: failureMessage,105 Location: location,106 FailureNodeLocation: failureLocation,107 }108 mockReport.SpecReports[0].CapturedStdOutErr = stderr109 reporter.processReport(mockReport)110 Expect(reporter.suite.Tests).To(Equal(1))111 Expect(reporter.suite.Failures).To(Equal(1))112 Expect(reporter.suite.Errors).To(Equal(0))113 Expect(reporter.suite.Phase).To(Equal(SpecPhaseFailed))114 Expect(len(reporter.testCases)).To(Equal(1))115 Expect(reporter.testCases[0].Metadata.Name).To(Equal(mockReportSuiteDescription))116 Expect(reporter.testCases[0].Name).To(Equal(testCaseName))117 Expect(reporter.testCases[0].ShortName).To(Equal(testCaseName))118 Expect(reporter.testCases[0].Phase).To(Equal(SpecPhaseFailed))119 Expect(reporter.testCases[0].Duration).To(Equal(testCaseDuration))120 Expect(reporter.testCases[0].FailureMessage).NotTo(BeNil())121 Expect(reporter.testCases[0].FailureMessage.Type).To(Equal(SpecPhaseFailed))122 Expect(reporter.testCases[0].FailureMessage.Message).To(Equal(fmt.Sprintf("%s\n%s\n%s", failureLocation.String(), failureMessage, location.String())))123 Expect(reporter.testCases[0].SystemOut).To(Equal(stderr))124 })125 It("should process one panicked test correctly", func() {126 stderr := "stderr - something panicked"127 failureMessage := "something went utterly wrong"128 location := types.CodeLocation{129 FileName: "test.go",130 LineNumber: 10,131 FullStackTrace: "some text",132 }133 failureLocation := types.CodeLocation{134 FileName: "error.go",135 LineNumber: 20,136 FullStackTrace: "some error",137 }138 mockReport.PreRunStats.SpecsThatWillRun = 1139 mockReport.SpecReports[0].State = types.SpecStatePanicked140 mockReport.SpecReports[0].Failure = types.Failure{141 Message: failureMessage,142 Location: location,143 FailureNodeLocation: failureLocation,144 }145 mockReport.SpecReports[0].CapturedStdOutErr = stderr146 reporter.processReport(mockReport)147 Expect(reporter.suite.Tests).To(Equal(1))148 Expect(reporter.suite.Failures).To(Equal(0))149 Expect(reporter.suite.Errors).To(Equal(1))150 Expect(reporter.suite.Phase).To(Equal(SpecPhaseFailed))151 Expect(len(reporter.testCases)).To(Equal(1))152 Expect(reporter.testCases[0].Metadata.Name).To(Equal(mockReportSuiteDescription))153 Expect(reporter.testCases[0].Name).To(Equal(testCaseName))154 Expect(reporter.testCases[0].ShortName).To(Equal(testCaseName))155 Expect(reporter.testCases[0].Phase).To(Equal(SpecPhaseFailed))156 Expect(reporter.testCases[0].Duration).To(Equal(testCaseDuration))157 Expect(reporter.testCases[0].FailureMessage).NotTo(BeNil())158 Expect(reporter.testCases[0].FailureMessage.Type).To(Equal(SpecPhaseFailed))159 Expect(reporter.testCases[0].FailureMessage.Message).To(Equal(fmt.Sprintf("%s\n%s\n%s", failureLocation.String(), failureMessage, location.String())))160 Expect(reporter.testCases[0].SystemOut).To(Equal(stderr))161 })162 It("should process one skipped test correctly", func() {163 mockReport.PreRunStats.SpecsThatWillRun = 0164 mockReport.SpecReports[0].State = types.SpecStateSkipped165 reporter.processReport(mockReport)166 Expect(reporter.suite.Tests).To(Equal(0))167 Expect(reporter.suite.Failures).To(Equal(0))168 Expect(reporter.suite.Phase).To(Equal(SpecPhaseSucceeded))169 Expect(len(reporter.testCases)).To(Equal(0))170 })171})...
Test
Using AI Code Generation
1import "testing"2func Test(t *testing.T) {3 t.Log("Hello")4}5func Test2(t *testing.T) {6 t.Log("Hello2")7}8func Test3(t *testing.T) {9 t.Log("Hello3")10}11--- PASS: Test (0.00s)12--- PASS: Test2 (0.00s)13--- PASS: Test3 (0.00s)14--- PASS: Test (0.00s)15--- PASS: Test2 (0.00s)16--- PASS: Test3 (0.00s)17--- PASS: Test (0.00s)18--- PASS: Test2 (0.00s)19--- PASS: Test3 (0.00s)20--- PASS: Test (0.00s)21--- PASS: Test2 (0.00s)22--- PASS: Test3 (0.00s)
Test
Using AI Code Generation
1import (2func Test(t *testing.T) {3 t.Log("Test1")4 t.Log("Test2")5 t.Log("Test3")6 t.Log("Test4")7 t.Log("Test5")8}9func Test1(t *testing.T) {10 t.Log("Test6")11 t.Log("Test7")12 t.Log("Test8")13 t.Log("Test9")14 t.Log("Test10")15}16--- PASS: Test (0.00s)17--- PASS: Test1 (0.00s)18--- PASS: Test1 (0.00s)
Test
Using AI Code Generation
1import (2func Test(t *testing.T) {3 t.Log("Hello World")4}5import (6func Test(t *testing.T) {7 t.Errorf("Hello World")8}9import (10func Test(t *testing.T) {11 t.FailNow()12}13import (14func Test(t *testing.T) {15 t.Error("Hello World")16}17import (18func Test(t *testing.T) {19 t.Fatal("Hello World")20}21import (22func Test(t *testing.T) {23 t.Fail()24}25import (26func Test(t *testing.T) {27 t.SkipNow()28}29import (30func Test(t *testing.T) {31 t.Skip()32}33import (34func Test(t *testing.T) {35 t.Skipf("Hello World")36}37import (38func Test(t *testing.T) {39 t.SkipNow()40}41import (42func Test(t *testing.T) {43 t.SkipNow()44}45import (46func Test(t *testing.T) {47 t.SkipNow()48}49import (50func Test(t *
Test
Using AI Code Generation
1import (2func Test(t *testing.T) {3 fmt.Println("Test method of reporter class")4}5import (6func Test(t *testing.T) {7 fmt.Println("Run method of reporter class")8}9import (10func Test(t *testing.T) {11 fmt.Println("Run method of reporter class")12}13import (14func Test(t *testing.T) {15 fmt.Println("Run method of reporter class")16}17import (18func Test(t *testing.T) {19 fmt.Println("Run method of reporter class")20}21import (22func Test(t *testing.T) {23 fmt.Println("Run method of reporter class")24}25import (26func Test(t *testing.T) {27 fmt.Println("Run method of reporter class")28}29import (30func Test(t *testing.T) {31 fmt.Println("Run method of reporter class")32}33import (34func Test(t *testing.T) {35 fmt.Println("Run method of reporter class")36}37import (38func Test(t *testing.T) {39 fmt.Println("Run method of reporter class")40}41import (42func Test(t *testing.T) {43 fmt.Println("Run method of reporter class
Test
Using AI Code Generation
1import (2func Test(t *testing.T) {3 fmt.Println("This is a test")4}5import (6func Test(t *testing.T) {7 fmt.Println("This is a test")8 t.Fail()9}10import (11func Test(t *testing.T) {12 fmt.Println("This is a test")13 t.Error()14}15import (16func Test(t *testing.T) {17 fmt.Println("This is a test")18 t.Errorf("Error")19}20import (21func Test(t *testing.T) {22 fmt.Println("This is a test")23 t.FailNow()24}25import (26func Test(t *testing.T) {27 fmt.Println("This is a test")28 t.Fatal()29}30import (31func Test(t *testing.T) {32 fmt.Println("This is a test")33 t.Fatalf("Error")34}35import (36func Test(t *testing.T) {37 fmt.Println("This is a test")38 t.Log("Log")39}40import (41func Test(t *testing.T) {42 fmt.Println("This is a test")43 t.Logf("Log %s", "Message")44}45import (46func Test(t *testing.T) {47 fmt.Println("This is a test")48 t.Skip("Skip")49}
Test
Using AI Code Generation
1import (2func Test(t *testing.T) {3 t.Log("Test method of reporter class")4}5import (6func Test(t *testing.T) {7 t.Log("Test method of reporter class")8}9import (10func Test(t *testing.T) {11 t.Log("Test method of reporter class")12}13import (14func Test(t *testing.T) {15 t.Log("Test method of reporter class")16}17import (18func Test(t *testing.T) {19 t.Log("Test method of reporter class")20}21import (22func Test(t *testing.T) {23 t.Log("Test method of reporter class")24}25import (26func Test(t *testing.T) {27 t.Log("Test method of reporter class")28}29import (30func Test(t *testing.T) {31 t.Log("Test method of reporter class")32}33import (34func Test(t *testing.T) {35 t.Log("Test method of reporter class")36}37import (38func Test(t *testing.T) {39 t.Log("Test method of reporter class")40}41import (42func Test(t *testing.T) {43 t.Log("Test method of reporter class")44}
Test
Using AI Code Generation
1import "testing"2func Test(t *testing.T) {3 t.Log("Hello")4}5--- PASS: Test (0.00s)6import "testing"7func Test(t *testing.T) {8 t.Log("Hello")9 t.Fail()10}11--- FAIL: Test (0.00s)12The t.SkipNow() method is used to skip the test immediately. It
Test
Using AI Code Generation
1func Test(t *testing.T) {2 t.Error("Error")3}4func Test(t *testing.T) {5 t.Run("Subtest", func(t *testing.T) {6 t.Error("Error")7 })8}9func Test(t *testing.T) {10 t.Run("Subtest", func(t *testing.T) {11 t.Run("Subtest", func(t *testing.T) {12 t.Error("Error")13 })14 })15}16func Test(t *testing.T) {17 t.Run("Subtest", func(t *testing.T)
Test
Using AI Code Generation
1import "testing"2func Test(t *testing.T) {3 t.Log("Hello")4}5import "testing"6func Test(t *testing.T) {7 t.Error("Hello")8}9--- FAIL: Test (0.00s)10import "testing"11func Test(t *testing.T) {12 t.Fail()13}14--- FAIL: Test (0.00s)15import "testing"16func Test(t *testing.T) {17 t.Fatal("Hello")18}19--- FAIL: Test (0.00s)20import "testing"21func Test(t *testing.T) {22 t.Skip("Hello")23}24--- SKIP: Test (0.00s)25import "testing"26func Test(t *testing.T) {27 t.SkipNow()28}29--- SKIP: Test (0.00s)30import "testing"31func Test(t *testing.T) {32 t.Skipf("Hello")33}34--- SKIP: Test (0.00s)
Test
Using AI Code Generation
1import (2func Test(t *testing.T) {3 fmt.Println("Test method")4}5func Add(a int, b int) int {6}7import (8func TestAdd(t *testing.T) {9 if Add(2, 3) != 5 {10 t.Error("Expected 5")11 }12}13In the above example, we have used the function Error() to check if the test case passes or fails. We can also use the function Errorf() to check if the test case passes or fails. The function Error
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!