diff --git a/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/LogCollector.cs b/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/LogCollector.cs index bdb5ff981c0..553fe1f1cd4 100644 --- a/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/LogCollector.cs +++ b/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/LogCollector.cs @@ -31,6 +31,46 @@ public void WriteTo(ITestOutputHelper log) } } + public async Task WaitForLogsAsync(int[] expectedErrorIds, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + lock (_items) + { + // Check for exact match to avoid race conditions with AssertErrors + if (_items.Count == expectedErrorIds.Length) + { + bool match = true; + for (int i = 0; i < expectedErrorIds.Length; i++) + { + if (_items[i].eventId.Id != expectedErrorIds[i]) + { + match = false; + break; + } + } + + if (match) + { + return; // Success + } + } + + // If we have more logs than expected, something unexpected happened + // Stop waiting to let AssertErrors report the mismatch + if (_items.Count > expectedErrorIds.Length) + { + return; + } + } + + await Task.Delay(10); + } + + // Timeout reached, will fail in AssertErrors + } + public void AssertErrors(int[] errorIds) { lock (_items) diff --git a/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/UnreliableL2Tests.cs b/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/UnreliableL2Tests.cs index f6232357651..bba5020f58b 100644 --- a/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/UnreliableL2Tests.cs +++ b/test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/UnreliableL2Tests.cs @@ -43,7 +43,9 @@ public async Task WriteFailureInvisible(BreakType writeBreak, params int[] error } await l2.LastWrite; // allows out-of-band write to complete - await Task.Delay(150); // even then: thread jitter can cause problems + + // Wait for logs to be written (with timeout to avoid hanging on failure) + await log.WaitForLogsAsync(errorIds, TimeSpan.FromSeconds(5)); log.WriteTo(testLog); log.AssertErrors(errorIds);