File: ratelimiter_test.go

package info (click to toggle)
golang-github-twin-g8 3.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 192 kB
  • sloc: makefile: 2
file content (73 lines) | stat: -rw-r--r-- 2,206 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package g8

import (
	"testing"
	"time"
)

func TestNewRateLimiter(t *testing.T) {
	rl := NewRateLimiter(2)
	if rl.maximumExecutionsPerSecond != 2 {
		t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond)
	}
	if rl.executionsLeftInWindow != 2 {
		t.Errorf("expected executionsLeftInWindow to be %d, got %d", 2, rl.executionsLeftInWindow)
	}
	// First execution: should not be rate limited
	if notRateLimited := rl.Try(); !notRateLimited {
		t.Error("expected Try to return true")
	}
	if rl.maximumExecutionsPerSecond != 2 {
		t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond)
	}
	if rl.executionsLeftInWindow != 1 {
		t.Errorf("expected executionsLeftInWindow to be %d, got %d", 1, rl.executionsLeftInWindow)
	}
	// Second execution: should not be rate limited
	if notRateLimited := rl.Try(); !notRateLimited {
		t.Error("expected Try to return true")
	}
	if rl.maximumExecutionsPerSecond != 2 {
		t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond)
	}
	if rl.executionsLeftInWindow != 0 {
		t.Errorf("expected executionsLeftInWindow to be %d, got %d", 0, rl.executionsLeftInWindow)
	}
	// Third execution: should be rate limited
	if notRateLimited := rl.Try(); notRateLimited {
		t.Error("expected Try to return false")
	}
	if rl.maximumExecutionsPerSecond != 2 {
		t.Errorf("expected maximumExecutionsPerSecond to be %d, got %d", 2, rl.maximumExecutionsPerSecond)
	}
	if rl.executionsLeftInWindow != 0 {
		t.Errorf("expected executionsLeftInWindow to be %d, got %d", 0, rl.executionsLeftInWindow)
	}
}

func TestRateLimiter_Try(t *testing.T) {
	rl := NewRateLimiter(5)
	for i := 0; i < 20; i++ {
		notRateLimited := rl.Try()
		if i < 5 {
			if !notRateLimited {
				t.Fatal("expected to not be rate limited")
			}
		} else {
			if notRateLimited {
				t.Fatal("expected to be rate limited")
			}
		}
	}
}

func TestRateLimiter_TryAlwaysUnderRateLimit(t *testing.T) {
	rl := NewRateLimiter(20)
	for i := 0; i < 45; i++ {
		notRateLimited := rl.Try()
		if !notRateLimited {
			t.Fatal("expected to not be rate limited")
		}
		time.Sleep(51 * time.Millisecond)
	}
}