Skip to content

Commit f02fa1e

Browse files
committed
Add limiter tests and fix bugs
1 parent 3df62ee commit f02fa1e

File tree

3 files changed

+55
-4
lines changed

3 files changed

+55
-4
lines changed

internal/limiter/limiter.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ type Store interface {
1414
}
1515

1616
type Config interface {
17-
PolicyFor(apiKey string) (Policy, error)
17+
PolicyFor(apiKey string) (Policy, bool)
1818
GetDefault() Policy
1919
}
2020

internal/limiter/limiter_test.go

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,52 @@
1-
// internal/limiter/limiter_test.go
1+
package limiter_test
2+
3+
import (
4+
"context"
5+
"testing"
6+
"time"
7+
8+
"github.com/Pavan-Rana/rate-limiter/internal/limiter"
9+
)
10+
11+
type fakeStore struct {
12+
allowResult bool
13+
callCount int
14+
}
15+
16+
func (f *fakeStore) AllowRequest(_ context.Context, _ string, _ limiter.Policy) (bool, error) {
17+
f.callCount++
18+
return f.allowResult, nil
19+
}
20+
21+
func (f *fakeStore) Ping(_ context.Context) error { return nil }
22+
23+
type fakeConfig struct {}
24+
25+
func(f *fakeConfig) PolicyFor(_ string) (limiter.Policy, bool) { return limiter.Policy{}, false }
26+
func(f *fakeConfig) GetDefault() limiter.Policy { return limiter.Policy{Limit: 10, Window: time.Minute} }
27+
28+
func TestAllowRequest_Allowed(t *testing.T) {
29+
store := &fakeStore{allowResult: true}
30+
lim := limiter.New(store, &fakeConfig{})
31+
32+
allowed, err := lim.AllowRequest(context.Background(), "test-key")
33+
if err != nil {
34+
t.Fatalf("Unexpected error: %v", err)
35+
}
36+
if !allowed {
37+
t.Fatalf("Expected request to be allowed")
38+
}
39+
}
40+
41+
func TestAllowRequest_Rejected(t *testing.T) {
42+
store := &fakeStore{allowResult: false}
43+
lim := limiter.New(store, &fakeConfig{})
44+
45+
allowed, err := lim.AllowRequest(context.Background(), "test-key")
46+
if err != nil {
47+
t.Fatalf("Unexpected error: %v", err)
48+
}
49+
if allowed {
50+
t.Fatalf("Expected request to be rejected")
51+
}
52+
}

internal/limiter/policy.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@ type Policy struct {
99
}
1010

1111
var DefaultPolicy = Policy{
12-
Limit: 100,
13-
Window: time.Minute
12+
Limit: 100,
13+
Window: time.Minute,
1414
}

0 commit comments

Comments
 (0)