From dd9c654291f8686a614add8514b8a37fe37056ed Mon Sep 17 00:00:00 2001 From: Wang Xu Date: Tue, 27 Feb 2018 15:37:12 +0800 Subject: [PATCH] tests for shrink the socks pool Signed-off-by: Wang Xu --- session_test.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/session_test.go b/session_test.go index eb2c812b3..359b7455e 100644 --- a/session_test.go +++ b/session_test.go @@ -30,11 +30,13 @@ import ( "flag" "fmt" "math" + "math/rand" "os" "runtime" "sort" "strconv" "strings" + "sync" "testing" "time" @@ -166,6 +168,87 @@ func (s *S) TestURLInvalidReadPreference(c *C) { } } +func (s *S) TestMinPoolSize(c *C) { + tests := []struct { + url string + size int + fail bool + }{ + {"localhost:40001?minPoolSize=0", 0, false}, + {"localhost:40001?minPoolSize=1", 1, false}, + {"localhost:40001?minPoolSize=-1", -1, true}, + {"localhost:40001?minPoolSize=-.", 0, true}, + } + for _, test := range tests { + info, err := mgo.ParseURL(test.url) + if test.fail { + c.Assert(err, NotNil) + } else { + c.Assert(err, IsNil) + c.Assert(info.MinPoolSize, Equals, test.size) + } + } +} + +func (s *S) TestMaxIdleTimeMS(c *C) { + tests := []struct { + url string + size int + fail bool + }{ + {"localhost:40001?maxIdleTimeMS=0", 0, false}, + {"localhost:40001?maxIdleTimeMS=1", 1, false}, + {"localhost:40001?maxIdleTimeMS=-1", -1, true}, + {"localhost:40001?maxIdleTimeMS=-.", 0, true}, + } + for _, test := range tests { + info, err := mgo.ParseURL(test.url) + if test.fail { + c.Assert(err, NotNil) + } else { + c.Assert(err, IsNil) + c.Assert(info.MaxIdleTimeMS, Equals, test.size) + } + } +} + +func (s *S) TestPoolShrink(c *C) { + oldSocket := mgo.GetStats().SocketsAlive + + session, err := mgo.Dial("localhost:40001?minPoolSize=1&maxIdleTimeMS=1000") + c.Assert(err, IsNil) + defer session.Close() + + parallel := 10 + res := make(chan error, parallel+1) + wg := &sync.WaitGroup{} + for i := 1; i < parallel; i++ { + wg.Add(1) + go func() { + s := session.Copy() + defer s.Close() + result := struct{}{} + err := s.Run("ping", &result) + + //sleep random time to make the allocate and release in different sequence + time.Sleep(time.Duration(rand.Intn(parallel)*100) * time.Millisecond) + res <- err + wg.Done() + }() + } + wg.Wait() + stats := mgo.GetStats() + c.Logf("living socket: After queries: %d, before queris: %d", stats.SocketsAlive, oldSocket) + + // give some time for shrink the pool, the tick is set to 1 minute + c.Log("Sleeping... 1 minutes to for pool shrinking") + time.Sleep(61 * time.Second) + + stats = mgo.GetStats() + c.Logf("living socket: After shrinking: %d, at the beginning of the test: %d", stats.SocketsAlive, oldSocket) + c.Assert(stats.SocketsAlive-oldSocket > 1, Equals, false) +} + func (s *S) TestURLReadPreferenceTags(c *C) { type test struct { url string