|
| 1 | +package kubernetes |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/require" |
| 8 | +) |
| 9 | + |
| 10 | +func TestCalculateBackoff(t *testing.T) { |
| 11 | + const ( |
| 12 | + baseDelay = 500 * time.Millisecond |
| 13 | + maxDelay = 10 * time.Second |
| 14 | + ) |
| 15 | + tests := []struct { |
| 16 | + attempt int |
| 17 | + floor, cap time.Duration |
| 18 | + }{ |
| 19 | + {0, 500 * time.Millisecond, time.Second}, |
| 20 | + {1, time.Second, 2 * time.Second}, |
| 21 | + {2, 2 * time.Second, 4 * time.Second}, |
| 22 | + {3, 4 * time.Second, 8 * time.Second}, |
| 23 | + {4, 8 * time.Second, maxDelay}, |
| 24 | + {5, maxDelay, maxDelay}, |
| 25 | + {20, maxDelay, maxDelay}, |
| 26 | + } |
| 27 | + for _, tt := range tests { |
| 28 | + seen := make(map[time.Duration]struct{}) |
| 29 | + for range 500 { |
| 30 | + got := calculateBackoff(tt.attempt, baseDelay, maxDelay) |
| 31 | + require.GreaterOrEqual(t, got, tt.floor, "attempt %d must never wait less than the exponential schedule", tt.attempt) |
| 32 | + require.LessOrEqual(t, got, tt.cap, "attempt %d must not exceed twice the schedule, nor maxDelay", tt.attempt) |
| 33 | + seen[got] = struct{}{} |
| 34 | + } |
| 35 | + if tt.floor < tt.cap { |
| 36 | + // The narrowest jittered range is 500ms wide, so a single distinct |
| 37 | + // value across 500 draws would not be chance. |
| 38 | + require.Greater(t, len(seen), 1, "attempt %d must vary so concurrent builders do not retry in lockstep", tt.attempt) |
| 39 | + } |
| 40 | + } |
| 41 | +} |
0 commit comments