| package handler |
|
|
| import ( |
| "testing" |
| "time" |
|
|
| "github.com/stretchr/testify/assert" |
| "github.com/stretchr/testify/require" |
| ) |
|
|
| |
|
|
| func TestNextBackoff_ExponentialGrowth(t *testing.T) { |
| |
| |
| current := initialBackoff |
|
|
| for i := 0; i < 10; i++ { |
| next := nextBackoff(current) |
|
|
| |
| assert.GreaterOrEqual(t, int64(next), int64(initialBackoff), |
| "第 %d 次退避不应低于初始值 %v", i, initialBackoff) |
| assert.LessOrEqual(t, int64(next), int64(maxBackoff), |
| "第 %d 次退避不应超过最大值 %v", i, maxBackoff) |
|
|
| |
| current = next |
| } |
| } |
|
|
| func TestNextBackoff_BoundedByMaxBackoff(t *testing.T) { |
| |
| for i := 0; i < 100; i++ { |
| result := nextBackoff(10 * time.Second) |
| assert.LessOrEqual(t, int64(result), int64(maxBackoff), |
| "退避值不应超过 maxBackoff") |
| } |
| } |
|
|
| func TestNextBackoff_BoundedByInitialBackoff(t *testing.T) { |
| |
| for i := 0; i < 100; i++ { |
| result := nextBackoff(1 * time.Millisecond) |
| assert.GreaterOrEqual(t, int64(result), int64(initialBackoff), |
| "退避值不应低于 initialBackoff") |
| } |
| } |
|
|
| func TestNextBackoff_HasJitter(t *testing.T) { |
| |
| |
| results := make(map[time.Duration]bool) |
| current := 500 * time.Millisecond |
|
|
| for i := 0; i < 50; i++ { |
| result := nextBackoff(current) |
| results[result] = true |
| } |
|
|
| |
| require.Greater(t, len(results), 1, |
| "nextBackoff 应产生随机抖动,但所有 50 次调用结果相同") |
| } |
|
|
| func TestNextBackoff_InitialValueGrows(t *testing.T) { |
| |
| current := initialBackoff |
| var sum time.Duration |
|
|
| runs := 100 |
| for i := 0; i < runs; i++ { |
| next := nextBackoff(current) |
| sum += next |
| current = next |
| } |
|
|
| avg := sum / time.Duration(runs) |
| |
| assert.Greater(t, int64(avg), int64(initialBackoff), |
| "平均退避时间应大于初始退避值") |
| } |
|
|
| func TestNextBackoff_ConvergesToMaxBackoff(t *testing.T) { |
| |
| current := initialBackoff |
| for i := 0; i < 20; i++ { |
| current = nextBackoff(current) |
| } |
|
|
| |
| |
| lowerBound := time.Duration(float64(maxBackoff) * 0.8) |
| assert.GreaterOrEqual(t, int64(current), int64(lowerBound), |
| "经过多次退避后应收敛到 maxBackoff 附近") |
| } |
|
|
| func BenchmarkNextBackoff(b *testing.B) { |
| current := initialBackoff |
| for i := 0; i < b.N; i++ { |
| current = nextBackoff(current) |
| if current > maxBackoff { |
| current = initialBackoff |
| } |
| } |
| } |
|
|