pool_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2011 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://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, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "io"
  17. "testing"
  18. )
  19. type fakeConn struct {
  20. closed bool
  21. err error
  22. }
  23. func (c *fakeConn) Close() error { c.closed = true; return nil }
  24. func (c *fakeConn) Err() error { return c.err }
  25. func (c *fakeConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
  26. return nil, nil
  27. }
  28. func (c *fakeConn) Send(commandName string, args ...interface{}) error {
  29. return nil
  30. }
  31. func (c *fakeConn) Flush() error {
  32. return nil
  33. }
  34. func (c *fakeConn) Receive() (reply interface{}, err error) {
  35. return nil, nil
  36. }
  37. func TestPool(t *testing.T) {
  38. var count int
  39. p := NewPool(func() (Conn, error) { count += 1; return &fakeConn{}, nil }, 2)
  40. count = 0
  41. for i := 0; i < 10; i++ {
  42. c1, _ := p.Get()
  43. c2, _ := p.Get()
  44. c1.Close()
  45. c2.Close()
  46. }
  47. if count != 2 {
  48. t.Fatal("expected count 1, actual", count)
  49. }
  50. p.Get()
  51. p.Get()
  52. count = 0
  53. for i := 0; i < 10; i++ {
  54. c, _ := p.Get()
  55. c.(*pooledConnection).c.(*fakeConn).err = io.EOF
  56. c.Close()
  57. }
  58. if count != 10 {
  59. t.Fatal("expected count 10, actual", count)
  60. }
  61. p.Get()
  62. p.Get()
  63. count = 0
  64. for i := 0; i < 10; i++ {
  65. c1, _ := p.Get()
  66. c2, _ := p.Get()
  67. c3, _ := p.Get()
  68. c1.Close()
  69. c2.Close()
  70. c3.Close()
  71. }
  72. if count != 12 {
  73. t.Fatal("expected count 12, actual", count)
  74. }
  75. }