You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

69 lines
1.6 KiB

  1. // Copyright 2014 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 redistest contains utilities for writing Redigo tests.
  15. package redistest
  16. import (
  17. "errors"
  18. "time"
  19. "github.com/garyburd/redigo/redis"
  20. )
  21. type testConn struct {
  22. redis.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. // Dial 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 Dial() (redis.Conn, error) {
  39. c, err := redis.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. c.Close()
  46. return nil, err
  47. }
  48. n, err := redis.Int(c.Do("DBSIZE"))
  49. if err != nil {
  50. c.Close()
  51. return nil, err
  52. }
  53. if n != 0 {
  54. c.Close()
  55. return nil, errors.New("database #9 is not empty, test can not continue")
  56. }
  57. return testConn{c}, nil
  58. }