pubsub_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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_test
  15. import (
  16. "reflect"
  17. "testing"
  18. "time"
  19. "github.com/gomodule/redigo/redis"
  20. )
  21. func expectPushed(t *testing.T, c redis.PubSubConn, message string, expected interface{}) {
  22. actual := c.Receive()
  23. if !reflect.DeepEqual(actual, expected) {
  24. t.Errorf("%s = %v, want %v", message, actual, expected)
  25. }
  26. }
  27. func TestPushed(t *testing.T) {
  28. pc, err := redis.DialDefaultServer()
  29. if err != nil {
  30. t.Fatalf("error connection to database, %v", err)
  31. }
  32. defer pc.Close()
  33. sc, err := redis.DialDefaultServer()
  34. if err != nil {
  35. t.Fatalf("error connection to database, %v", err)
  36. }
  37. defer sc.Close()
  38. c := redis.PubSubConn{Conn: sc}
  39. c.Subscribe("c1")
  40. expectPushed(t, c, "Subscribe(c1)", redis.Subscription{Kind: "subscribe", Channel: "c1", Count: 1})
  41. c.Subscribe("c2")
  42. expectPushed(t, c, "Subscribe(c2)", redis.Subscription{Kind: "subscribe", Channel: "c2", Count: 2})
  43. c.PSubscribe("p1")
  44. expectPushed(t, c, "PSubscribe(p1)", redis.Subscription{Kind: "psubscribe", Channel: "p1", Count: 3})
  45. c.PSubscribe("p2")
  46. expectPushed(t, c, "PSubscribe(p2)", redis.Subscription{Kind: "psubscribe", Channel: "p2", Count: 4})
  47. c.PUnsubscribe()
  48. expectPushed(t, c, "Punsubscribe(p1)", redis.Subscription{Kind: "punsubscribe", Channel: "p1", Count: 3})
  49. expectPushed(t, c, "Punsubscribe()", redis.Subscription{Kind: "punsubscribe", Channel: "p2", Count: 2})
  50. pc.Do("PUBLISH", "c1", "hello")
  51. expectPushed(t, c, "PUBLISH c1 hello", redis.Message{Channel: "c1", Data: []byte("hello")})
  52. c.Ping("hello")
  53. expectPushed(t, c, `Ping("hello")`, redis.Pong{Data: "hello"})
  54. c.Conn.Send("PING")
  55. c.Conn.Flush()
  56. expectPushed(t, c, `Send("PING")`, redis.Pong{})
  57. c.Ping("timeout")
  58. got := c.ReceiveWithTimeout(time.Minute)
  59. if want := (redis.Pong{Data: "timeout"}); want != got {
  60. t.Errorf("recv /w timeout got %v, want %v", got, want)
  61. }
  62. }