-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathengine_test.go
More file actions
700 lines (622 loc) · 17.8 KB
/
engine_test.go
File metadata and controls
700 lines (622 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
package stats_test
import (
"io"
"net/http"
"reflect"
"strings"
"testing"
"time"
stats "github.com/segmentio/stats/v5"
"github.com/segmentio/stats/v5/datadog"
"github.com/segmentio/stats/v5/influxdb"
"github.com/segmentio/stats/v5/prometheus"
"github.com/segmentio/stats/v5/statstest"
)
func TestEngine(t *testing.T) {
tests := []struct {
scenario string
function func(*testing.T, *stats.Engine)
}{
{
scenario: "calling Engine.WithPrefix returns a copy of the engine with the prefix and tags inherited from the original",
function: testEngineWithPrefix,
},
{
scenario: "calling Engine.WithTags returns a copy of the engine with the prefix and tags inherited from the original",
function: testEngineWithPrefix,
},
{
scenario: "calling Engine.Flush calls Flush the handler's Flush method",
function: testEngineFlush,
},
{
scenario: "calling Engine.Incr produces a counter increment of one",
function: testEngineIncr,
},
{
scenario: "calling Engine.Add produces a counter increment of the expected amount",
function: testEngineAdd,
},
{
scenario: "calling Engine.Set produces the expected gauge value",
function: testEngineSet,
},
{
scenario: "calling Engine.Observe produces the expected histogram value",
function: testEngineObserve,
},
{
scenario: "calling Engine.Report produces the expected measures",
function: testEngineReport,
},
{
scenario: "calling Engine.Report with an array of metrics produces the expected measures",
function: testEngineReportArray,
},
{
scenario: "calling Engine.Report with a slice of metrics produces the expected measures",
function: testEngineReportSlice,
},
{
scenario: "calling Engine.Clock produces expected metrics",
function: testEngineClock,
},
{
scenario: "calling Engine.WithTags produces expected tags",
function: testEngineWithTags,
},
{
scenario: "calling Engine.Incr produces expected tags when AllowDuplicateTags is set",
function: testEngineAllowDuplicateTags,
},
}
initValue := stats.GoVersionReportingEnabled
stats.GoVersionReportingEnabled = false
defer func() { stats.GoVersionReportingEnabled = initValue }()
// Extra t.Run is necessary so above defer runs after parallel tests
// complete.
t.Run("subtests", func(t *testing.T) {
for _, test := range tests {
testFunc := test.function
t.Run(test.scenario, func(t *testing.T) {
t.Parallel()
h := &statstest.Handler{}
testFunc(t, stats.NewEngine("test", h, stats.T("service", "test-service")))
})
}
})
}
func testEngineWithPrefix(t *testing.T, eng *stats.Engine) {
e2 := eng.WithPrefix("subtest", stats.T("command", "hello world"))
if e2.Prefix != "test.subtest" {
t.Error("bad prefix:", e2.Prefix)
}
if !reflect.DeepEqual(e2.Tags, []stats.Tag{
stats.T("command", "hello world"),
stats.T("service", "test-service"),
}) {
t.Error("bad tags:", e2.Tags)
}
}
func testEngineWithTags(t *testing.T, eng *stats.Engine) {
e2 := eng.WithTags(
stats.T("command", "hello world"),
stats.T("system", "testing"),
)
if e2.Prefix != "test" {
t.Error("bad prefix:", e2.Prefix)
}
if !reflect.DeepEqual(e2.Tags, []stats.Tag{
stats.T("command", "hello world"),
stats.T("service", "test-service"),
stats.T("system", "testing"),
}) {
t.Error("bad tags:", e2.Tags)
}
}
func testEngineFlush(t *testing.T, eng *stats.Engine) {
eng.Flush()
eng.Flush()
eng.Flush()
h := eng.Handler.(*statstest.Handler)
if n := h.FlushCalls(); n != 3 {
t.Error("bad number of flush calls:", n)
}
}
func testEngineAllowDuplicateTags(t *testing.T, eng *stats.Engine) {
e2 := eng.WithTags()
e2.AllowDuplicateTags = true
if e2.Prefix != "test" {
t.Error("bad prefix:", e2.Prefix)
}
e2.Incr("measure.count")
e2.Incr("measure.count", stats.T("category", "a"), stats.T("category", "b"), stats.T("category", "c"))
checkMeasuresEqual(t, e2,
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("count", 1, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service")},
},
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("count", 1, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("category", "a"), stats.T("category", "b"), stats.T("category", "c")},
},
)
}
func testEngineIncr(t *testing.T, eng *stats.Engine) {
eng.Incr("measure.count")
eng.Incr("measure.count", stats.T("type", "testing"))
checkMeasuresEqual(t, eng,
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("count", 1, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service")},
},
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("count", 1, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
)
}
func testEngineAdd(t *testing.T, eng *stats.Engine) {
eng.Add("measure.count", 42)
eng.Add("measure.count", 10, stats.T("type", "testing"))
checkMeasuresEqual(t, eng,
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("count", 42, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service")},
},
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("count", 10, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
)
}
func testEngineSet(t *testing.T, eng *stats.Engine) {
eng.Set("measure.level", 42)
eng.Set("measure.level", 10, stats.T("type", "testing"))
checkMeasuresEqual(t, eng,
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("level", 42, stats.Gauge)},
Tags: []stats.Tag{stats.T("service", "test-service")},
},
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("level", 10, stats.Gauge)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
)
}
func testEngineObserve(t *testing.T, eng *stats.Engine) {
eng.Observe("measure.size", 42)
eng.Observe("measure.size", 10, stats.T("type", "testing"))
checkMeasuresEqual(t, eng,
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("size", 42, stats.Histogram)},
Tags: []stats.Tag{stats.T("service", "test-service")},
},
stats.Measure{
Name: "test.measure",
Fields: []stats.Field{stats.MakeField("size", 10, stats.Histogram)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
)
}
func testEngineReport(t *testing.T, eng *stats.Engine) {
m := struct {
Count int `metric:"count" type:"counter"`
}{42}
eng.Report(m)
eng.Report(m, stats.T("type", "testing"))
checkMeasuresEqual(t, eng,
stats.Measure{
Name: "test",
Fields: []stats.Field{stats.MakeField("count", 42, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service")},
},
stats.Measure{
Name: "test",
Fields: []stats.Field{stats.MakeField("count", 42, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
)
}
func testEngineReportArray(t *testing.T, eng *stats.Engine) {
m := [2]struct {
Count int `metric:"count" type:"counter"`
}{}
m[0].Count = 1
m[1].Count = 2
eng.Report(m, stats.T("type", "testing"))
checkMeasuresEqual(t, eng,
stats.Measure{
Name: "test",
Fields: []stats.Field{stats.MakeField("count", 1, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
stats.Measure{
Name: "test",
Fields: []stats.Field{stats.MakeField("count", 2, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
)
}
func testEngineReportSlice(t *testing.T, eng *stats.Engine) {
m := []struct {
Count int `metric:"count" type:"counter"`
}{{}, {}}
m[0].Count = 1
m[1].Count = 2
eng.Report(m, stats.T("type", "testing"))
checkMeasuresEqual(t, eng,
stats.Measure{
Name: "test",
Fields: []stats.Field{stats.MakeField("count", 1, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
stats.Measure{
Name: "test",
Fields: []stats.Field{stats.MakeField("count", 2, stats.Counter)},
Tags: []stats.Tag{stats.T("service", "test-service"), stats.T("type", "testing")},
},
)
}
func testEngineClock(t *testing.T, eng *stats.Engine) {
c := eng.Clock("upload", stats.T("f", "img.jpg"))
c.Stamp("compress")
c.Stamp("grayscale")
c.Stop()
found := measures(t, eng)
if len(found) != 3 {
t.Fatalf("expected 3 measures got %d", len(found))
}
stamps := []string{"compress", "grayscale", "total"}
for i, m := range found {
if m.Name != "test" {
t.Errorf("measure name mismatch, got %q", m.Name)
}
if len(m.Tags) != 3 {
t.Errorf("expected 3 tags, got %d", len(m.Tags))
}
exp := []stats.Tag{
stats.T("f", "img.jpg"),
stats.T("service", "test-service"),
stats.T("stamp", stamps[i]),
}
if !reflect.DeepEqual(m.Tags, exp) {
t.Errorf("tag mismatch, expected %v, got %v", exp, m.Tags)
}
}
}
func checkMeasuresEqual(t *testing.T, eng *stats.Engine, expected ...stats.Measure) {
found := measures(t, eng)
if !reflect.DeepEqual(found, expected) {
t.Error("bad measures:")
t.Logf("expected: %#v", expected)
t.Logf("found: %#v", found)
}
}
func measures(t *testing.T, eng *stats.Engine) []stats.Measure {
t.Helper()
return eng.Handler.(*statstest.Handler).Measures()
}
func BenchmarkEngine(b *testing.B) {
engines := []struct {
name string
value stats.Engine
}{
{
name: "discard",
value: stats.Engine{Handler: stats.Discard},
},
{
name: "datadog",
value: stats.Engine{Handler: datadog.NewClientWith(datadog.ClientConfig{
BufferSize: datadog.MaxBufferSize,
})},
},
{
name: "influxdb",
value: stats.Engine{Handler: influxdb.NewClientWith(influxdb.ClientConfig{
Transport: &discardTransport{},
})},
},
{
name: "prometheus",
value: stats.Engine{Handler: &prometheus.Handler{}},
},
}
for i := range engines {
eng := &engines[i]
b.Run(eng.name, func(b *testing.B) {
tests := []struct {
scenario string
function func(*testing.PB, *stats.Engine)
}{
{
scenario: "Engine.Add.1x",
function: benchmarkEngineAdd1x,
},
{
scenario: "Engine.Set.1x",
function: benchmarkEngineSet1x,
},
{
scenario: "Engine.Observe.1x",
function: benchmarkEngineObserve1x,
},
{
scenario: "Engine.Add.10x",
function: benchmarkEngineAdd10x,
},
{
scenario: "Engine.Set.10x",
function: benchmarkEngineSet10x,
},
{
scenario: "Engine.Observe.10x",
function: benchmarkEngineObserve10x,
},
{
scenario: "Engine.ReportAt(struct)",
function: benchmarkEngineReportAtStruct,
},
{
scenario: "Engine.ReportAt(struct:large)",
function: benchmarkEngineReportAtStructLarge,
},
{
scenario: "Engine.ReportAt(array)",
function: benchmarkEngineReportAtArray,
},
{
scenario: "Engine.ReportAt(slice)",
function: benchmarkEngineReportAtSlice,
},
}
for _, test := range tests {
b.Run(test.scenario, func(b *testing.B) {
b.RunParallel(func(pb *testing.PB) { test.function(pb, &eng.value) })
})
}
})
}
}
func benchmarkEngineAdd1x(pb *testing.PB, e *stats.Engine) {
for pb.Next() {
e.Add("calls", 1)
}
}
func benchmarkEngineSet1x(pb *testing.PB, e *stats.Engine) {
for pb.Next() {
e.Set("calls", 1)
}
}
func benchmarkEngineObserve1x(pb *testing.PB, e *stats.Engine) {
for pb.Next() {
e.Observe("calls", 1)
}
}
func benchmarkEngineAdd10x(pb *testing.PB, e *stats.Engine) {
for pb.Next() {
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
e.Add("calls", 1)
}
}
func benchmarkEngineSet10x(pb *testing.PB, e *stats.Engine) {
for pb.Next() {
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
e.Set("calls", 1)
}
}
func benchmarkEngineObserve10x(pb *testing.PB, e *stats.Engine) {
for pb.Next() {
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
e.Observe("calls", 1)
}
}
func benchmarkEngineReportAtStruct(pb *testing.PB, e *stats.Engine) {
t := time.Now()
m := struct {
Calls int `metric:"calls" type:"counter"`
}{1}
for pb.Next() {
e.ReportAt(t, &m)
}
}
func benchmarkEngineReportAtStructLarge(pb *testing.PB, e *stats.Engine) {
t := time.Now()
m := struct {
Calls0 int `metric:"calls" type:"counter"`
Calls1 int `metric:"calls" type:"counter"`
Calls2 int `metric:"calls" type:"counter"`
Calls3 int `metric:"calls" type:"counter"`
Calls4 int `metric:"calls" type:"counter"`
Calls5 int `metric:"calls" type:"counter"`
Calls6 int `metric:"calls" type:"counter"`
Calls7 int `metric:"calls" type:"counter"`
Calls8 int `metric:"calls" type:"counter"`
Calls9 int `metric:"calls" type:"counter"`
}{}
for pb.Next() {
e.ReportAt(t, &m)
}
}
func benchmarkEngineReportAtArray(pb *testing.PB, e *stats.Engine) {
t := time.Now()
m := [1]struct {
Calls int `metric:"calls" type:"counter"`
}{}
m[0].Calls = 1
for pb.Next() {
e.ReportAt(t, &m)
}
}
func benchmarkEngineReportAtSlice(pb *testing.PB, e *stats.Engine) {
t := time.Now()
m := []struct {
Calls int `metric:"calls" type:"counter"`
}{{}}
m[0].Calls = 1
for pb.Next() {
e.ReportAt(t, &m)
}
}
type discardTransport struct{}
func (t *discardTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader("")),
Request: req,
}, nil
}
// TestVersionMetricsIncludeEngineTags verifies that version metrics include
// the engine's configured tags for service correlation.
func TestVersionMetricsIncludeEngineTags(t *testing.T) {
initValue := stats.GoVersionReportingEnabled
stats.GoVersionReportingEnabled = true
defer func() { stats.GoVersionReportingEnabled = initValue }()
h := &statstest.Handler{}
e := stats.NewEngine("test", h, stats.T("service", "my-app"), stats.T("env", "prod"))
// Trigger version reporting by sending a metric
e.Incr("trigger")
measures := h.Measures()
// Find version metrics
var statsVersionMeasure, goVersionMeasure *stats.Measure
for i := range measures {
switch measures[i].Name {
case "stats_version":
statsVersionMeasure = &measures[i]
case "go_version":
goVersionMeasure = &measures[i]
}
}
if statsVersionMeasure == nil {
t.Fatal("stats_version metric not found")
}
// Check that engine tags are present in stats_version
hasServiceTag := false
hasEnvTag := false
hasVersionTag := false
for _, tag := range statsVersionMeasure.Tags {
switch tag.Name {
case "service":
if tag.Value == "my-app" {
hasServiceTag = true
}
case "env":
if tag.Value == "prod" {
hasEnvTag = true
}
case "stats_version":
hasVersionTag = true
}
}
if !hasServiceTag {
t.Errorf("stats_version missing service tag, got tags: %v", statsVersionMeasure.Tags)
}
if !hasEnvTag {
t.Errorf("stats_version missing env tag, got tags: %v", statsVersionMeasure.Tags)
}
if !hasVersionTag {
t.Errorf("stats_version missing stats_version tag, got tags: %v", statsVersionMeasure.Tags)
}
// Check go_version if present (may be skipped for devel versions)
if goVersionMeasure != nil {
hasServiceTag = false
hasEnvTag = false
hasGoVersionTag := false
for _, tag := range goVersionMeasure.Tags {
switch tag.Name {
case "service":
if tag.Value == "my-app" {
hasServiceTag = true
}
case "env":
if tag.Value == "prod" {
hasEnvTag = true
}
case "go_version":
hasGoVersionTag = true
}
}
if !hasServiceTag {
t.Errorf("go_version missing service tag, got tags: %v", goVersionMeasure.Tags)
}
if !hasEnvTag {
t.Errorf("go_version missing env tag, got tags: %v", goVersionMeasure.Tags)
}
if !hasGoVersionTag {
t.Errorf("go_version missing go_version tag, got tags: %v", goVersionMeasure.Tags)
}
}
}
// TestVersionMetricsPrometheusNoTimestamp verifies that version metrics
// are reported with zero time so Prometheus doesn't include a stale timestamp.
func TestVersionMetricsPrometheusNoTimestamp(t *testing.T) {
initValue := stats.GoVersionReportingEnabled
stats.GoVersionReportingEnabled = true
defer func() { stats.GoVersionReportingEnabled = initValue }()
h := &prometheus.Handler{}
e := stats.NewEngine("", h)
// Trigger version reporting
e.Incr("trigger")
// Get prometheus output
var buf strings.Builder
h.WriteStats(&buf)
output := buf.String()
// The prometheus output should NOT contain timestamps for version metrics.
// Timestamps in Prometheus format appear as a number after the value, e.g.:
// metric_name 1 1496614320000
// If there's no timestamp, it's just:
// metric_name 1
lines := strings.Split(output, "\n")
for _, line := range lines {
// Skip empty lines, comments, and TYPE/HELP lines
if line == "" || strings.HasPrefix(line, "#") {
continue
}
// Check version metric lines
if strings.HasPrefix(line, "stats_version") || strings.HasPrefix(line, "go_version") {
// Count space-separated parts. With timestamp: "name{labels} value timestamp"
// Without timestamp: "name{labels} value"
parts := strings.Fields(line)
// After removing the metric name (possibly with labels), we should have just the value
// The metric line format is: name{label="value"} value [timestamp]
// So we expect 2 parts without timestamp, 3 with timestamp
if len(parts) > 2 {
t.Errorf("version metric appears to have timestamp: %q", line)
}
}
}
}