github.com/tamaxcode/worker@v1.0.0/worker_test.go (about) 1 package worker 2 3 import ( 4 "sync" 5 "testing" 6 ) 7 8 func Test_Run(t *testing.T) { 9 c := 0 10 mtx := sync.Mutex{} 11 fn := func(_ interface{}) bool { 12 mtx.Lock() 13 c++ 14 mtx.Unlock() 15 16 return true 17 } 18 19 collector := NewCollector(Config{ 20 Handler: fn, 21 }) 22 23 for i := 0; i < 1000; i++ { 24 collector.Add(nil) 25 } 26 27 collector.Wait() 28 29 if c != 1000 { 30 t.Errorf("Count Want: 1000, Got: %d\n", c) 31 } 32 } 33 34 func Test_Concurrent(t *testing.T) { 35 want := make([]int, 1000) 36 got := make([]int, 1000) 37 38 type payload struct { 39 n int 40 i int 41 } 42 43 collector := NewCollector(Config{ 44 Handler: func(data interface{}) bool { 45 p, _ := data.(payload) 46 47 got[p.i] = p.n 48 49 return true 50 }, 51 }) 52 53 for i := 0; i < 1000; i++ { 54 want[i] = i 55 56 collector.Add(payload{ 57 n: i, 58 i: i, 59 }) 60 } 61 62 collector.Wait() 63 64 for i, n := range want { 65 if got[i] != n { 66 t.Errorf("At index %d, WANT: %d, GOT: %d", i, n, got[i]) 67 } 68 } 69 } 70 71 func Test_Worker_Stop(t *testing.T) { 72 73 c := 0 74 mtx := sync.Mutex{} 75 fn := func(data interface{}) bool { 76 mtx.Lock() 77 defer mtx.Unlock() 78 79 if c == 2 { 80 return false 81 } 82 83 c++ 84 85 return true 86 } 87 88 collector := NewCollector(Config{ 89 NoOfWorkers: 2, 90 Handler: fn, 91 }) 92 93 for i := 0; i < 100; i++ { 94 collector.Add(nil) 95 } 96 97 collector.Wait() 98 99 if c != 2 { 100 t.Errorf("Count Want: 2, Got: %d\n", c) 101 } 102 } 103 104 func Benchmark_Run1000(b *testing.B) { 105 c := 0 106 mtx := sync.Mutex{} 107 108 collector := NewCollector(Config{ 109 Handler: func(data interface{}) bool { 110 mtx.Lock() 111 c++ 112 mtx.Unlock() 113 114 return true 115 }, 116 }) 117 118 for i := 0; i < 1000; i++ { 119 collector.Add(nil) 120 } 121 122 collector.Wait() 123 }