github.com/lingyao2333/mo-zero@v1.4.1/core/executors/chunkexecutor_test.go (about) 1 package executors 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func TestChunkExecutor(t *testing.T) { 12 var values []int 13 var lock sync.Mutex 14 15 executor := NewChunkExecutor(func(items []interface{}) { 16 lock.Lock() 17 values = append(values, len(items)) 18 lock.Unlock() 19 }, WithChunkBytes(10), WithFlushInterval(time.Minute)) 20 21 for i := 0; i < 50; i++ { 22 executor.Add(1, 1) 23 time.Sleep(time.Millisecond) 24 } 25 26 lock.Lock() 27 assert.True(t, len(values) > 0) 28 // ignore last value 29 for i := 0; i < len(values); i++ { 30 assert.Equal(t, 10, values[i]) 31 } 32 lock.Unlock() 33 } 34 35 func TestChunkExecutorFlushInterval(t *testing.T) { 36 const ( 37 caches = 10 38 size = 5 39 ) 40 var wait sync.WaitGroup 41 42 wait.Add(1) 43 executor := NewChunkExecutor(func(items []interface{}) { 44 assert.Equal(t, size, len(items)) 45 wait.Done() 46 }, WithChunkBytes(caches), WithFlushInterval(time.Millisecond*100)) 47 48 for i := 0; i < size; i++ { 49 executor.Add(1, 1) 50 } 51 52 wait.Wait() 53 } 54 55 func TestChunkExecutorEmpty(t *testing.T) { 56 NewChunkExecutor(func(items []interface{}) { 57 assert.Fail(t, "should not called") 58 }, WithChunkBytes(10), WithFlushInterval(time.Millisecond)) 59 time.Sleep(time.Millisecond * 100) 60 } 61 62 func TestChunkExecutorFlush(t *testing.T) { 63 const ( 64 caches = 10 65 tasks = 5 66 ) 67 68 var wait sync.WaitGroup 69 wait.Add(1) 70 be := NewChunkExecutor(func(items []interface{}) { 71 assert.Equal(t, tasks, len(items)) 72 wait.Done() 73 }, WithChunkBytes(caches), WithFlushInterval(time.Minute)) 74 for i := 0; i < tasks; i++ { 75 be.Add(1, 1) 76 } 77 be.Flush() 78 wait.Wait() 79 } 80 81 func BenchmarkChunkExecutor(b *testing.B) { 82 b.ReportAllocs() 83 84 be := NewChunkExecutor(func(tasks []interface{}) { 85 time.Sleep(time.Millisecond * time.Duration(len(tasks))) 86 }) 87 for i := 0; i < b.N; i++ { 88 time.Sleep(time.Microsecond * 200) 89 be.Add(1, 1) 90 } 91 be.Flush() 92 }