@@ -746,6 +746,51 @@ func TestExtendedLifetimeTimeout(t *testing.T) {
746
746
}
747
747
}
748
748
749
+ // TestMaxIdleCount tests the MaxIdleCount setting, to check if the pool closes
750
+ // the idle connections when the number of idle connections exceeds the limit.
751
+ func TestMaxIdleCount (t * testing.T ) {
752
+ testMaxIdleCount := func (t * testing.T , setting * Setting , maxIdleCount int64 , expClosedConn int ) {
753
+ var state TestState
754
+
755
+ ctx := context .Background ()
756
+ p := NewPool (& Config [* TestConn ]{
757
+ Capacity : 5 ,
758
+ MaxIdleCount : maxIdleCount ,
759
+ LogWait : state .LogWait ,
760
+ }).Open (newConnector (& state ), nil )
761
+
762
+ defer p .Close ()
763
+
764
+ var conns []* Pooled [* TestConn ]
765
+ for i := 0 ; i < 5 ; i ++ {
766
+ r , err := p .Get (ctx , setting )
767
+ require .NoError (t , err )
768
+ assert .EqualValues (t , i + 1 , state .open .Load ())
769
+ assert .EqualValues (t , 0 , p .Metrics .IdleClosed ())
770
+
771
+ conns = append (conns , r )
772
+ }
773
+
774
+ for _ , conn := range conns {
775
+ p .put (conn )
776
+ }
777
+
778
+ closedConn := 0
779
+ for _ , conn := range conns {
780
+ if conn .Conn .IsClosed () {
781
+ closedConn ++
782
+ }
783
+ }
784
+ assert .EqualValues (t , expClosedConn , closedConn )
785
+ assert .EqualValues (t , expClosedConn , p .Metrics .IdleClosed ())
786
+ }
787
+
788
+ t .Run ("WithoutSettings" , func (t * testing.T ) { testMaxIdleCount (t , nil , 2 , 3 ) })
789
+ t .Run ("WithSettings" , func (t * testing.T ) { testMaxIdleCount (t , sFoo , 2 , 3 ) })
790
+ t .Run ("WithoutSettings-MaxIdleCount-Zero" , func (t * testing.T ) { testMaxIdleCount (t , nil , 0 , 0 ) })
791
+ t .Run ("WithSettings-MaxIdleCount-Zero" , func (t * testing.T ) { testMaxIdleCount (t , sFoo , 0 , 0 ) })
792
+ }
793
+
749
794
func TestCreateFail (t * testing.T ) {
750
795
var state TestState
751
796
state .chaos .failConnect = true
0 commit comments