github.com/mier85/go-sensor@v1.30.1-0.20220920111756-9bf41b3bc7e0/autoprofile/internal/timer_test.go (about) 1 // (c) Copyright IBM Corp. 2021 2 // (c) Copyright Instana Inc. 2020 3 4 package internal_test 5 6 import ( 7 "sync/atomic" 8 "testing" 9 "time" 10 11 "github.com/instana/testify/assert" 12 "github.com/mier85/go-sensor/autoprofile/internal" 13 ) 14 15 func TestTimer_Stop_Restart(t *testing.T) { 16 var fired int64 17 scheduleTime := 60 * time.Millisecond 18 19 start := time.Now() 20 timer := internal.NewTimer(0, scheduleTime, func() { 21 atomic.AddInt64(&fired, 1) 22 }) 23 24 time.Sleep(100 * time.Millisecond) 25 timer.Stop() 26 27 elapsed := time.Since(start) 28 expectation := elapsed / scheduleTime 29 30 assert.EqualValues(t, expectation, atomic.LoadInt64(&fired)) 31 32 time.Sleep(200 * time.Millisecond) 33 assert.EqualValues(t, expectation, atomic.LoadInt64(&fired), "a stopped timer should not be restarted") 34 } 35 36 func TestTimer_Sleep_Stopped(t *testing.T) { 37 timer := internal.NewTimer(20*time.Millisecond, 0, func() { 38 t.Error("stopped timer has fired") 39 }) 40 41 timer.Stop() 42 time.Sleep(30 * time.Millisecond) 43 }