Skip to content

Commit 81342da

Browse files
committed
move test file and add benchmark tests
1 parent e85e9a6 commit 81342da

2 files changed

Lines changed: 43 additions & 2 deletions

File tree

‎Makefile‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ test:
88

99
build:
1010
go build checkpoint.go
11+
12+
benchmark:
13+
go test -v -bench=. -benchmem
1114

1215
pre-commit:
1316
$(format)
Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,23 @@
11
package checkpoint_test
22

33
import (
4+
"fmt"
5+
"math/rand"
46
"testing"
57
"time"
68

7-
checkpoint "github.com/aidenfine/checkpoint"
9+
"github.com/aidenfine/checkpoint"
810
)
911

12+
func generateRandomIPv4() string {
13+
o1 := rand.Intn(256)
14+
o2 := rand.Intn(256)
15+
o3 := rand.Intn(256)
16+
o4 := rand.Intn(256)
17+
18+
return fmt.Sprintf("%d.%d.%d.%d", o1, o2, o3, o4)
19+
}
20+
1021
func TestTokenBucketLimiter_HasEnoughTokens(t *testing.T) {
1122

1223
limiter := checkpoint.NewTokenBucket(100, 1, 5)
@@ -22,7 +33,6 @@ func TestTokenBucketLimiter_HasEnoughTokens(t *testing.T) {
2233
t.Errorf("expected remaining to be 99 but got %d", remaining)
2334
}
2435
}
25-
2636
func TestTokenBucketLimiter_DoesNotHaveEnoughTokens(t *testing.T) {
2737

2838
limiter := checkpoint.NewTokenBucket(100, 1, 5)
@@ -54,3 +64,31 @@ func TestTokenBucketLimiter_HasZeroTokensButCanBeRefilled(t *testing.T) {
5464
t.Errorf("expected request to be allowed but has failed")
5565
}
5666
}
67+
68+
// ---------------- BENCHMARKS ----------------//
69+
func BenchmarkAllowUniqueIps(b *testing.B) {
70+
tb := checkpoint.NewTokenBucket(100, 1, 1)
71+
72+
ips := make([]string, 1000)
73+
for i := range ips {
74+
ips[i] = generateRandomIPv4()
75+
}
76+
77+
b.ResetTimer()
78+
for i := 0; i < b.N; i++ {
79+
tb.Allow(ips[i%len(ips)])
80+
}
81+
}
82+
func BenchmarkAllowNonUniqueIps(b *testing.B) {
83+
tb := checkpoint.NewTokenBucket(100, 1, 1)
84+
85+
ips := make([]string, 5)
86+
for i := range ips {
87+
ips[i] = generateRandomIPv4()
88+
}
89+
90+
b.ResetTimer()
91+
for i := 0; i < b.N; i++ {
92+
tb.Allow(ips[i%len(ips)])
93+
}
94+
}

0 commit comments

Comments
 (0)