vitess.io/vitess@v0.16.2/go/timer/rate_limiter_test.go (about) 1 /* 2 Copyright 2020 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package timer 18 19 import ( 20 "testing" 21 "time" 22 23 "github.com/stretchr/testify/assert" 24 "github.com/stretchr/testify/require" 25 ) 26 27 func TestRateLimiterLong(t *testing.T) { 28 r := NewRateLimiter(time.Hour) 29 require.NotNil(t, r) 30 val := 0 31 incr := func() error { val++; return nil } 32 for i := 0; i < 10; i++ { 33 err := r.Do(incr) 34 assert.NoError(t, err) 35 } 36 assert.Equal(t, 1, val) 37 } 38 39 func TestRateLimiterShort(t *testing.T) { 40 r := NewRateLimiter(time.Millisecond * 250) 41 require.NotNil(t, r) 42 val := 0 43 incr := func() error { val++; return nil } 44 for i := 0; i < 10; i++ { 45 time.Sleep(time.Millisecond * 100) 46 err := r.Do(incr) 47 assert.NoError(t, err) 48 } 49 // we expect some 3-5 entries; this depends on the CI server performance. 50 assert.Greater(t, val, 2) 51 assert.Less(t, val, 10) 52 } 53 54 func TestRateLimiterStop(t *testing.T) { 55 r := NewRateLimiter(time.Millisecond * 10) 56 require.NotNil(t, r) 57 val := 0 58 incr := func() error { val++; return nil } 59 for i := 0; i < 5; i++ { 60 time.Sleep(time.Millisecond * 10) 61 err := r.Do(incr) 62 assert.NoError(t, err) 63 } 64 // we expect some 3-5 entries; this depends on the CI server performance. 65 assert.Greater(t, val, 2) 66 valSnapshot := val 67 r.Stop() 68 for i := 0; i < 5; i++ { 69 time.Sleep(time.Millisecond * 10) 70 err := r.Do(incr) 71 assert.NoError(t, err) 72 } 73 assert.Equal(t, valSnapshot, val) 74 }