github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zpool/inject_test.go (about) 1 package zpool 2 3 import ( 4 "errors" 5 "reflect" 6 "sync" 7 "testing" 8 "time" 9 10 "github.com/sohaha/zlsgo" 11 "github.com/sohaha/zlsgo/zdi" 12 "github.com/sohaha/zlsgo/zerror" 13 ) 14 15 type preTest func(i int) 16 17 func (p preTest) Invoke(i []interface{}) ([]reflect.Value, error) { 18 p(i[0].(int)) 19 return nil, nil 20 } 21 22 var _ zdi.PreInvoker = (*preTest)(nil) 23 24 func TestPoolInvoke(t *testing.T) { 25 tt := zlsgo.NewTest(t) 26 27 var wg sync.WaitGroup 28 testErr := errors.New("test") 29 count := 10 30 p := New(count) 31 32 p.Injector().Map(1) 33 p.Injector().Map(time.Now()) 34 35 p.PanicFunc(func(err error) { 36 code, b := zerror.UnwrapCode(err) 37 if b { 38 t.Log("is zerror", code, err) 39 wg.Done() 40 } else { 41 t.Log("is not zerror", err) 42 } 43 }) 44 45 wg.Add(1) 46 err := p.Do(func() error { 47 defer wg.Done() 48 return testErr 49 }) 50 tt.NoError(err) 51 52 wg.Add(1) 53 err = p.Do(preTest(func(i int) { 54 defer wg.Done() 55 })) 56 tt.NoError(err) 57 58 for i := 0; i <= 100; i++ { 59 wg.Add(1) 60 index := i 61 err = p.Do(func(now time.Time) error { 62 if index > 0 && index%20 == 0 { 63 return zerror.New(zerror.ErrCode(index), now.String()) 64 } 65 defer wg.Done() 66 return nil 67 }) 68 tt.NoError(err) 69 } 70 71 wg.Wait() 72 time.Sleep(time.Second / 2) 73 } 74 75 func BenchmarkInjectorNo(b *testing.B) { 76 var wg sync.WaitGroup 77 count := 10000 78 p := New(count) 79 _ = p.PreInit() 80 ii := 1 81 wg.Add(b.N) 82 b.ResetTimer() 83 b.ReportAllocs() 84 for i := 0; i < b.N; i++ { 85 err := p.Do(func() { 86 _ = ii 87 wg.Done() 88 }) 89 if err != nil { 90 b.Error(err) 91 } 92 } 93 wg.Wait() 94 } 95 96 func BenchmarkInjectorPre(b *testing.B) { 97 var wg sync.WaitGroup 98 count := 10000 99 p := New(count) 100 p.Injector().Map(1) 101 _ = p.PreInit() 102 wg.Add(b.N) 103 b.ResetTimer() 104 b.ReportAllocs() 105 for i := 0; i < b.N; i++ { 106 err := p.Do(preTest(func(ii int) { 107 _ = ii 108 wg.Done() 109 })) 110 if err != nil { 111 b.Error(err) 112 } 113 } 114 wg.Wait() 115 } 116 117 func BenchmarkInjector(b *testing.B) { 118 var wg sync.WaitGroup 119 count := 10000 120 p := New(count) 121 _ = p.PreInit() 122 p.Injector().Map(1) 123 wg.Add(b.N) 124 b.ResetTimer() 125 b.ReportAllocs() 126 for i := 0; i < b.N; i++ { 127 err := p.Do(func(ii int) { 128 _ = ii 129 wg.Done() 130 }) 131 if err != nil { 132 b.Error(err) 133 } 134 } 135 wg.Wait() 136 }