Debian Codegraph @

trace/trace_test.go

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 Copyright 2019 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package trace
18
19 import (
20 "bytes"
21 "context"
22 "flag"
23 "os"
24 "strings"
25 "testing"
26 "time"
27
28 "k8s.io/klog/v2"
29 )
30
31 func init() {
32 klog.InitFlags(flag.CommandLine)
33 flag.CommandLine.Lookup("logtostderr").Value.Set("false")
34 flag.CommandLine.Lookup("v").Value.Set("2")
35 }
36
37 func TestStep(t *testing.T) {
38 tests := []struct {
39 name string
40 inputString string
41 expectedTrace *Trace
42 }{
43 {
44 name: "When string is empty",
45 inputString: "",
46 expectedTrace: &Trace{
47 traceItems: []traceItem{
48 traceStep{stepTime: time.Now(), msg: ""},
49 },
50 },
51 },
52 {
53 name: "When string is not empty",
54 inputString: "test2",
55 expectedTrace: &Trace{
56 traceItems: []traceItem{
57 traceStep{stepTime: time.Now(), msg: "test2"},
58 },
59 },
60 },
61 }
62
63 for _, tt := range tests {
64 t.Run(tt.name, func(t *testing.T) {
65 sampleTrace := &Trace{}
66 sampleTrace.Step(tt.inputString)
67 if sampleTrace.traceItems[0].(traceStep).msg != tt.expectedTrace.traceItems[0].(traceStep).msg {
68 t.Errorf("Expected %v \n Got %v \n", tt.expectedTrace, sampleTrace)
69 }
70 })
71 }
72 }
73
74 func TestNestedTrace(t *testing.T) {
75 tests := []struct {
76 name string
77 inputString string
78 expectedTrace *Trace
79 }{
80 {
81 name: "Empty string",
82 inputString: "",
83 expectedTrace: &Trace{
84 traceItems: []traceItem{
85 &Trace{startTime: time.Now(), name: ""},
86 },
87 },
88 },
89 {
90 name: "Non-empty string",
91 inputString: "Inner trace",
92 expectedTrace: &Trace{
93 traceItems: []traceItem{
94 &Trace{
95 startTime: time.Now(),
96 name: "Inner trace",
97 traceItems: []traceItem{
98 &Trace{name: "Inner trace"},
99 },
100 },
101 },
102 },
103 },
104 }
105
106 for _, tt := range tests {
107 t.Run(tt.name, func(t *testing.T) {
108 sampleTrace := &Trace{}
109 innerSampleTrace := sampleTrace.Nest(tt.inputString)
110 innerSampleTrace.Nest(tt.inputString)
111 if sampleTrace.traceItems[0].(*Trace).name != tt.expectedTrace.traceItems[0].(*Trace).name {
112 t.Errorf("Expected %v \n Got %v \n", tt.expectedTrace, sampleTrace)
113 }
114 })
115 }
116 }
117
118 func TestTotalTime(t *testing.T) {
119 test := struct {
120 name string
121 inputTrace *Trace
122 }{
123 name: "Test with current system time",
124 inputTrace: &Trace{
125 startTime: time.Now(),
126 },
127 }
128
129 t.Run(test.name, func(t *testing.T) {
130 got := test.inputTrace.TotalTime()
131 if got == 0 {
132 t.Errorf("Expected total time 0, got %d \n", got)
133 }
134 })
135 }
136
137 func TestLog(t *testing.T) {
138 tests := []struct {
139 name string
140 msg string
141 fields []Field
142 expectedMessages []string
143 sampleTrace *Trace
144 verbosity klog.Level
145 }{
146 {
147 name: "Check the log dump with 3 msg",
148 expectedMessages: []string{
149 "msg1", "msg2", "msg3",
150 },
151 sampleTrace: &Trace{
152 name: "Sample Trace",
153 traceItems: []traceItem{
154 &traceStep{stepTime: time.Now(), msg: "msg1"},
155 &traceStep{stepTime: time.Now(), msg: "msg2"},
156 &traceStep{stepTime: time.Now(), msg: "msg3"},
157 },
158 },
159 },
160 {
161 name: "Check formatting",
162 expectedMessages: []string{
163 "URL:/api,count:3", `"msg1" str:text,int:2,bool:false`, `"msg2" x:1`,
164 },
165 sampleTrace: &Trace{
166 name: "Sample Trace",
167 fields: []Field{{"URL", "/api"}, {"count", 3}},
168 traceItems: []traceItem{
169 &traceStep{stepTime: time.Now(), msg: "msg1", fields: []Field{{"str", "text"}, {"int", 2}, {"bool",
170 false}}},
171 &traceStep{stepTime: time.Now(), msg: "msg2", fields: []Field{{"x", "1"}}},
172 },
173 },
174 },
175 {
176 name: "Check fixture formatted",
177 expectedMessages: []string{
178 "URL:/api,count:3", `"msg1" str:text,int:2,bool:false`, `"msg2" x:1`,
179 },
180 sampleTrace: fieldsTraceFixture(),
181 },
182 {
183 name: "Check that logs are not dumped if verbosity < 2",
184 verbosity: 1,
185 expectedMessages: []string{},
186 sampleTrace: fieldsTraceFixture(),
187 },
188 }
189
190 for _, test := range tests {
191 t.Run(test.name, func(t *testing.T) {
192 var buf bytes.Buffer
193 klog.SetOutput(&buf)
194
195 if test.verbosity > 0 {
196 orig := klogV
197 klogV = func(l klog.Level) bool {
198 return l <= test.verbosity
199 }
200 defer func() {
201 klogV = orig
202 }()
203 }
204
205 test.sampleTrace.Log()
206
207 if len(test.expectedMessages) == 0 && buf.Len() != 0 {
208 t.Errorf("\nNo message expected in trace log: \n%v\n", buf.String())
209 }
210
211 for _, msg := range test.expectedMessages {
212 if !strings.Contains(buf.String(), msg) {
213 t.Errorf("\nMsg %q not found in log: \n%v\n", msg, buf.String())
214 }
215 }
216 })
217 }
218 }
219
220 func TestNestedTraceLog(t *testing.T) {
221 currentTime := time.Now()
222 tests := []struct {
223 name string
224 msg string
225 fields []Field
226 expectedMessages []string
227 sampleTrace *Trace
228 }{
229 {
230 name: "Check the log dump with 3 nestedTraces",
231 expectedMessages: []string{
232 "Sample Trace", "msg1", "msg2", "msg3",
233 },
234 sampleTrace: &Trace{
235 name: "Sample Trace",
236 traceItems: []traceItem{
237 &Trace{startTime: currentTime, endTime: &currentTime, name: "msg1"},
238 &Trace{startTime: currentTime, endTime: &currentTime, name: "msg2"},
239 &Trace{startTime: currentTime, endTime: &currentTime, name: "msg3"},
240 },
241 },
242 },
243 {
244 name: "Check the log dump with 3 nestedTraces and steps",
245 expectedMessages: []string{
246 "Sample Trace", "msg1", "msg2", "msg3", "step1", "step2", "step3",
247 },
248 sampleTrace: &Trace{
249 name: "Sample Trace",
250 traceItems: []traceItem{
251 &Trace{startTime: currentTime, endTime: &currentTime, name: "msg1"},
252 &Trace{startTime: currentTime, endTime: &currentTime, name: "msg2"},
253 &Trace{startTime: currentTime, endTime: &currentTime, name: "msg3"},
254 &traceStep{stepTime: currentTime, msg: "step1"},
255 &traceStep{stepTime: currentTime, msg: "step2"},
256 &traceStep{stepTime: currentTime, msg: "step3"},
257 },
258 },
259 },
260 {
261 name: "Check the log dump with nestedTrace with fields",
262 expectedMessages: []string{
263 "Sample Trace", `"msg1" str:text,int:2,bool:false`,
264 },
265 sampleTrace: &Trace{
266 name: "Sample Trace",
267 traceItems: []traceItem{
268 &Trace{
269 startTime: currentTime,
270 endTime: &currentTime,
271 name: "msg1", fields: []Field{
272 {"str", "text"},
273 {"int", 2},
274 {"bool", false}}},
275 },
276 },
277 },
278 {
279 name: "Check the log dump with doubly nestedTrace",
280 expectedMessages: []string{
281 "Sample Trace", "msg1", "nested1",
282 },
283 sampleTrace: &Trace{
284 name: "Sample Trace",
285 traceItems: []traceItem{
286 &Trace{
287 startTime: currentTime,
288 endTime: &currentTime,
289 name: "msg1",
290 traceItems: []traceItem{&Trace{name: "nested1", startTime: currentTime, endTime: &currentTime}},
291 },
292 },
293 },
294 },
295 }
296 for _, test := range tests {
297 t.Run(test.name, func(t *testing.T) {
298 var buf bytes.Buffer
299 klog.SetOutput(&buf)
300 test.sampleTrace.Log()
301 for _, msg := range test.expectedMessages {
302 if !strings.Contains(buf.String(), msg) {
303 t.Errorf("\nMsg %q not found in log: \n%v\n", msg, buf.String())
304 }
305 }
306 })
307 }
308 }
309
310 func fieldsTraceFixture() *Trace {
311 trace := New("Sample Trace", Field{"URL", "/api"}, Field{"count", 3})
312 trace.Step("msg1", Field{"str", "text"}, Field{"int", 2}, Field{"bool", false})
313 trace.Step("msg2", Field{"x", "1"})
314 return trace
315 }
316
317 func TestLogIfLong(t *testing.T) {
318 currentTime := time.Now()
319 type mutate struct {
320 delay time.Duration
321 msg string
322 }
323
324 tests := []*struct {
325 name string
326 expectedMessages []string
327 sampleTrace *Trace
328 threshold time.Duration
329 mutateInfo []mutate // mutateInfo contains the information to mutate step's time to simulate multiple tests without waiting.
330
331 }{
332 {
333 name: "When threshold is 10 and msg 3 has highest share",
334 expectedMessages: []string{
335 "msg3",
336 },
337 mutateInfo: []mutate{
338 {0, "msg1"},
339 {0, "msg2"},
340 {50, "msg3"},
341 },
342 threshold: 10,
343 },
344 {
345 name: "When threshold is 0 and all msg have same share",
346 expectedMessages: []string{
347 "msg1", "msg2", "msg3",
348 },
349 mutateInfo: []mutate{
350 {0, "msg1"},
351 {0, "msg2"},
352 {0, "msg3"},
353 },
354 threshold: 0,
355 },
356 {
357 name: "When threshold is 20 and all msg 1 has highest share",
358 expectedMessages: []string{},
359 mutateInfo: []mutate{
360 {10, "msg1"},
361 {0, "msg2"},
362 {0, "msg3"},
363 },
364 threshold: 20,
365 },
366 }
367
368 for _, tt := range tests {
369 t.Run(tt.name, func(t *testing.T) {
370 var buf bytes.Buffer
371 klog.SetOutput(&buf)
372
373 tt.sampleTrace = New("Test trace")
374 for _, mod := range tt.mutateInfo {
375 tt.sampleTrace.traceItems = append(tt.sampleTrace.traceItems,
376 &traceStep{stepTime: currentTime.Add(mod.delay), msg: mod.msg})
377 }
378
379 tt.sampleTrace.LogIfLong(tt.threshold)
380
381 for _, msg := range tt.expectedMessages {
382 if msg != "" && !strings.Contains(buf.String(), msg) {
383 t.Errorf("Msg %q expected in trace log: \n%v\n", msg, buf.String())
384 }
385 }
386 })
387 }
388 }
389
390 func TestLogNestedTrace(t *testing.T) {
391 twoHundred := 200 * time.Millisecond
392 five := 5 * time.Millisecond
393 currentTime := time.Now()
394
395 tests := []struct {
396 name string
397 expectedMsgs []string
398 unexpectedMsg []string
399 trace *Trace
400 verbosity klog.Level
401 }{
402 {
403 name: "Log nested trace when it surpasses threshold",
404 expectedMsgs: []string{"inner1"},
405 unexpectedMsg: []string{"msg"},
406 trace: &Trace{
407 name: "msg",
408 startTime: currentTime.Add(10),
409 traceItems: []traceItem{
410 &Trace{
411 name: "inner1",
412 threshold: &five,
413 startTime: currentTime.Add(-10 * time.Millisecond),
414 endTime: &currentTime,
415 },
416 },
417 },
418 },
419 {
420 name: "Log inner nested trace when it surpasses threshold",
421 expectedMsgs: []string{"inner2"},
422 unexpectedMsg: []string{"msg", "inner1"},
423 trace: &Trace{
424 name: "msg",
425 startTime: currentTime.Add(10),
426 traceItems: []traceItem{
427 &Trace{
428 name: "inner1",
429 threshold: &five,
430 startTime: currentTime.Add(-1 * time.Millisecond),
431 endTime: &currentTime,
432 traceItems: []traceItem{
433 &Trace{
434 name: "inner2",
435 threshold: &five,
436 startTime: currentTime.Add(-10 * time.Millisecond),
437 endTime: &currentTime,
438 },
439 },
440 },
441 },
442 },
443 },
444 {
445 name: "Log inner nested trace when it surpasses threshold and surrounding trace not ended",
446 expectedMsgs: []string{"inner2"},
447 unexpectedMsg: []string{"msg", "inner1"},
448 trace: &Trace{
449 name: "msg",
450 startTime: currentTime.Add(10),
451 traceItems: []traceItem{
452 &Trace{
453 name: "inner1",
454 threshold: &five,
455 traceItems: []traceItem{
456 &Trace{
457 name: "inner2",
458 threshold: &five,
459 startTime: currentTime.Add(-10 * time.Millisecond),
460 endTime: &currentTime,
461 },
462 },
463 },
464 },
465 },
466 },
467 {
468 name: "Do not log nested trace that does not surpass threshold",
469 expectedMsgs: []string{"msg", "inner2"},
470 unexpectedMsg: []string{"inner1"},
471 trace: &Trace{
472 name: "msg",
473 startTime: currentTime.Add(-300 * time.Millisecond),
474 traceItems: []traceItem{
475 &Trace{
476 name: "inner1",
477 threshold: &five,
478 startTime: currentTime.Add(-1 * time.Millisecond),
479 endTime: &currentTime,
480 traceItems: []traceItem{
481 &Trace{
482 name: "inner2",
483 threshold: &five,
484 startTime: currentTime.Add(-10 * time.Millisecond),
485 endTime: &currentTime,
486 },
487 },
488 },
489 },
490 },
491 },
492 {
493 name: "Log all nested traces that surpass threshold",
494 expectedMsgs: []string{"inner1", "inner2"},
495 unexpectedMsg: []string{"msg"},
496 trace: &Trace{
497 name: "msg",
498 startTime: currentTime.Add(10),
499 traceItems: []traceItem{
500 &Trace{
501 name: "inner1",
502 threshold: &five,
503 startTime: currentTime.Add(-10 * time.Millisecond),
504 endTime: &currentTime,
505 traceItems: []traceItem{
506 &Trace{
507 name: "inner2",
508 threshold: &five,
509 startTime: currentTime.Add(-10 * time.Millisecond),
510 endTime: &currentTime,
511 },
512 },
513 },
514 },
515 },
516 },
517 {
518 name: "Log all nested traces that surpass threshold and their children if klog verbosity is >= 4",
519 expectedMsgs: []string{"inner1", "inner2"},
520 unexpectedMsg: []string{"msg"},
521 verbosity: 4,
522 trace: &Trace{
523 name: "msg",
524 startTime: currentTime.Add(10),
525 traceItems: []traceItem{
526 &Trace{
527 name: "inner1",
528 threshold: &five,
529 startTime: currentTime.Add(-10 * time.Millisecond),
530 endTime: &currentTime,
531 traceItems: []traceItem{
532 &Trace{
533 name: "inner2",
534 threshold: &twoHundred,
535 startTime: currentTime.Add(-10 * time.Millisecond),
536 endTime: &currentTime,
537 },
538 },
539 },
540 },
541 },
542 },
543 }
544
545 for _, tt := range tests {
546 t.Run(tt.name, func(t *testing.T) {
547 var buf bytes.Buffer
548 klog.SetOutput(&buf)
549
550 if tt.verbosity > 0 {
551 orig := klogV
552 klogV = func(l klog.Level) bool {
553 return l <= tt.verbosity
554 }
555 defer func() {
556 klogV = orig
557 }()
558 }
559
560 tt.trace.LogIfLong(twoHundred)
561
562 for _, msg := range tt.expectedMsgs {
563 if msg != "" && !strings.Contains(buf.String(), msg) {
564 t.Errorf("Msg %q expected in trace log: \n%v\n", msg, buf.String())
565 }
566 }
567
568 for _, msg := range tt.unexpectedMsg {
569 if msg != "" && strings.Contains(buf.String(), msg) {
570 t.Errorf("Msg %q not expected in trace log: \n%v\n", msg, buf.String())
571 }
572 }
573 })
574
575 }
576 }
577
578 func TestStepThreshold(t *testing.T) {
579
580 thousandMs := 1000 * time.Millisecond
581 sixHundred := 600 * time.Millisecond
582 hundredMs := 100 * time.Millisecond
583 twoThousandMs := 1200 * time.Millisecond
584
585 tests := []struct {
586 name string
587 inputTrace *Trace
588 expectedThreshold time.Duration
589 }{
590 {
591 name: "Trace with nested traces",
592 inputTrace: &Trace{
593 threshold: &thousandMs,
594 traceItems: []traceItem{
595 traceStep{msg: "trace 1"},
596 traceStep{msg: "trace 2"},
597 &Trace{threshold: &sixHundred},
598 &Trace{name: "msg 1"},
599 },
600 },
601 expectedThreshold: 100 * time.Millisecond,
602 },
603 {
604 name: "Trace with nested traces",
605 inputTrace: &Trace{
606 threshold: &thousandMs,
607 traceItems: []traceItem{
608 traceStep{msg: "trace 1"},
609 traceStep{msg: "trace 2"},
610 &Trace{threshold: &sixHundred},
611 &Trace{name: "msg 1", threshold: &hundredMs},
612 },
613 },
614 expectedThreshold: 100 * time.Millisecond,
615 },
616 {
617 name: "Trace with nested traces with a large threshold",
618 inputTrace: &Trace{
619 threshold: &thousandMs,
620 traceItems: []traceItem{
621 &Trace{threshold: &twoThousandMs},
622 },
623 },
624 expectedThreshold: 125 * time.Millisecond,
625 },
626 }
627
628 for _, tt := range tests {
629 actualThreshold := *tt.inputTrace.calculateStepThreshold()
630 if actualThreshold != tt.expectedThreshold {
631 t.Errorf("Expecting %v threshold but got %v", tt.expectedThreshold, actualThreshold)
632 }
633 }
634 }
635
636 func TestParentEndedBeforeChild(_ *testing.T) {
637 var buf bytes.Buffer
638 klog.SetOutput(&buf)
639 parent := New("foo")
640 for range 1000 {
641 go func(parent *Trace) {
642 child := parent.Nest("bar")
643 child.Step("hello")
644 child.LogIfLong(0 * time.Second)
645 }(parent)
646 }
647 parent.Step("world")
648 parent.LogIfLong(0 * time.Second)
649 }
650
651 func TestContext(t *testing.T) {
652 ctx := context.Background()
653
654 trace1 := FromContext(ctx).Nest("op1")
655 ctx = ContextWithTrace(ctx, trace1)
656 defer trace1.Log()
657 func(ctx context.Context) {
658 trace2 := FromContext(ctx).Nest("op2")
659 defer trace2.Log()
660 }(ctx)
661 if len(trace1.traceItems) != 1 {
662 t.Fatalf("expected len(trace1.traceItems) == 1, but got %d", len(trace1.traceItems))
663 }
664 nested, ok := trace1.traceItems[0].(*Trace)
665 if !ok {
666 t.Fatal("expected trace1.traceItems[0] to be a nested trace")
667 }
668 if nested.name != "op2" {
669 t.Errorf("expected trace named op2 to be nested in op1, but got %s", nested.name)
670 }
671 }
672
673 func ExampleTrace_Step() {
674 t := New("frobber")
675
676 time.Sleep(5 * time.Millisecond)
677 t.Step("reticulated splines") // took 5ms
678
679 time.Sleep(10 * time.Millisecond)
680 t.Step("sequenced particles") // took 10ms
681
682 klog.SetOutput(os.Stdout) // change output from stderr to stdout
683 t.Log()
684 }