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+ }
0 commit comments