test_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2012 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. "bufio"
  17. "errors"
  18. "net"
  19. "time"
  20. )
  21. type testConn struct {
  22. Conn
  23. }
  24. func (t testConn) Close() error {
  25. _, err := t.Conn.Do("SELECT", "9")
  26. if err != nil {
  27. return nil
  28. }
  29. _, err = t.Conn.Do("FLUSHDB")
  30. if err != nil {
  31. return err
  32. }
  33. return t.Conn.Close()
  34. }
  35. // DialTestDB dials the local Redis server and selects database 9. To prevent
  36. // stomping on real data, DialTestDB fails if database 9 contains data. The
  37. // returned connection flushes database 9 on close.
  38. func DialTestDB() (Conn, error) {
  39. c, err := DialTimeout("tcp", ":6379", 0, 1*time.Second, 1*time.Second)
  40. if err != nil {
  41. return nil, err
  42. }
  43. _, err = c.Do("SELECT", "9")
  44. if err != nil {
  45. return nil, err
  46. }
  47. n, err := Int(c.Do("DBSIZE"))
  48. if err != nil {
  49. return nil, err
  50. }
  51. if n != 0 {
  52. return nil, errors.New("database #9 is not empty, test can not continue")
  53. }
  54. return testConn{c}, nil
  55. }
  56. type dummyClose struct{ net.Conn }
  57. func (dummyClose) Close() error { return nil }
  58. // NewConnBufio is a hook for tests.
  59. func NewConnBufio(rw bufio.ReadWriter) Conn {
  60. return &conn{br: rw.Reader, bw: rw.Writer, conn: dummyClose{}}
  61. }