github.com/XiaoMi/Gaea@v1.2.5/util/timer/randticker_flaky_test.go (about) 1 /* 2 Copyright 2017 Google Inc. 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 24 const ( 25 testDuration = 100 * time.Millisecond 26 testVariance = 20 * time.Millisecond 27 ) 28 29 func TestTick(t *testing.T) { 30 tkr := NewRandTicker(testDuration, testVariance) 31 for i := 0; i < 5; i++ { 32 start := time.Now() 33 end := <-tkr.C 34 diff := start.Add(testDuration).Sub(end) 35 tolerance := testVariance + 20*time.Millisecond 36 if diff < -tolerance || diff > tolerance { 37 t.Errorf("start: %v, end: %v, diff %v. Want <%v tolerenace", start, end, diff, tolerance) 38 } 39 } 40 tkr.Stop() 41 _, ok := <-tkr.C 42 if ok { 43 t.Error("Channel was not closed") 44 } 45 } 46 47 func TestTickSkip(t *testing.T) { 48 tkr := NewRandTicker(10*time.Millisecond, 1*time.Millisecond) 49 time.Sleep(35 * time.Millisecond) 50 end := <-tkr.C 51 diff := time.Now().Sub(end) 52 if diff < 20*time.Millisecond { 53 t.Errorf("diff: %v, want >20ms", diff) 54 } 55 56 // This tick should be up-to-date 57 end = <-tkr.C 58 diff = time.Now().Sub(end) 59 if diff > 1*time.Millisecond { 60 t.Errorf("diff: %v, want <1ms", diff) 61 } 62 tkr.Stop() 63 }