Given tests: order arrivals by limiter state instead of sleeps (limiter, spread, cancel-while-queued)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
2026-09-25 11:20:26 -07:00
co-authored by Claude Fable 5.1
parent 6c3a2cff8a
commit 98faa3a57d
7 changed files with 46 additions and 24 deletions
@@ -39,10 +39,7 @@ func TestParallelAndQueue(t *testing.T) {
}
got3 <- err
}()
time.Sleep(20 * time.Millisecond)
if l.Queued("alpha", "m") != 1 {
t.Errorf("queued = %d, want 1", l.Queued("alpha", "m"))
}
waitUntil(t, func() bool { return l.Queued("alpha", "m") == 1 })
// Fourth finds the queue full and is refused at once.
start := time.Now()
_, _, err = l.Acquire(ctx, "alpha", "m")
@@ -52,8 +49,8 @@ func TestParallelAndQueue(t *testing.T) {
if time.Since(start) > 50*time.Millisecond {
t.Errorf("a full queue must refuse immediately, took %v", time.Since(start))
}
time.Sleep(30 * time.Millisecond)
rel1() // frees a slot: the queued third proceeds
time.Sleep(50 * time.Millisecond) // a lower bound on the third's wait, checked above as >= 40 ms
rel1() // frees a slot: the queued third proceeds
select {
case err := <-got3:
if err != nil {
@@ -95,7 +92,7 @@ func TestCancelWhileQueuedLeaksNothing(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { _, _, err := l.Acquire(ctx, "h", "m"); done <- err }()
time.Sleep(20 * time.Millisecond)
waitUntil(t, func() bool { return l.Queued("h", "m") == 1 })
cancel()
select {
case err := <-done:
@@ -139,7 +136,7 @@ func TestQueueIsFIFO(t *testing.T) {
time.Sleep(5 * time.Millisecond)
r()
}(i)
time.Sleep(15 * time.Millisecond) // stagger arrivals so the order is defined
waitUntil(t, func() bool { return l.Queued("h", "m") == i }) // arrivals in order, by observation
}
rel()
wg.Wait()
@@ -176,3 +173,16 @@ func TestFreeSlotsSumsModels(t *testing.T) {
t.Errorf("unknown host has no slots")
}
}
// waitUntil polls cond every millisecond for up to two seconds and fails the test if it never holds.
func waitUntil(t *testing.T, cond func() bool) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("condition not reached within two seconds")
}