github.com/andy2046/gopie@v0.7.0/pkg/ratelimit/sliding_window_test.go (about) 1 package ratelimit 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 8 "github.com/go-redis/redis" 9 ) 10 11 func TestSlidingWindowLimiter(t *testing.T) { 12 t.Skip("only works with a local running Redis server") 13 opts := &redis.Options{ 14 Addr: "localhost:6379", 15 Password: "", // no password set 16 DB: 0, // use default DB 17 } 18 key := "user_1" 19 expire := 10 20 var once sync.Once 21 redStore, _ := NewRedisStore(opts) 22 sLimiter := NewSlidingWindowLimiter(1, expire, redStore) 23 24 t1 := t0.Add(200 * time.Millisecond) 25 t2 := t0.Add(time.Duration(expire) * time.Second) 26 cases := []struct { 27 t time.Time 28 n int 29 ok bool 30 }{ 31 {t0, 1, true}, 32 {t0, 1, false}, 33 {t0, 1, false}, 34 {t1, 1, false}, 35 {t1, 1, false}, 36 {t2, 1, true}, 37 {t2, 1, false}, 38 } 39 40 for _, c := range cases { 41 if c.t == t2 { 42 once.Do(func() { 43 time.Sleep(time.Duration(expire) * time.Second) 44 }) 45 } 46 ok := sLimiter.AllowN(c.t, key, c.n) 47 if ok != c.ok { 48 t.Errorf("AllowN(%v, %v, %v) = %v want %v", 49 c.t, key, c.n, ok, c.ok) 50 } 51 } 52 }