script_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "fmt"
  17. "github.com/garyburd/redigo/redis"
  18. "reflect"
  19. "testing"
  20. "time"
  21. )
  22. func ExampleScript(c redis.Conn, reply interface{}, err error) {
  23. // Initialize a package-level variable with a script.
  24. var getScript = redis.NewScript(1, `return redis.call('get', KEYS[1])`)
  25. // In a function, use the script Do method to evaluate the script. The Do
  26. // method optimistically uses the EVALSHA command. If the script is not
  27. // loaded, then the Do method falls back to the EVAL command.
  28. reply, err = getScript.Do(c, "foo")
  29. }
  30. func TestScript(t *testing.T) {
  31. c, err := dial()
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. defer c.Close()
  36. // To test fallback in Do, we make script unique by adding comment with current time.
  37. script := fmt.Sprintf("--%d\nreturn {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", time.Now().UnixNano())
  38. s := redis.NewScript(2, script)
  39. reply := []interface{}{[]byte("key1"), []byte("key2"), []byte("arg1"), []byte("arg2")}
  40. v, err := s.Do(c, "key1", "key2", "arg1", "arg2")
  41. if err != nil {
  42. t.Errorf("s.Do(c, ...) returned %v", err)
  43. }
  44. if !reflect.DeepEqual(v, reply) {
  45. t.Errorf("s.Do(c, ..); = %v, want %v", v, reply)
  46. }
  47. err = s.Load(c)
  48. if err != nil {
  49. t.Errorf("s.Load(c) returned %v", err)
  50. }
  51. err = s.SendHash(c, "key1", "key2", "arg1", "arg2")
  52. if err != nil {
  53. t.Errorf("s.SendHash(c, ...) returned %v", err)
  54. }
  55. v, err = c.Receive()
  56. if !reflect.DeepEqual(v, reply) {
  57. t.Errorf("s.SendHash(c, ..); s.Recevie() = %v, want %v", v, reply)
  58. }
  59. err = s.Send(c, "key1", "key2", "arg1", "arg2")
  60. if err != nil {
  61. t.Errorf("s.Send(c, ...) returned %v", err)
  62. }
  63. v, err = c.Receive()
  64. if !reflect.DeepEqual(v, reply) {
  65. t.Errorf("s.Send(c, ..); s.Recevie() = %v, want %v", v, reply)
  66. }
  67. }