| 1 | package g8 |
| 2 | |
| 3 | import ( |
| 4 | "testing" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | func TestNewRateLimiter(t *testing.T) { |
| 9 | rl := NewRateLimiter(2) |
| 10 | if rl.maximumExecutionsPerSecond != 2 { |
| 11 | t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond) |
| 12 | } |
| 13 | if rl.executionsLeftInWindow != 2 { |
| 14 | t.Errorf("expected executionsLeftInWindow to be %d, got %d", 2, rl.executionsLeftInWindow) |
| 15 | } |
| 16 | // First execution: should not be rate limited |
| 17 | if notRateLimited := rl.Try(); !notRateLimited { |
| 18 | t.Error("expected Try to return true") |
| 19 | } |
| 20 | if rl.maximumExecutionsPerSecond != 2 { |
| 21 | t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond) |
| 22 | } |
| 23 | if rl.executionsLeftInWindow != 1 { |
| 24 | t.Errorf("expected executionsLeftInWindow to be %d, got %d", 1, rl.executionsLeftInWindow) |
| 25 | } |
| 26 | // Second execution: should not be rate limited |
| 27 | if notRateLimited := rl.Try(); !notRateLimited { |
| 28 | t.Error("expected Try to return true") |
| 29 | } |
| 30 | if rl.maximumExecutionsPerSecond != 2 { |
| 31 | t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond) |
| 32 | } |
| 33 | if rl.executionsLeftInWindow != 0 { |
| 34 | t.Errorf("expected executionsLeftInWindow to be %d, got %d", 0, rl.executionsLeftInWindow) |
| 35 | } |
| 36 | // Third execution: should be rate limited |
| 37 | if notRateLimited := rl.Try(); notRateLimited { |
| 38 | t.Error("expected Try to return false") |
| 39 | } |
| 40 | if rl.maximumExecutionsPerSecond != 2 { |
| 41 | t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond) |
| 42 | } |
| 43 | if rl.executionsLeftInWindow != 0 { |
| 44 | t.Errorf("expected executionsLeftInWindow to be %d, got %d", 0, rl.executionsLeftInWindow) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | func TestRateLimiter_Try(t *testing.T) { |
| 49 | rl := NewRateLimiter(5) |
| 50 | for i := 0; i < 20; i++ { |
| 51 | notRateLimited := rl.Try() |
| 52 | if i < 5 { |
| 53 | if !notRateLimited { |
| 54 | t.Fatal("expected to not be rate limited") |
| 55 | } |
| 56 | } else { |
| 57 | if notRateLimited { |
| 58 | t.Fatal("expected to be rate limited") |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | func TestRateLimiter_TryAlwaysUnderRateLimit(t *testing.T) { |
| 65 | rl := NewRateLimiter(20) |
| 66 | for i := 0; i < 45; i++ { |
| 67 | notRateLimited := rl.Try() |
| 68 | if !notRateLimited { |
| 69 | t.Fatal("expected to not be rate limited") |
| 70 | } |
| 71 | time.Sleep(51 * time.Millisecond) |
| 72 | } |
| 73 | } |