Skip to content

Commit 6e25f07

Browse files
[Hangfire] Fix flaky test
- Avoid `InvalidOperationException` by copying collection before passing to `Any()`. - Refactor `while` loop to improve readability.
1 parent ed58954 commit 6e25f07

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
using System.Diagnostics;
55
using Hangfire;
6-
using Hangfire.Storage.Monitoring;
76
using OpenTelemetry.Trace;
87
using Xunit;
98

@@ -173,13 +172,29 @@ public async Task Should_Respect_Filter_Option(string filter, bool shouldRecord)
173172

174173
private async Task WaitJobProcessedAsync(string jobId, int timeToWaitInSeconds)
175174
{
176-
var timeout = DateTime.Now.AddSeconds(timeToWaitInSeconds);
175+
var timeout = TimeSpan.FromSeconds(timeToWaitInSeconds);
176+
using var cts = new CancellationTokenSource(timeout);
177+
177178
string[] states = ["Enqueued", "Processing"];
178-
JobDetailsDto jobDetails;
179-
while (((jobDetails = this.hangfireFixture.MonitoringApi.JobDetails(jobId)) == null || jobDetails.History.All(h => states.Contains(h.StateName)))
180-
&& DateTime.Now < timeout)
179+
180+
while (!Completed() && !cts.IsCancellationRequested)
181181
{
182182
await Task.Delay(500);
183183
}
184+
185+
bool Completed()
186+
{
187+
var jobDetails = this.hangfireFixture.MonitoringApi.JobDetails(jobId);
188+
189+
if (jobDetails == null)
190+
{
191+
return false;
192+
}
193+
194+
// Copy the history to an array to avoid exception if the collection is modified while iterating
195+
var history = jobDetails.History.ToArray();
196+
197+
return !history.All(h => states.Contains(h.StateName));
198+
}
184199
}
185200
}

0 commit comments

Comments
 (0)