github.com/turingchain2020/turingchain@v1.1.21/system/mempool/pipeline_test.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package mempool 6 7 import ( 8 "runtime" 9 "testing" 10 "time" 11 12 "github.com/turingchain2020/turingchain/queue" 13 "github.com/stretchr/testify/assert" 14 ) 15 16 func TestStep(t *testing.T) { 17 done := make(chan struct{}) 18 in := make(chan *queue.Message) 19 msg := &queue.Message{ID: 0} 20 cb := func(in *queue.Message) *queue.Message { 21 in.ID++ 22 time.Sleep(time.Microsecond) 23 return in 24 } 25 out := step(done, in, cb) 26 in <- msg 27 msg2 := <-out 28 assert.Equal(t, msg2.ID, int64(1)) 29 close(done) 30 } 31 32 func TestMutiStep(t *testing.T) { 33 done := make(chan struct{}) 34 in := make(chan *queue.Message) 35 msg := &queue.Message{ID: 0} 36 step1 := func(in *queue.Message) *queue.Message { 37 in.ID++ 38 time.Sleep(time.Microsecond) 39 return in 40 } 41 out1 := step(done, in, step1) 42 step2 := func(in *queue.Message) *queue.Message { 43 in.ID++ 44 time.Sleep(time.Microsecond) 45 return in 46 } 47 out21 := step(done, out1, step2) 48 out22 := step(done, out1, step2) 49 50 out3 := mergeList(done, out21, out22) 51 in <- msg 52 msg2 := <-out3 53 assert.Equal(t, msg2.ID, int64(2)) 54 close(done) 55 } 56 57 func BenchmarkStep(b *testing.B) { 58 done := make(chan struct{}) 59 in := make(chan *queue.Message) 60 msg := &queue.Message{ID: 0} 61 cb := func(in *queue.Message) *queue.Message { 62 in.ID++ 63 time.Sleep(100 * time.Microsecond) 64 return in 65 } 66 out := step(done, in, cb) 67 go func() { 68 for i := 0; i < b.N; i++ { 69 in <- msg 70 } 71 }() 72 for i := 0; i < b.N; i++ { 73 msg2 := <-out 74 assert.Equal(b, msg2.ID, int64(1)) 75 } 76 close(done) 77 } 78 79 func BenchmarkStepMerge(b *testing.B) { 80 done := make(chan struct{}) 81 in := make(chan *queue.Message) 82 msg := &queue.Message{ID: 0} 83 cb := func(in *queue.Message) *queue.Message { 84 in.ID++ 85 time.Sleep(100 * time.Microsecond) 86 return in 87 } 88 chs := make([]<-chan *queue.Message, runtime.NumCPU()) 89 for i := 0; i < runtime.NumCPU(); i++ { 90 chs[i] = step(done, in, cb) 91 } 92 out := merge(done, chs) 93 go func() { 94 for i := 0; i < b.N; i++ { 95 in <- msg 96 } 97 }() 98 for i := 0; i < b.N; i++ { 99 msg2 := <-out 100 assert.Equal(b, msg2.ID, int64(1)) 101 } 102 close(done) 103 } 104 105 func mergeList(done <-chan struct{}, cs ...<-chan *queue.Message) <-chan *queue.Message { 106 return merge(done, cs) 107 }