github.com/searKing/golang/go@v1.2.117/sync/lru_pool_test.go (about) 1 // Copyright 2021 The searKing Author. 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 sync 6 7 import ( 8 "context" 9 "runtime" 10 "runtime/debug" 11 "testing" 12 ) 13 14 func TestLruPool(t *testing.T) { 15 // disable GC so we can control when it happens. 16 defer debug.SetGCPercent(debug.SetGCPercent(-1)) 17 var p LruPool 18 g, put := p.Get(context.Background(), "") 19 defer put() 20 if g != nil { 21 t.Fatal("expected empty") 22 } 23 24 // Make sure that the goroutine doesn't migrate to another P 25 // between Put and Get calls. 26 runtime.LockOSThread() 27 defer runtime.UnlockOSThread() 28 g, put = p.Get(context.Background(), "") 29 defer put() 30 if g != nil { 31 t.Fatal("expected empty") 32 } 33 } 34 35 func TestLruPool_New(t *testing.T) { 36 // disable GC so we can control when it happens. 37 defer debug.SetGCPercent(debug.SetGCPercent(-1)) 38 39 i := 0 40 p := LruPool{ 41 New: func(ctx context.Context, req any) (resp any, err error) { 42 i++ 43 return i, nil 44 }, 45 } 46 a, puta := p.Get(context.Background(), "") 47 if a != 1 { 48 t.Fatalf("got %v; want 1", a) 49 } 50 b, putb := p.Get(context.Background(), "") 51 if b != 2 { 52 t.Fatalf("got %v; want 2", b) 53 } 54 55 // Make sure that the goroutine doesn't migrate to another P 56 // between Put and Get calls. 57 runtime.LockOSThread() 58 defer runtime.UnlockOSThread() 59 puta() 60 a, puta = p.Get(context.Background(), "") 61 defer puta() 62 if a != 1 { 63 t.Fatalf("got %v; want 1", a) 64 } 65 c, putc := p.Get(context.Background(), "") 66 defer putc() 67 if c != 3 { 68 t.Fatalf("got %v; want 3", a) 69 } 70 putb() 71 b, putb = p.Get(context.Background(), "") 72 defer putb() 73 74 }