-
Notifications
You must be signed in to change notification settings - Fork 765
/
MetricViewTests.cs
1269 lines (1054 loc) · 46.5 KB
/
MetricViewTests.cs
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// <copyright file="MetricViewTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Diagnostics.Metrics;
using OpenTelemetry.Internal;
using OpenTelemetry.Tests;
using Xunit;
namespace OpenTelemetry.Metrics.Tests;
public class MetricViewTests : MetricTestsBase
{
private const int MaxTimeToAllowForFlush = 10000;
[Fact]
public void ViewToRenameMetric()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("name1", "renamed")
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting one metric stream.
var counterLong = meter.CreateCounter<long>("name1");
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("renamed", metric.Name);
}
[Theory]
[MemberData(nameof(MetricTestData.InvalidInstrumentNames), MemberType = typeof(MetricTestData))]
public void AddViewWithInvalidNameThrowsArgumentException(string viewNewName)
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithInvalidNameThrowsArgumentException");
var ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView("name1", viewNewName)
.AddInMemoryExporter(exportedItems)
.Build());
Assert.Contains($"Custom view name {viewNewName} is invalid.", ex.Message);
ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView("name1", new MetricStreamConfiguration() { Name = viewNewName })
.AddInMemoryExporter(exportedItems)
.Build());
Assert.Contains($"Custom view name {viewNewName} is invalid.", ex.Message);
}
[Fact]
public void AddViewWithNullMetricStreamConfigurationThrowsArgumentnullException()
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithInvalidNameThrowsArgumentException");
Assert.Throws<ArgumentNullException>(() => Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView("name1", (MetricStreamConfiguration)null)
.AddInMemoryExporter(exportedItems)
.Build());
}
[Fact]
public void AddViewWithNameThrowsInvalidArgumentExceptionWhenConflict()
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithGuaranteedConflictThrowsInvalidArgumentException");
Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView("instrumenta.*", name: "newname")
.AddInMemoryExporter(exportedItems)
.Build());
}
[Fact]
public void AddViewWithNameInMetricStreamConfigurationThrowsInvalidArgumentExceptionWhenConflict()
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithGuaranteedConflictThrowsInvalidArgumentException");
Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView("instrumenta.*", new MetricStreamConfiguration() { Name = "newname" })
.AddInMemoryExporter(exportedItems)
.Build());
}
[Fact]
public void AddViewWithExceptionInUserCallbackAppliedDefault()
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithExceptionInUserCallback");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView((instrument) => { throw new Exception("bad"); })
.AddInMemoryExporter(exportedItems)
.Build();
using (var inMemoryEventListener = new InMemoryEventListener(OpenTelemetrySdkEventSource.Log))
{
var counter1 = meter1.CreateCounter<long>("counter1");
counter1.Add(1);
Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 41));
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// Counter is still reported with default config
// even if View is ignored due to View exception.
Assert.Single(exportedItems);
}
[Fact]
public void AddViewWithExceptionInUserCallbackNoDefault()
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithExceptionInUserCallback");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView((instrument) => { throw new Exception("bad"); })
.AddView("*", MetricStreamConfiguration.Drop)
.AddInMemoryExporter(exportedItems)
.Build();
using (var inMemoryEventListener = new InMemoryEventListener(OpenTelemetrySdkEventSource.Log))
{
var counter1 = meter1.CreateCounter<long>("counter1");
counter1.Add(1);
Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 41));
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// Counter is not reported.
// as the View is ignored due to View exception.
// and Default is suppressed with * -> Drop
Assert.Empty(exportedItems);
}
[Fact]
public void AddViewsWithAndWithoutExceptionInUserCallback()
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithExceptionInUserCallback");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView((instrument) => { throw new Exception("bad"); })
.AddView((instrument) => { return new MetricStreamConfiguration() { Name = "newname" }; })
.AddInMemoryExporter(exportedItems)
.Build();
using (var inMemoryEventListener = new InMemoryEventListener(OpenTelemetrySdkEventSource.Log))
{
var counter1 = meter1.CreateCounter<long>("counter1");
counter1.Add(1);
Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 41));
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// Counter is still reported with 2nd View
// even if 1st View is ignored due to View exception.
Assert.Single(exportedItems);
Assert.Equal("newname", exportedItems[0].Name);
}
[Theory]
[MemberData(nameof(MetricTestData.InvalidHistogramBoundaries), MemberType = typeof(MetricTestData))]
public void AddViewWithInvalidHistogramBoundsThrowsArgumentException(double[] boundaries)
{
var ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder()
.AddView("name1", new ExplicitBucketHistogramConfiguration { Boundaries = boundaries }));
Assert.Contains("Histogram boundaries must be in ascending order with distinct values", ex.Message);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void AddViewWithInvalidExponentialHistogramMaxSizeConfigThrowsArgumentException(int maxSize)
{
var ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder()
.AddView("name1", new Base2ExponentialBucketHistogramConfiguration { MaxSize = maxSize }));
Assert.Contains("Histogram max size is invalid", ex.Message);
}
[Theory]
[InlineData(-12)]
[InlineData(21)]
public void AddViewWithInvalidExponentialHistogramMaxScaleConfigThrowsArgumentException(int maxScale)
{
var ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder()
.AddView("name1", new Base2ExponentialBucketHistogramConfiguration { MaxScale = maxScale }));
Assert.Contains("Histogram max scale is invalid", ex.Message);
}
[Theory]
[MemberData(nameof(MetricTestData.InvalidHistogramBoundaries), MemberType = typeof(MetricTestData))]
public void AddViewWithInvalidHistogramBoundsIgnored(double[] boundaries)
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("AddViewWithInvalidHistogramBoundsIgnored");
var counter1 = meter1.CreateCounter<long>("counter1");
using (var provider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView((instrument) =>
{
return instrument.Name == counter1.Name
? new ExplicitBucketHistogramConfiguration() { Boundaries = boundaries }
: null;
})
.AddInMemoryExporter(exportedItems)
.Build())
{
counter1.Add(1);
}
// Counter is aggregated with default configuration
// as the View config is ignored due to invalid histogram bounds.
Assert.Single(exportedItems);
}
[Theory]
[MemberData(nameof(MetricTestData.ValidInstrumentNames), MemberType = typeof(MetricTestData))]
public void ViewWithValidNameExported(string viewNewName)
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter("ViewWithInvalidNameIgnoredTest");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView("name1", viewNewName)
.AddInMemoryExporter(exportedItems)
.Build();
var counterLong = meter1.CreateCounter<long>("name1");
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// Expecting one metric stream.
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal(viewNewName, metric.Name);
}
[Fact]
public void ViewToRenameMetricConditionally()
{
using var meter1 = new Meter($"{Utils.GetCurrentMethodName()}.1");
using var meter2 = new Meter($"{Utils.GetCurrentMethodName()}.2");
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddMeter(meter2.Name)
.AddView((instrument) =>
{
if (instrument.Meter.Name.Equals(meter2.Name, StringComparison.OrdinalIgnoreCase)
&& instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase))
{
return new MetricStreamConfiguration() { Name = "name1_Renamed", Description = "new description" };
}
else
{
return null;
}
})
.AddInMemoryExporter(exportedItems)
.Build();
// Without views only 1 stream would be
// exported (the 2nd one gets dropped due to
// name conflict). Due to renaming with Views,
// we expect 2 metric streams here.
var counter1 = meter1.CreateCounter<long>("name1", "unit", "original_description");
var counter2 = meter2.CreateCounter<long>("name1", "unit", "original_description");
counter1.Add(10);
counter2.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
Assert.Equal("name1", exportedItems[0].Name);
Assert.Equal("name1_Renamed", exportedItems[1].Name);
Assert.Equal("original_description", exportedItems[0].Description);
Assert.Equal("new description", exportedItems[1].Description);
}
[Theory]
[MemberData(nameof(MetricTestData.InvalidInstrumentNames), MemberType = typeof(MetricTestData))]
public void ViewWithInvalidNameIgnoredConditionally(string viewNewName)
{
using var meter1 = new Meter("ViewToRenameMetricConditionallyTest");
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
// since here it's a func, we can't validate the name right away
// so the view is allowed to be added, but upon instrument creation it's going to be ignored.
.AddView((instrument) =>
{
if (instrument.Meter.Name.Equals(meter1.Name, StringComparison.OrdinalIgnoreCase)
&& instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase))
{
// invalid instrument name as per the spec
return new MetricStreamConfiguration() { Name = viewNewName, Description = "new description" };
}
else
{
return null;
}
})
.AddInMemoryExporter(exportedItems)
.Build();
// Because the MetricStreamName passed is invalid, the view is ignored,
// and default aggregation is used.
var counter1 = meter1.CreateCounter<long>("name1", "unit", "original_description");
counter1.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
}
[Theory]
[MemberData(nameof(MetricTestData.ValidInstrumentNames), MemberType = typeof(MetricTestData))]
public void ViewWithValidNameConditionally(string viewNewName)
{
using var meter1 = new Meter("ViewToRenameMetricConditionallyTest");
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddView((instrument) =>
{
if (instrument.Meter.Name.Equals(meter1.Name, StringComparison.OrdinalIgnoreCase)
&& instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase))
{
// invalid instrument name as per the spec
return new MetricStreamConfiguration() { Name = viewNewName, Description = "new description" };
}
else
{
return null;
}
})
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting one metric stream.
var counter1 = meter1.CreateCounter<long>("name1", "unit", "original_description");
counter1.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// Expecting one metric stream.
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal(viewNewName, metric.Name);
}
[Fact]
public void ViewWithNullCustomNameTakesInstrumentName()
{
var exportedItems = new List<Metric>();
using var meter = new Meter("ViewToRenameMetricConditionallyTest");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView((instrument) =>
{
if (instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase))
{
// null View name
return new MetricStreamConfiguration() { };
}
else
{
return null;
}
})
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting one metric stream.
// Since the View name was null, the instrument name was used instead
var counter1 = meter.CreateCounter<long>("name1", "unit", "original_description");
counter1.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// Expecting one metric stream.
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal(counter1.Name, metric.Name);
}
[Fact]
public void ViewToProduceMultipleStreamsFromInstrument()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("name1", "renamedStream1")
.AddView("name1", "renamedStream2")
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting two metric stream.
var counterLong = meter.CreateCounter<long>("name1");
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
Assert.Equal("renamedStream1", exportedItems[0].Name);
Assert.Equal("renamedStream2", exportedItems[1].Name);
}
[Fact]
public void ViewToProduceMultipleStreamsWithDuplicatesFromInstrument()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("name1", "renamedStream1")
.AddView("name1", "renamedStream2")
.AddView("name1", "renamedStream2")
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting three metric stream.
// the second .AddView("name1", "renamedStream2")
// produces a conflicting metric stream.
var counterLong = meter.CreateCounter<long>("name1");
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(3, exportedItems.Count);
Assert.Equal("renamedStream1", exportedItems[0].Name);
Assert.Equal("renamedStream2", exportedItems[1].Name);
Assert.Equal("renamedStream2", exportedItems[2].Name);
}
[Fact]
public void ViewWithHistogramConfigurationIgnoredWhenAppliedToNonHistogram()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("NotAHistogram", new ExplicitBucketHistogramConfiguration() { Name = "ImAnExplicitBoundsHistogram" })
.AddView("NotAHistogram", new Base2ExponentialBucketHistogramConfiguration() { Name = "ImAnExponentialHistogram" })
.AddInMemoryExporter(exportedItems)
.Build();
var counter = meter.CreateCounter<long>("NotAHistogram");
counter.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("NotAHistogram", metric.Name);
List<MetricPoint> metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
var metricPoint = metricPoints[0];
Assert.Equal(10, metricPoint.GetSumLong());
}
[Fact]
public void ViewToProduceCustomHistogramBound()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
var boundaries = new double[] { 10, 20 };
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("MyHistogram", new ExplicitBucketHistogramConfiguration() { Name = "MyHistogramDefaultBound" })
.AddView("MyHistogram", new ExplicitBucketHistogramConfiguration() { Boundaries = boundaries })
.AddInMemoryExporter(exportedItems)
.Build();
var histogram = meter.CreateHistogram<long>("MyHistogram");
histogram.Record(-10);
histogram.Record(0);
histogram.Record(1);
histogram.Record(9);
histogram.Record(10);
histogram.Record(11);
histogram.Record(19);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
var metricDefault = exportedItems[0];
var metricCustom = exportedItems[1];
Assert.Equal("MyHistogramDefaultBound", metricDefault.Name);
Assert.Equal("MyHistogram", metricCustom.Name);
List<MetricPoint> metricPointsDefault = new List<MetricPoint>();
foreach (ref readonly var mp in metricDefault.GetMetricPoints())
{
metricPointsDefault.Add(mp);
}
Assert.Single(metricPointsDefault);
var histogramPoint = metricPointsDefault[0];
var count = histogramPoint.GetHistogramCount();
var sum = histogramPoint.GetHistogramSum();
Assert.Equal(40, sum);
Assert.Equal(7, count);
int index = 0;
int actualCount = 0;
var expectedBucketCounts = new long[] { 2, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets())
{
Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount);
index++;
actualCount++;
}
Assert.Equal(Metric.DefaultHistogramBounds.Length + 1, actualCount);
List<MetricPoint> metricPointsCustom = new List<MetricPoint>();
foreach (ref readonly var mp in metricCustom.GetMetricPoints())
{
metricPointsCustom.Add(mp);
}
Assert.Single(metricPointsCustom);
histogramPoint = metricPointsCustom[0];
count = histogramPoint.GetHistogramCount();
sum = histogramPoint.GetHistogramSum();
Assert.Equal(40, sum);
Assert.Equal(7, count);
index = 0;
actualCount = 0;
expectedBucketCounts = new long[] { 5, 2, 0 };
foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets())
{
Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount);
index++;
actualCount++;
}
Assert.Equal(boundaries.Length + 1, actualCount);
}
[Fact]
public void ViewToProduceExponentialHistogram()
{
var valuesToRecord = new[] { -10, 0, 1, 9, 10, 11, 19 };
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("MyHistogram", new Base2ExponentialBucketHistogramConfiguration())
.AddInMemoryExporter(exportedItems)
.Build();
var histogram = meter.CreateHistogram<long>("MyHistogram");
var expectedHistogram = new Base2ExponentialBucketHistogram();
foreach (var value in valuesToRecord)
{
histogram.Record(value);
if (value >= 0)
{
expectedHistogram.Record(value);
}
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("MyHistogram", metric.Name);
var metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
var metricPoint = metricPoints[0];
var count = metricPoint.GetHistogramCount();
var sum = metricPoint.GetHistogramSum();
AggregatorTestsBase.AssertExponentialBucketsAreCorrect(expectedHistogram, metricPoint.GetExponentialHistogramData());
Assert.Equal(50, sum);
Assert.Equal(6, count);
}
[Theory]
[MemberData(nameof(MetricTestData.ValidHistogramMinMax), MemberType = typeof(MetricTestData))]
public void HistogramMinMax(double[] values, HistogramConfiguration histogramConfiguration, double expectedMin, double expectedMax)
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var histogram = meter.CreateHistogram<double>("MyHistogram");
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView(histogram.Name, histogramConfiguration)
.AddInMemoryExporter(exportedItems)
.Build();
for (var i = 0; i < values.Length; i++)
{
histogram.Record(values[i]);
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
var metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in exportedItems[0].GetMetricPoints())
{
metricPoints.Add(mp);
}
var histogramPoint = metricPoints[0];
if (histogramPoint.TryGetHistogramMinMaxValues(out double min, out double max))
{
Assert.Equal(expectedMin, min);
Assert.Equal(expectedMax, max);
}
else
{
Assert.Fail("MinMax expected");
}
}
[Theory]
[MemberData(nameof(MetricTestData.InvalidHistogramMinMax), MemberType = typeof(MetricTestData))]
public void HistogramMinMaxNotPresent(double[] values, HistogramConfiguration histogramConfiguration)
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var histogram = meter.CreateHistogram<double>("MyHistogram");
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView(histogram.Name, histogramConfiguration)
.AddInMemoryExporter(exportedItems)
.Build();
for (var i = 0; i < values.Length; i++)
{
histogram.Record(values[i]);
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
var metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in exportedItems[0].GetMetricPoints())
{
metricPoints.Add(mp);
}
var histogramPoint = metricPoints[0];
Assert.False(histogramPoint.TryGetHistogramMinMaxValues(out double _, out double _));
}
[Fact]
public void ViewToSelectTagKeys()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("FruitCounter", new MetricStreamConfiguration()
{
TagKeys = new string[] { "name" },
Name = "NameOnly",
})
.AddView("FruitCounter", new MetricStreamConfiguration()
{
TagKeys = new string[] { "size" },
Name = "SizeOnly",
})
.AddView("FruitCounter", new MetricStreamConfiguration()
{
TagKeys = Array.Empty<string>(),
Name = "NoTags",
})
.AddInMemoryExporter(exportedItems)
.Build();
var counter = meter.CreateCounter<long>("FruitCounter");
counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "small"));
counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "small"));
counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "medium"));
counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "medium"));
counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "large"));
counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "large"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(3, exportedItems.Count);
var metric = exportedItems[0];
Assert.Equal("NameOnly", metric.Name);
List<MetricPoint> metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
// Only one point expected "apple"
Assert.Single(metricPoints);
metric = exportedItems[1];
Assert.Equal("SizeOnly", metric.Name);
metricPoints.Clear();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
// 3 points small,medium,large expected
Assert.Equal(3, metricPoints.Count);
metric = exportedItems[2];
Assert.Equal("NoTags", metric.Name);
metricPoints.Clear();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
// Single point expected.
Assert.Single(metricPoints);
}
[Fact]
public void ViewToDropSingleInstrument()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("counterNotInteresting", MetricStreamConfiguration.Drop)
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting one metric stream.
var counterInteresting = meter.CreateCounter<long>("counterInteresting");
var counterNotInteresting = meter.CreateCounter<long>("counterNotInteresting");
counterInteresting.Add(10);
counterNotInteresting.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("counterInteresting", metric.Name);
}
[Fact]
public void ViewToDropSingleInstrumentObservableCounter()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("observableCounterNotInteresting", MetricStreamConfiguration.Drop)
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting one metric stream.
meter.CreateObservableCounter("observableCounterNotInteresting", () => { return 10; }, "ms");
meter.CreateObservableCounter("observableCounterInteresting", () => { return 10; }, "ms");
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("observableCounterInteresting", metric.Name);
}
[Fact]
public void ViewToDropSingleInstrumentObservableGauge()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("observableGaugeNotInteresting", MetricStreamConfiguration.Drop)
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting one metric stream.
meter.CreateObservableGauge("observableGaugeNotInteresting", () => { return 10; }, "ms");
meter.CreateObservableGauge("observableGaugeInteresting", () => { return 10; }, "ms");
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("observableGaugeInteresting", metric.Name);
}
[Fact]
public void ViewToDropMultipleInstruments()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("server*", MetricStreamConfiguration.Drop)
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting two client metric streams as both server* are dropped.
var serverRequests = meter.CreateCounter<long>("server.requests");
var serverExceptions = meter.CreateCounter<long>("server.exceptions");
var clientRequests = meter.CreateCounter<long>("client.requests");
var clientExceptions = meter.CreateCounter<long>("client.exceptions");
serverRequests.Add(10);
serverExceptions.Add(10);
clientRequests.Add(10);
clientExceptions.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
Assert.Equal("client.requests", exportedItems[0].Name);
Assert.Equal("client.exceptions", exportedItems[1].Name);
}
[Fact]
public void ViewToDropAndRetainInstrument()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("server.requests", MetricStreamConfiguration.Drop)
.AddView("server.requests", "server.request_renamed")
.AddInMemoryExporter(exportedItems)
.Build();
// Expecting one metric stream even though a View is asking
// to drop the instrument, because another View is matching
// the instrument, which asks to aggregate with defaults
// and a use a new name for the resulting metric.
var serverRequests = meter.CreateCounter<long>("server.requests");
serverRequests.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
Assert.Equal("server.request_renamed", exportedItems[0].Name);
}
[Fact]
public void ViewConflict_OneInstrument_DifferentDescription()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("instrumentName", new MetricStreamConfiguration() { Description = "newDescription1" })
.AddView("instrumentName", new MetricStreamConfiguration() { Description = "newDescription2" })
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription");
instrument.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
var metric1 = exportedItems[0];
var metric2 = exportedItems[1];
Assert.Equal("newDescription1", metric1.Description);
Assert.Equal("newDescription2", metric2.Description);
List<MetricPoint> metric1MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric1.GetMetricPoints())
{
metric1MetricPoints.Add(mp);
}
Assert.Single(metric1MetricPoints);
var metricPoint1 = metric1MetricPoints[0];
Assert.Equal(10, metricPoint1.GetSumLong());
List<MetricPoint> metric2MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric2.GetMetricPoints())
{
metric2MetricPoints.Add(mp);
}
Assert.Single(metric2MetricPoints);
var metricPoint2 = metric2MetricPoints[0];
Assert.Equal(10, metricPoint2.GetSumLong());
}
[Fact]
public void ViewConflict_TwoDistinctInstruments_ThreeStreams()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView((instrument) =>
{
return new MetricStreamConfiguration() { Name = "MetricStreamA", Description = "description" };
})
.AddView((instrument) =>
{
return instrument.Description == "description1"
? new MetricStreamConfiguration() { Name = "MetricStreamB" }
: new MetricStreamConfiguration() { Name = "MetricStreamC" };
})
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument1 = meter.CreateCounter<long>("name", "unit", "description1");
var instrument2 = meter.CreateCounter<long>("name", "unit", "description2");
instrument1.Add(10);
instrument2.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(3, exportedItems.Count);
var metricA = exportedItems[0];
var metricB = exportedItems[1];
var metricC = exportedItems[2];
Assert.Equal("MetricStreamA", metricA.Name);
Assert.Equal(20, GetAggregatedValue(metricA));
Assert.Equal("MetricStreamB", metricB.Name);
Assert.Equal(10, GetAggregatedValue(metricB));
Assert.Equal("MetricStreamC", metricC.Name);
Assert.Equal(10, GetAggregatedValue(metricC));
long GetAggregatedValue(Metric metric)
{
var metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
return metricPoints[0].GetSumLong();
}