-
Notifications
You must be signed in to change notification settings - Fork 150
/
pool_test.go
2140 lines (1855 loc) · 63.8 KB
/
pool_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pool
import (
"context"
"errors"
"flag"
"fmt"
"math"
"math/rand"
"os"
"reflect"
"sync"
"testing"
"time"
"github.com/fortytw2/leaktest"
"github.com/jolestar/go-commons-pool/v2/collections"
"github.com/jolestar/go-commons-pool/v2/concurrent"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
type TestObject struct {
Num int
}
var (
debugTest = false
)
func init() {
rand.Seed(time.Now().UnixNano())
}
type SimpleFactory struct {
makeCounter int
activationCounter int
validateCounter int
activeCount int
evenValid bool
oddValid bool
exceptionOnPassivate bool
exceptionOnActivate bool
exceptionOnDestroy bool
exceptionOnMake bool
enableValidation bool
destroyLatency time.Duration
makeLatency time.Duration
validateLatency time.Duration
maxTotal int
lock sync.Mutex
}
func NewSimpleFactory() *SimpleFactory {
return &SimpleFactory{maxTotal: math.MaxInt32, evenValid: true, oddValid: true, enableValidation: true}
}
func (f *SimpleFactory) setValid(valid bool) {
f.lock.Lock()
f.evenValid = valid
f.oddValid = valid
f.lock.Unlock()
}
func (f *SimpleFactory) setValidateLatency(validate time.Duration) {
f.lock.Lock()
f.validateLatency = validate
f.lock.Unlock()
}
func (f *SimpleFactory) MakeObject(context.Context) (*PooledObject, error) {
if debugTest {
fmt.Println("factory MakeObject")
}
if f.exceptionOnMake {
return nil, errors.New("make object error")
}
var waitLatency time.Duration
f.lock.Lock()
f.activeCount = f.activeCount + 1
if f.activeCount > f.maxTotal {
return nil, fmt.Errorf("Too many active instances: %v", f.activeCount)
}
waitLatency = f.makeLatency
f.lock.Unlock()
if waitLatency > 0 {
time.Sleep(waitLatency)
}
var counter int
f.lock.Lock()
counter = f.makeCounter
f.makeCounter = f.makeCounter + 1
f.lock.Unlock()
return NewPooledObject(&TestObject{Num: counter}), nil
}
func (f *SimpleFactory) DestroyObject(ctx context.Context, object *PooledObject) error {
if debugTest {
fmt.Println("factory DestroyObject")
}
var waitLatency time.Duration
var hurl bool
f.lock.Lock()
waitLatency = f.destroyLatency
hurl = f.exceptionOnDestroy
f.lock.Unlock()
if waitLatency > 0 {
time.Sleep(waitLatency)
}
f.lock.Lock()
f.activeCount = f.activeCount - 1
f.lock.Unlock()
if hurl {
return errors.New("destroy error")
}
return nil
}
func (f *SimpleFactory) ValidateObject(ctx context.Context, object *PooledObject) bool {
if debugTest {
fmt.Println("factory ValidateObject")
}
var validate bool
var evenTest bool
var oddTest bool
var waitLatency time.Duration
var counter int
f.lock.Lock()
validate = f.enableValidation
evenTest = f.evenValid
oddTest = f.oddValid
counter = f.validateCounter
f.validateCounter = f.validateCounter + 1
waitLatency = f.validateLatency
f.lock.Unlock()
if waitLatency > 0 {
time.Sleep(waitLatency)
}
if validate {
if counter%2 == 0 {
return evenTest
}
return oddTest
}
return true
}
func (f *SimpleFactory) ActivateObject(ctx context.Context, object *PooledObject) error {
if debugTest {
fmt.Println("factory ActivateObject")
defer fmt.Println("factory ActivateObject end")
}
var hurl bool
var evenTest bool
var oddTest bool
var counter int
f.lock.Lock()
hurl = f.exceptionOnActivate
evenTest = f.evenValid
oddTest = f.oddValid
counter = f.activationCounter
f.activationCounter = f.activationCounter + 1
f.lock.Unlock()
if hurl {
var test bool
if counter%2 == 0 {
test = evenTest
} else {
test = oddTest
}
if !test {
return errors.New("activate error")
}
}
return nil
}
func (f *SimpleFactory) PassivateObject(ctx context.Context, object *PooledObject) error {
if debugTest {
fmt.Println("factory PassivateObject")
}
var hurl bool
f.lock.Lock()
hurl = f.exceptionOnPassivate
f.lock.Unlock()
if hurl {
return errors.New("passivate error")
}
return nil
}
type PoolTestSuite struct {
suite.Suite
pool *ObjectPool
factory *SimpleFactory
}
func (suit *PoolTestSuite) assertEquals(expect interface{}, actual interface{}) {
suit.Equal(expect, actual)
}
func (suit *PoolTestSuite) assertNotNil(object interface{}) {
suit.NotNil(object)
}
func (suit *PoolTestSuite) assertNil(object interface{}) {
suit.Nil(object)
}
func (suit *PoolTestSuite) NoErrorWithResult(object interface{}, err error) interface{} {
suit.NotNil(object)
suit.Nil(err)
return object
}
func (suit *PoolTestSuite) ErrorWithResult(object interface{}, err error) error {
suit.Nil(object)
suit.NotNil(err)
return err
}
func TestPoolTestSuite(t *testing.T) {
t.Parallel()
suite.Run(t, new(PoolTestSuite))
}
func (suit *PoolTestSuite) SetupTest() {
suit.makeEmptyPool(context.Background(), DefaultMaxTotal)
}
func (suit *PoolTestSuite) TearDownTest() {
ctx := context.Background()
suit.pool.Clear(ctx)
suit.pool.Close(ctx)
suit.pool = nil
suit.factory = nil
}
func (suit *PoolTestSuite) makeEmptyPool(ctx context.Context, maxTotal int) {
suit.factory = NewSimpleFactory()
suit.pool = NewObjectPoolWithDefaultConfig(ctx, suit.factory)
suit.pool.Config.MaxTotal = maxTotal
}
func getNthObject(num int) *TestObject {
return &TestObject{Num: num}
}
func (suit *PoolTestSuite) TestBaseBorrow() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
o0, err := suit.pool.BorrowObject(ctx)
suit.Nil(err)
suit.NotNil(o0)
suit.Equal(getNthObject(0), o0)
o1, _ := suit.pool.BorrowObject(ctx)
suit.Equal(getNthObject(1), o1)
o2, _ := suit.pool.BorrowObject(ctx)
suit.Equal(getNthObject(2), o2)
}
func (suit *PoolTestSuite) TestBaseAddObject() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
suit.assertEquals(0, suit.pool.GetNumIdle())
suit.assertEquals(0, suit.pool.GetNumActive())
if debugTest {
fmt.Println("test AddObject")
}
suit.pool.AddObject(ctx)
suit.assertEquals(1, suit.pool.GetNumIdle())
suit.assertEquals(0, suit.pool.GetNumActive())
if debugTest {
fmt.Println("test BorrowObject")
}
obj, err := suit.pool.BorrowObject(ctx)
if err != nil {
suit.Fail(err.Error())
}
suit.assertEquals(getNthObject(0), obj)
suit.assertEquals(0, suit.pool.GetNumIdle())
suit.assertEquals(1, suit.pool.GetNumActive())
err = suit.pool.ReturnObject(ctx, obj)
if err != nil {
suit.Fail(err.Error())
}
suit.assertEquals(1, suit.pool.GetNumIdle())
suit.assertEquals(0, suit.pool.GetNumActive())
}
func (suit *PoolTestSuite) isLIFO() bool {
return true
}
func (suit *PoolTestSuite) isFIFO() bool {
return false
}
func (suit *PoolTestSuite) TestBaseBorrowReturn() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
obj0 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(getNthObject(0), obj0)
obj1 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(getNthObject(1), obj1)
obj2 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(getNthObject(2), obj2)
suit.NoError(suit.pool.ReturnObject(ctx, obj2))
obj2 = suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(getNthObject(2), obj2)
suit.pool.ReturnObject(ctx, obj1)
obj1 = suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(getNthObject(1), obj1)
suit.pool.ReturnObject(ctx, obj0)
suit.pool.ReturnObject(ctx, obj2)
obj2 = suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
if suit.isLIFO() {
suit.assertEquals(getNthObject(2), obj2)
}
if suit.isFIFO() {
suit.assertEquals(getNthObject(0), obj2)
}
obj0 = suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
if suit.isLIFO() {
suit.assertEquals(getNthObject(0), obj0)
}
if suit.isFIFO() {
suit.assertEquals(getNthObject(2), obj0)
}
}
func (suit *PoolTestSuite) TestBorrowReturnAsync() {
suit.pool.Config.MaxTotal = 1
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
obj0 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(getNthObject(0), obj0)
//start new goroutine to borrow will block
ch := make(chan interface{}, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
obj, _ := suit.pool.BorrowObject(ctx)
ch <- obj
}()
time.Sleep(100 * time.Millisecond)
//return obj0
go func() {
suit.pool.ReturnObject(context.Background(), obj0)
}()
time.Sleep(100 * time.Millisecond)
obj1 := <-ch
suit.NotNil(obj1)
suit.Equal(obj0, obj1)
}
func (suit *PoolTestSuite) TestBaseNumActiveNumIdle() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
obj0 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(1, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
obj1 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(2, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
suit.pool.ReturnObject(ctx, obj1)
suit.assertEquals(1, suit.pool.GetNumActive())
suit.assertEquals(1, suit.pool.GetNumIdle())
suit.NoError(suit.pool.ReturnObject(ctx, obj0))
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(2, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestBaseClear() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
obj0 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
obj1 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(2, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
suit.pool.ReturnObject(ctx, obj1)
suit.pool.ReturnObject(ctx, obj0)
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(2, suit.pool.GetNumIdle())
suit.pool.Clear(ctx)
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
obj2 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(getNthObject(2), obj2)
}
func (suit *PoolTestSuite) TestBaseInvalidateObject() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
obj0 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
obj1 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.assertEquals(2, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
err := suit.pool.InvalidateObject(ctx, obj0)
suit.NoError(err)
suit.assertEquals(1, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
err = suit.pool.InvalidateObject(ctx, obj1)
suit.NoError(err)
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestBaseClosePool() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
obj, err := suit.pool.BorrowObject(ctx)
suit.NoError(err)
suit.pool.ReturnObject(ctx, obj)
suit.pool.Close(ctx)
obj, err = suit.pool.BorrowObject(ctx)
suit.NotNil(err)
suit.Nil(obj)
}
func (suit *PoolTestSuite) TestWhenExhaustedFail() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 1
suit.pool.Config.BlockWhenExhausted = false
obj1 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
err2 := suit.ErrorWithResult(suit.pool.BorrowObject(ctx))
_, ok := err2.(*NoSuchElementErr)
suit.True(ok, "expect NoSuchElementErr but get", reflect.TypeOf(err2))
suit.pool.ReturnObject(ctx, obj1)
suit.assertEquals(1, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestWhenExhaustedBlock() {
suit.pool.Config.MaxTotal = 1
suit.pool.Config.BlockWhenExhausted = true
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
obj1 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
err2 := suit.ErrorWithResult(suit.pool.BorrowObject(ctx))
_, ok := err2.(*NoSuchElementErr)
suit.True(ok, "expect NoSuchElementErr but get", reflect.TypeOf(err2))
suit.pool.ReturnObject(ctx, obj1)
}
func borrowAndWait(ctx context.Context, pool *ObjectPool, pause time.Duration) chan time.Duration {
ch := make(chan time.Duration, 1)
go func() {
preborrow := time.Now()
obj, _ := pool.BorrowObject(ctx)
//objectId = obj;
postborrow := time.Now()
ch <- postborrow.Sub(preborrow)
time.Sleep(pause)
if obj != nil {
pool.ReturnObject(ctx, obj)
}
//postreturn = time.Now();
}()
return ch
}
func (suit *PoolTestSuite) TestWhenExhaustedBlockInterrupt() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 1
suit.pool.Config.BlockWhenExhausted = true
obj1, _ := suit.pool.BorrowObject(ctx)
// Make sure on object was obtained
suit.assertNotNil(obj1)
// Create a separate goroutine to try and borrow another object
//WaitingTestGoroutine wtt = new WaitingTestGoroutine(pool, 200000);
ch := borrowAndWait(ctx, suit.pool, 200000*time.Millisecond)
// Give wtt time to start
time.Sleep(200 * time.Millisecond)
suit.pool.idleObjects.InterruptTakeWaiters()
borrowTime := <-ch
close(ch)
if debugTest {
fmt.Println("TestWhenExhaustedBlockInterrupt borrowTime:", borrowTime)
}
suit.True(borrowTime >= 200)
// Check goroutine was interrupted
//assertTrue(wtt._thrown instanceof InterruptedException);
// Return object to the pool
suit.pool.ReturnObject(ctx, obj1)
// Bug POOL-162 - check there is now an object in the pool
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
obj2 := suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.pool.ReturnObject(ctx, obj2)
}
func (suit *PoolTestSuite) TestEvictWhileEmpty() {
ctx := context.Background()
suit.pool.evict(ctx)
suit.pool.evict(ctx)
}
type TestGoroutineArg struct {
/** pool to borrow from */
pool *ObjectPool
/** number of borrow attempts */
iter int
/** delay before each borrow attempt */
startDelay time.Duration
borrowTimeout time.Duration
/** time to hold each borrowed object before returning it */
holdTime time.Duration
/** whether or not start and hold time are randomly generated */
randomDelay bool
/** object expected to be borrowed (fail otherwise) */
expectedObject interface{}
}
type TestGoroutineResult struct {
complete bool
failed bool
error error
preborrow time.Time
postborrow time.Time
postreturn time.Time
ended time.Time
objectID interface{}
}
func NewTesGoroutineArgSimple(pool *ObjectPool, iter int, delay time.Duration, randomDelay bool) *TestGoroutineArg {
return NewTestGoroutineArg(pool, iter, delay, time.Duration(0), delay, randomDelay, nil)
}
func NewTestGoroutineArg(pool *ObjectPool, iter int, startDelay, borrowTimeout,
holdTime time.Duration, randomDelay bool, obj interface{}) *TestGoroutineArg {
return &TestGoroutineArg{
pool: pool,
iter: iter,
startDelay: startDelay,
borrowTimeout: borrowTimeout,
holdTime: holdTime,
randomDelay: randomDelay,
expectedObject: obj,
}
}
func goroutineRun(ctx context.Context, arg *TestGoroutineArg) chan TestGoroutineResult {
resultChan := make(chan TestGoroutineResult, 1)
result := TestGoroutineResult{}
go func() {
for i := 0; i < arg.iter; i++ {
var startDelay time.Duration
if arg.randomDelay {
startDelay = time.Duration(rand.Int63n(int64(arg.startDelay)))
} else {
startDelay = arg.startDelay
}
var holdTime time.Duration
if arg.randomDelay {
holdTime = time.Duration(rand.Int63n(int64(arg.holdTime)))
} else {
holdTime = arg.holdTime
}
time.Sleep(startDelay)
startBorrow := time.Now()
borrowCtx := ctx
if arg.borrowTimeout > 0 {
var borrowCancel func()
borrowCtx, borrowCancel = context.WithTimeout(ctx, arg.borrowTimeout)
defer borrowCancel()
}
obj, err := arg.pool.BorrowObject(borrowCtx)
endBorrow := time.Now()
if err != nil {
if debugTest {
fmt.Println("borrow error, time:", endBorrow.Sub(startBorrow))
}
result.error = err
result.failed = true
result.complete = true
break
}
if arg.expectedObject != nil && !(arg.expectedObject == obj) {
result.error = fmt.Errorf("Expected: %v found: %v", arg.expectedObject, obj)
result.failed = true
result.complete = true
break
}
time.Sleep(holdTime)
//startReturn := time.Now()
err = arg.pool.ReturnObject(ctx, obj)
//endReturn := time.Now()
//fmt.Println("returnTime:", endReturn.Sub(startReturn))
if err != nil {
result.error = err
result.failed = true
result.complete = true
break
}
}
result.complete = true
resultChan <- result
}()
return resultChan
}
func (suit *PoolTestSuite) TestEvictAddObjects() {
ctx := context.Background()
suit.factory.makeLatency = 300 * time.Millisecond
suit.factory.maxTotal = 2
suit.pool.Config.MaxTotal = 2
suit.pool.Config.MinIdle = 1
suit.pool.BorrowObject(ctx) // numActive = 1, numIdle = 0
// Create a test goroutine that will run once and try a borrow after
// 150ms fixed delay
borrower := NewTesGoroutineArgSimple(suit.pool, 1, 150*time.Millisecond, false)
//// Set evictor to run in 100 ms - will create idle instance
suit.pool.Config.TimeBetweenEvictionRuns = 100 * time.Millisecond
ch := goroutineRun(ctx, borrower)
result := <-ch
close(ch)
if debugTest {
fmt.Printf("TestEvictAddObjects %v error:%v", borrower, result.error)
}
suit.True(!result.failed)
}
func (suit *PoolTestSuite) TestEvictLIFO() {
suit.checkEvict(context.Background(), true)
}
func (suit *PoolTestSuite) TestEvictFIFO() {
suit.checkEvict(context.Background(), false)
}
func (suit *PoolTestSuite) checkEvict(ctx context.Context, lifo bool) {
var idle int
// yea suit is hairy but it tests all the code paths in GOP.evict()
suit.pool.Config.SoftMinEvictableIdleTime = 10 * time.Millisecond
suit.pool.Config.MinIdle = 2
suit.pool.Config.TestWhileIdle = true
suit.pool.Config.LIFO = lifo
Prefill(ctx, suit.pool, 5)
suit.pool.evict(ctx)
idle = suit.pool.GetNumIdle()
if debugTest {
fmt.Printf("checkEvict lifo:%v idel:%v \n", lifo, idle)
}
suit.factory.evenValid = false
suit.factory.oddValid = false
suit.factory.exceptionOnActivate = true
suit.pool.evict(ctx)
idle = suit.pool.GetNumIdle()
if debugTest {
fmt.Printf("checkEvict lifo:%v idel:%v \n", lifo, idle)
}
Prefill(ctx, suit.pool, 5)
suit.factory.exceptionOnActivate = false
suit.factory.exceptionOnPassivate = true
suit.pool.evict(ctx)
idle = suit.pool.GetNumIdle()
if debugTest {
fmt.Printf("checkEvict lifo:%v idel:%v \n", lifo, idle)
}
suit.factory.exceptionOnPassivate = false
suit.factory.evenValid = true
suit.factory.oddValid = true
time.Sleep(time.Duration(125) * time.Millisecond)
suit.pool.evict(ctx)
idle = suit.pool.GetNumIdle()
if debugTest {
fmt.Printf("checkEvict lifo:%v idel:%v \n", lifo, idle)
}
suit.assertEquals(2, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestEvictionOrder() {
ctx := context.Background()
suit.checkEvictionOrder(ctx, false)
suit.TearDownTest()
suit.SetupTest()
suit.checkEvictionOrder(ctx, true)
}
func (suit *PoolTestSuite) checkEvictionOrder(ctx context.Context, lifo bool) {
suit.checkEvictionOrderPart1(ctx, lifo)
suit.TearDownTest()
suit.SetupTest()
suit.checkEvictionOrderPart2(ctx, lifo)
}
func (suit *PoolTestSuite) checkEvictionOrderPart1(ctx context.Context, lifo bool) {
suit.pool.Config.NumTestsPerEvictionRun = 2
suit.pool.Config.MinEvictableIdleTime = 100 * time.Millisecond
suit.pool.Config.LIFO = lifo
for i := 0; i < 5; i++ {
suit.pool.AddObject(ctx)
time.Sleep(time.Duration(100) * time.Millisecond)
}
// Order, oldest to youngest, is "0", "1", ...,"4"
suit.pool.evict(ctx) // Should evict "0" and "1"
obj, _ := suit.pool.BorrowObject(ctx)
suit.True(getNthObject(0) != obj, "oldest not evicted")
suit.True(getNthObject(1) != obj, "second oldest not evicted")
// 2 should be next out for FIFO, 4 for LIFO
var expect *TestObject
if lifo {
expect = getNthObject(4)
} else {
expect = getNthObject(2)
}
suit.Equal(expect, obj, "Wrong instance returned")
}
func (suit *PoolTestSuite) checkEvictionOrderPart2(ctx context.Context, lifo bool) {
// Two eviction runs in sequence
suit.pool.Config.NumTestsPerEvictionRun = 2
suit.pool.Config.MinEvictableIdleTime = 100 * time.Millisecond
suit.pool.Config.LIFO = lifo
for i := 0; i < 5; i++ {
suit.pool.AddObject(ctx)
time.Sleep(time.Duration(100) * time.Millisecond)
}
suit.pool.evict(ctx) // Should evict "0" and "1"
suit.pool.evict(ctx) // Should evict "2" and "3"
obj, _ := suit.pool.BorrowObject(ctx)
suit.Equal(getNthObject(4), obj, "Wrong instance remaining in pool")
}
func (suit *PoolTestSuite) TestEvictorVisiting() {
suit.checkEvictorVisiting(true)
suit.checkEvictorVisiting(false)
}
func (suit *PoolTestSuite) checkEvictorVisiting(lifo bool) {
//TODO
}
func (suit *PoolTestSuite) TestExceptionOnPassivateDuringReturn() {
ctx := context.Background()
obj, _ := suit.pool.BorrowObject(ctx)
suit.factory.exceptionOnPassivate = true
suit.pool.ReturnObject(ctx, obj)
suit.assertEquals(0, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestExceptionOnPassivateDuringReturnWithBorrowWaiting() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 1
suit.pool.Config.BlockWhenExhausted = true
suit.factory.exceptionOnPassivate = true
obj, _ := suit.pool.BorrowObject(ctx)
goBorrow := func(ch chan<- interface{}, pool *ObjectPool) {
obj, _ := suit.pool.BorrowObject(ctx)
ch <- obj
}
ch1 := make(chan interface{})
go goBorrow(ch1, suit.pool)
ch2 := make(chan interface{})
go goBorrow(ch2, suit.pool)
select {
case <-ch1:
suit.FailNow("Borrowing additional objects should have blocked")
case <-ch2:
suit.FailNow("Borrowing additional objects should have blocked")
case <-time.After(100 * time.Millisecond):
// Just wait a moment to make sure neither of those channels, above, read...
}
suit.pool.ReturnObject(ctx, obj)
select {
case obj1 := <-ch1:
suit.T().Log("Returning item borrowed (ch1)")
suit.pool.ReturnObject(ctx, obj1)
case obj2 := <-ch2:
suit.T().Log("Returning item borrowed (ch2)")
suit.pool.ReturnObject(ctx, obj2)
case <-time.After(100 * time.Millisecond):
// Just wait a moment to make sure neither of those channels, above, read...
suit.FailNow("Failed to borrow additional objects")
}
// Once again, for the other channel
select {
case obj1 := <-ch1:
suit.T().Log("Returning item borrowed (ch1)")
suit.pool.ReturnObject(ctx, obj1)
case obj2 := <-ch2:
suit.T().Log("Returning item borrowed (ch2)")
suit.pool.ReturnObject(ctx, obj2)
case <-time.After(100 * time.Millisecond):
// Just wait a moment to make sure neither of those channels, above, read...
suit.FailNow("Failed to borrow additional objects")
}
}
func (suit *PoolTestSuite) TestExceptionOnDestroyDuringBorrow() {
ctx := context.Background()
suit.factory.exceptionOnDestroy = true
suit.pool.Config.TestOnBorrow = true
suit.pool.BorrowObject(ctx)
suit.factory.setValid(false) // Make validation fail on next borrow attempt
_, err := suit.pool.BorrowObject(ctx)
suit.NotNil(err)
suit.assertEquals(1, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestExceptionOnDestroyDuringReturn() {
ctx := context.Background()
suit.factory.exceptionOnDestroy = true
suit.pool.Config.TestOnReturn = true
obj1, _ := suit.pool.BorrowObject(ctx)
suit.pool.BorrowObject(ctx)
suit.factory.setValid(false) // Make validation fail
suit.pool.ReturnObject(context.Background(), obj1)
suit.assertEquals(1, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestExceptionOnActivateDuringBorrow() {
ctx := context.Background()
obj1, _ := suit.pool.BorrowObject(ctx)
obj2, _ := suit.pool.BorrowObject(ctx)
suit.pool.ReturnObject(ctx, obj1)
suit.pool.ReturnObject(ctx, obj2)
suit.factory.exceptionOnActivate = true
suit.factory.evenValid = false
// Activation will now throw every other time
// First attempt throws, but loop continues and second succeeds
obj, _ := suit.pool.BorrowObject(ctx)
suit.assertEquals(1, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
suit.pool.ReturnObject(ctx, obj)
suit.factory.setValid(false)
// Validation will now fail on activation when borrowObject returns
// an idle instance, and then when attempting to create a new instance
_, err := suit.pool.BorrowObject(ctx)
_, ok := err.(*NoSuchElementErr)
suit.True(ok, "expect NoSuchElementErr but get", reflect.TypeOf(err))
suit.assertEquals(0, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
}
func (suit *PoolTestSuite) TestNegativeMaxTotal() {
ctx := context.Background()
suit.pool.Config.MaxTotal = -1
suit.pool.Config.BlockWhenExhausted = false
obj, _ := suit.pool.BorrowObject(ctx)
suit.assertEquals(getNthObject(0), obj)
suit.pool.ReturnObject(context.Background(), obj)
}
func (suit *PoolTestSuite) TestMaxIdle() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 100
suit.pool.Config.MaxIdle = 8
active := make([]*TestObject, 100)
for i := 0; i < 100; i++ {
obj, err := suit.pool.BorrowObject(ctx)
suit.NoError(err)
testObj := obj.(*TestObject)
suit.NotNil(testObj)
active[i] = testObj
}
suit.assertEquals(100, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
for i := 0; i < 100; i++ {
obj := active[i]
if debugTest {
fmt.Printf("TestMaxIdle ReturnObject %v \n", obj)
}
err := suit.pool.ReturnObject(ctx, obj)
suit.NoError(err)
suit.assertEquals(99-i, suit.pool.GetNumActive())
idle := suit.pool.Config.MaxIdle
if i < idle {
idle = i + 1
}
suit.assertEquals(idle, suit.pool.GetNumIdle())
}
}
func (suit *PoolTestSuite) TestMaxIdleZero() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 100
suit.pool.Config.MaxIdle = 0
active := make([]*TestObject, 100)
for i := 0; i < 100; i++ {
obj, err := suit.pool.BorrowObject(ctx)
suit.NoError(err)
testObj := obj.(*TestObject)
suit.NotNil(testObj)
active[i] = testObj
}
suit.assertEquals(100, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
for i := 0; i < 100; i++ {
suit.pool.ReturnObject(ctx, active[i])
suit.assertEquals(99-i, suit.pool.GetNumActive())
suit.assertEquals(0, suit.pool.GetNumIdle())
}
}
func (suit *PoolTestSuite) TestMaxTotal() {
ctx := context.Background()
suit.pool.Config.MaxTotal = 3
suit.pool.Config.BlockWhenExhausted = false
suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
suit.NoErrorWithResult(suit.pool.BorrowObject(ctx))
_, err := suit.pool.BorrowObject(ctx)
suit.Error(err)
}
func (suit *PoolTestSuite) TestTimeoutNoLeak() {
suit.pool.Config.MaxTotal = 2
suit.pool.Config.BlockWhenExhausted = true
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
obj, err := suit.pool.BorrowObject(ctx)
suit.NoError(err)