github.com/cloudwego/kitex@v0.9.0/pkg/utils/sharedticker_test.go (about) 1 /* 2 * Copyright 2023 CloudWeGo 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 utils 18 19 import ( 20 "testing" 21 "time" 22 23 "github.com/golang/mock/gomock" 24 25 mockutils "github.com/cloudwego/kitex/internal/mocks/utils" 26 "github.com/cloudwego/kitex/internal/test" 27 ) 28 29 func TestSharedTickerAdd(t *testing.T) { 30 ctrl := gomock.NewController(t) 31 defer ctrl.Finish() 32 33 rt := mockutils.NewMockTickerTask(ctrl) 34 rt.EXPECT().Tick().AnyTimes() 35 st := NewSharedTicker(1) 36 st.Add(nil) 37 test.Assert(t, len(st.tasks) == 0) 38 st.Add(rt) 39 test.Assert(t, len(st.tasks) == 1) 40 test.Assert(t, !st.Closed()) 41 } 42 43 func TestSharedTickerDeleteAndClose(t *testing.T) { 44 ctrl := gomock.NewController(t) 45 defer ctrl.Finish() 46 47 st := NewSharedTicker(1) 48 var ( 49 num = 10 50 tasks = make([]TickerTask, num) 51 ) 52 for i := 0; i < num; i++ { 53 rt := mockutils.NewMockTickerTask(ctrl) 54 rt.EXPECT().Tick().AnyTimes() 55 tasks[i] = rt 56 st.Add(rt) 57 } 58 test.Assert(t, len(st.tasks) == num) 59 for i := 0; i < num; i++ { 60 st.Delete(tasks[i]) 61 } 62 test.Assert(t, len(st.tasks) == 0) 63 test.Assert(t, st.Closed()) 64 } 65 66 func TestSharedTickerTick(t *testing.T) { 67 ctrl := gomock.NewController(t) 68 defer ctrl.Finish() 69 70 duration := 100 * time.Millisecond 71 st := NewSharedTicker(duration) 72 var ( 73 num = 10 74 tasks = make([]TickerTask, num) 75 ) 76 for i := 0; i < num; i++ { 77 rt := mockutils.NewMockTickerTask(ctrl) 78 rt.EXPECT().Tick().MinTimes(1) // all tasks should be refreshed once during the test 79 tasks[i] = rt 80 st.Add(rt) 81 } 82 time.Sleep(150 * time.Millisecond) 83 }