github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/grpc/internal/buffer/unbounded_test.go (about) 1 /* 2 * Copyright 2019 gRPC 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 18 package buffer 19 20 import ( 21 "reflect" 22 "sort" 23 "sync" 24 "testing" 25 26 "github.com/hxx258456/ccgo/grpc/internal/grpctest" 27 ) 28 29 const ( 30 numWriters = 10 31 numWrites = 10 32 ) 33 34 type s struct { 35 grpctest.Tester 36 } 37 38 func Test(t *testing.T) { 39 grpctest.RunSubTests(t, s{}) 40 } 41 42 // wantReads contains the set of values expected to be read by the reader 43 // goroutine in the tests. 44 var wantReads []int 45 46 func init() { 47 for i := 0; i < numWriters; i++ { 48 for j := 0; j < numWrites; j++ { 49 wantReads = append(wantReads, i) 50 } 51 } 52 } 53 54 // TestSingleWriter starts one reader and one writer goroutine and makes sure 55 // that the reader gets all the value added to the buffer by the writer. 56 func (s) TestSingleWriter(t *testing.T) { 57 ub := NewUnbounded() 58 reads := []int{} 59 60 var wg sync.WaitGroup 61 wg.Add(1) 62 go func() { 63 defer wg.Done() 64 ch := ub.Get() 65 for i := 0; i < numWriters*numWrites; i++ { 66 r := <-ch 67 reads = append(reads, r.(int)) 68 ub.Load() 69 } 70 }() 71 72 wg.Add(1) 73 go func() { 74 defer wg.Done() 75 for i := 0; i < numWriters; i++ { 76 for j := 0; j < numWrites; j++ { 77 ub.Put(i) 78 } 79 } 80 }() 81 82 wg.Wait() 83 if !reflect.DeepEqual(reads, wantReads) { 84 t.Errorf("reads: %#v, wantReads: %#v", reads, wantReads) 85 } 86 } 87 88 // TestMultipleWriters starts multiple writers and one reader goroutine and 89 // makes sure that the reader gets all the data written by all writers. 90 func (s) TestMultipleWriters(t *testing.T) { 91 ub := NewUnbounded() 92 reads := []int{} 93 94 var wg sync.WaitGroup 95 wg.Add(1) 96 go func() { 97 defer wg.Done() 98 ch := ub.Get() 99 for i := 0; i < numWriters*numWrites; i++ { 100 r := <-ch 101 reads = append(reads, r.(int)) 102 ub.Load() 103 } 104 }() 105 106 wg.Add(numWriters) 107 for i := 0; i < numWriters; i++ { 108 go func(index int) { 109 defer wg.Done() 110 for j := 0; j < numWrites; j++ { 111 ub.Put(index) 112 } 113 }(i) 114 } 115 116 wg.Wait() 117 sort.Ints(reads) 118 if !reflect.DeepEqual(reads, wantReads) { 119 t.Errorf("reads: %#v, wantReads: %#v", reads, wantReads) 120 } 121 }