vitess.io/vitess@v0.16.2/go/timer/timer_flaky_test.go (about) 1 /* 2 Copyright 2019 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 25 "vitess.io/vitess/go/sync2" 26 ) 27 28 const ( 29 half = 50 * time.Millisecond 30 quarter = 25 * time.Millisecond 31 tenth = 10 * time.Millisecond 32 ) 33 34 var numcalls sync2.AtomicInt64 35 36 func f() { 37 numcalls.Add(1) 38 } 39 40 func TestWait(t *testing.T) { 41 numcalls.Set(0) 42 timer := NewTimer(quarter) 43 assert.False(t, timer.Running()) 44 timer.Start(f) 45 defer timer.Stop() 46 assert.True(t, timer.Running()) 47 time.Sleep(tenth) 48 assert.Equal(t, int64(0), numcalls.Get()) 49 time.Sleep(quarter) 50 assert.Equal(t, int64(1), numcalls.Get()) 51 time.Sleep(quarter) 52 assert.Equal(t, int64(2), numcalls.Get()) 53 } 54 55 func TestReset(t *testing.T) { 56 numcalls.Set(0) 57 timer := NewTimer(half) 58 timer.Start(f) 59 defer timer.Stop() 60 timer.SetInterval(quarter) 61 time.Sleep(tenth) 62 assert.Equal(t, int64(0), numcalls.Get()) 63 time.Sleep(quarter) 64 assert.Equal(t, int64(1), numcalls.Get()) 65 } 66 67 func TestIndefinite(t *testing.T) { 68 numcalls.Set(0) 69 timer := NewTimer(0) 70 timer.Start(f) 71 defer timer.Stop() 72 timer.TriggerAfter(quarter) 73 time.Sleep(tenth) 74 assert.Equal(t, int64(0), numcalls.Get()) 75 time.Sleep(quarter) 76 assert.Equal(t, int64(1), numcalls.Get()) 77 }