github.com/metacubex/mihomo@v1.18.5/common/singledo/singledo_test.go (about) 1 package singledo 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 8 "github.com/metacubex/mihomo/common/atomic" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func TestBasic(t *testing.T) { 14 single := NewSingle[int](time.Millisecond * 30) 15 foo := 0 16 shardCount := atomic.NewInt32(0) 17 call := func() (int, error) { 18 foo++ 19 time.Sleep(time.Millisecond * 5) 20 return 0, nil 21 } 22 23 var wg sync.WaitGroup 24 const n = 5 25 wg.Add(n) 26 for i := 0; i < n; i++ { 27 go func() { 28 _, _, shard := single.Do(call) 29 if shard { 30 shardCount.Add(1) 31 } 32 wg.Done() 33 }() 34 } 35 36 wg.Wait() 37 assert.Equal(t, 1, foo) 38 assert.Equal(t, int32(4), shardCount.Load()) 39 } 40 41 func TestTimer(t *testing.T) { 42 single := NewSingle[int](time.Millisecond * 30) 43 foo := 0 44 callM := func() (int, error) { 45 foo++ 46 return 0, nil 47 } 48 49 _, _, _ = single.Do(callM) 50 time.Sleep(10 * time.Millisecond) 51 _, _, shard := single.Do(callM) 52 53 assert.Equal(t, 1, foo) 54 assert.True(t, shard) 55 } 56 57 func TestReset(t *testing.T) { 58 single := NewSingle[int](time.Millisecond * 30) 59 foo := 0 60 callM := func() (int, error) { 61 foo++ 62 return 0, nil 63 } 64 65 _, _, _ = single.Do(callM) 66 single.Reset() 67 _, _, _ = single.Do(callM) 68 69 assert.Equal(t, 2, foo) 70 }