github.com/iotexproject/iotex-core@v1.14.1-rc1/pkg/routine/recurringtask_test.go (about) 1 // Copyright (c) 2019 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package routine_test 7 8 import ( 9 "context" 10 "sync" 11 "testing" 12 "time" 13 14 "github.com/facebookgo/clock" 15 "github.com/stretchr/testify/require" 16 17 "github.com/iotexproject/iotex-core/pkg/routine" 18 ) 19 20 type MockHandler struct { 21 Count uint 22 mu sync.RWMutex 23 } 24 25 func (h *MockHandler) Do() { 26 h.mu.Lock() 27 h.Count++ 28 h.mu.Unlock() 29 } 30 31 func TestRecurringTask(t *testing.T) { 32 require := require.New(t) 33 h := &MockHandler{Count: 0} 34 ctx := context.Background() 35 ck := clock.NewMock() 36 task := routine.NewRecurringTask(h.Do, 100*time.Millisecond, routine.WithClock(ck)) 37 require.Error(task.Stop(ctx)) 38 task.Start(ctx) 39 ck.Add(600 * time.Millisecond) 40 task.Stop(ctx) 41 h.mu.RLock() 42 require.True(h.Count >= 5) 43 h.mu.RUnlock() 44 }