Skip to content

Commit f02da12

Browse files
committed
Make test less brittle
1 parent 19a6754 commit f02da12

File tree

1 file changed

+40
-8
lines changed

1 file changed

+40
-8
lines changed

src/libraries/System.Diagnostics.DiagnosticSource/tests/RuntimeMetricsTests.cs

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,59 @@ public async Task GcCollectionsCount()
1818
using InstrumentRecorder<long> instrumentRecorder = new("dotnet.gc.collections.count");
1919
using CancellationTokenSource cts = new(1000);
2020

21+
var token = cts.Token;
22+
token.Register(() => Assert.Fail("Timed out waiting for measurements."));
23+
2124
for (var gen = 0; gen <= GC.MaxGeneration; gen++)
2225
{
2326
GC.Collect(gen, GCCollectionMode.Forced);
2427
}
2528

2629
instrumentRecorder.RecordObservableInstruments();
2730

28-
(bool success, IReadOnlyList<Measurement<long>> measurements) = await WaitForMeasurements(instrumentRecorder, 3, cts.Token);
31+
(bool success, IReadOnlyList<Measurement<long>> measurements) = await WaitForMeasurements(instrumentRecorder, GC.MaxGeneration + 1, token);
2932

30-
Assert.True(success, "Expected to receive at least 3 measurements.");
33+
Assert.True(success, "Expected to receive at least 1 measurement per generation.");
3134

32-
int count = 0;
33-
for (int i = GC.MaxGeneration; i >= 0; i--)
35+
bool[] foundGenerations = new bool[GC.MaxGeneration + 1];
36+
for (int i = 0; i < GC.MaxGeneration + 1; i++)
3437
{
35-
Measurement<long> measurement = measurements[count++];
36-
Assert.True(measurement.Value > 0, $"Gen {i} count should be greater than zero.");
38+
foundGenerations[i] = false;
39+
}
3740

41+
foreach (Measurement<long> measurement in measurements.Where(m => m.Value >= 1))
42+
{
3843
var tags = measurement.Tags.ToArray();
3944

40-
Assert.Equal(1, tags.Length);
41-
VerifyTag(tags, "gc.heap.generation", $"gen{i}");
45+
var tag = tags.SingleOrDefault(k => k.Key == "gc.heap.generation");
46+
47+
if (tag.Key is not null)
48+
{
49+
Assert.True(tag.Value is string, "Expected generation tag to be a string.");
50+
51+
string tagValue = (string)tag.Value;
52+
53+
switch (tagValue)
54+
{
55+
case "gen0":
56+
foundGenerations[0] = true;
57+
break;
58+
case "gen1":
59+
foundGenerations[1] = true;
60+
break;
61+
case "gen2":
62+
foundGenerations[2] = true;
63+
break;
64+
default:
65+
Assert.Fail("Unexpected generation tag value.");
66+
break;
67+
}
68+
}
69+
}
70+
71+
foreach (var found in foundGenerations)
72+
{
73+
Assert.True(found, "Expected to find a measurement for each generation (0, 1 and 2).");
4274
}
4375
}
4476

0 commit comments

Comments
 (0)