github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/pool/default_test.go (about) 1 // Copyright 2020 Asim Aslam 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Original source: github.com/micro/go-micro/v3/util/pool/default_test.go 16 17 package pool 18 19 import ( 20 "testing" 21 "time" 22 23 "github.com/tickoalcantara12/micro/v3/service/network/transport" 24 "github.com/tickoalcantara12/micro/v3/service/network/transport/memory" 25 ) 26 27 func testPool(t *testing.T, size int, ttl time.Duration) { 28 // mock transport 29 tr := memory.NewTransport() 30 31 options := Options{ 32 TTL: ttl, 33 Size: size, 34 Transport: tr, 35 } 36 // zero pool 37 p := newPool(options) 38 39 // listen 40 l, err := tr.Listen(":0") 41 if err != nil { 42 t.Fatal(err) 43 } 44 defer l.Close() 45 46 // accept loop 47 go func() { 48 for { 49 if err := l.Accept(func(s transport.Socket) { 50 for { 51 var msg transport.Message 52 if err := s.Recv(&msg); err != nil { 53 return 54 } 55 if err := s.Send(&msg); err != nil { 56 return 57 } 58 } 59 }); err != nil { 60 return 61 } 62 } 63 }() 64 65 for i := 0; i < 10; i++ { 66 // get a conn 67 c, err := p.Get(l.Addr()) 68 if err != nil { 69 t.Fatal(err) 70 } 71 72 msg := &transport.Message{ 73 Body: []byte(`hello world`), 74 } 75 76 if err := c.Send(msg); err != nil { 77 t.Fatal(err) 78 } 79 80 var rcv transport.Message 81 82 if err := c.Recv(&rcv); err != nil { 83 t.Fatal(err) 84 } 85 86 if string(rcv.Body) != string(msg.Body) { 87 t.Fatalf("got %v, expected %v", rcv.Body, msg.Body) 88 } 89 90 // release the conn 91 p.Release(c, nil) 92 93 p.Lock() 94 if i := len(p.conns[l.Addr()]); i > size { 95 p.Unlock() 96 t.Fatalf("pool size %d is greater than expected %d", i, size) 97 } 98 p.Unlock() 99 } 100 } 101 102 func TestClientPool(t *testing.T) { 103 testPool(t, 0, time.Minute) 104 testPool(t, 2, time.Minute) 105 }