github.com/dtroyer-salad/og2/v2@v2.0.0-20240412154159-c47231610877/internal/syncutil/pool_test.go (about) 1 /* 2 Copyright The ORAS Authors. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 */ 15 16 package syncutil 17 18 import ( 19 "sync" 20 "sync/atomic" 21 "testing" 22 ) 23 24 func TestPool(t *testing.T) { 25 var pool Pool[int64] 26 numbers := [][]int{ 27 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 28 {-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}, 29 } 30 31 // generate expected result 32 expected := make([]int, len(numbers)) 33 for i, nums := range numbers { 34 for _, num := range nums { 35 expected[i] += num 36 } 37 } 38 39 // test pool 40 for i, nums := range numbers { 41 val, done := pool.Get(i) 42 *val = 0 43 var wg sync.WaitGroup 44 for _, num := range nums { 45 wg.Add(1) 46 go func(n int) { 47 defer wg.Done() 48 val, done := pool.Get(i) 49 defer done() 50 atomic.AddInt64(val, int64(n)) 51 }(num) 52 } 53 wg.Wait() 54 item := pool.items[i] 55 if got := item.value; got != int64(expected[i]) { 56 t.Errorf("Pool.Get(%v).value = %v, want %v", i, got, expected[i]) 57 } 58 if got := item.refCount; got != 1 { 59 t.Errorf("Pool.Get(%v).refCount = %v, want %v", i, got, 1) 60 } 61 62 // item should be cleaned up after done 63 done() 64 got := pool.items[i] 65 if got != nil { 66 t.Errorf("Pool.Get(%v) = %v, want %v", i, got, nil) 67 } 68 } 69 }