script_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 := dialt(t)
  32. defer c.Close()
  33. // To test fallback in Do, we make script unique by adding comment with current time.
  34. script := fmt.Sprintf("--%d\nreturn {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", time.Now().UnixNano())
  35. s := redis.NewScript(2, script)
  36. reply := []interface{}{[]byte("key1"), []byte("key2"), []byte("arg1"), []byte("arg2")}
  37. v, err := s.Do(c, "key1", "key2", "arg1", "arg2")
  38. if err != nil {
  39. t.Errorf("s.Do(c, ...) returned %v", err)
  40. }
  41. if !reflect.DeepEqual(v, reply) {
  42. t.Errorf("s.Do(c, ..); = %v, want %v", v, reply)
  43. }
  44. err = s.Load(c)
  45. if err != nil {
  46. t.Errorf("s.Load(c) returned %v", err)
  47. }
  48. err = s.SendHash(c, "key1", "key2", "arg1", "arg2")
  49. if err != nil {
  50. t.Errorf("s.SendHash(c, ...) returned %v", err)
  51. }
  52. err = c.Flush()
  53. if err != nil {
  54. t.Errorf("s.Flush() returned %v", err)
  55. }
  56. v, err = c.Receive()
  57. if !reflect.DeepEqual(v, reply) {
  58. t.Errorf("s.SendHash(c, ..); s.Recevie() = %v, want %v", v, reply)
  59. }
  60. err = s.Send(c, "key1", "key2", "arg1", "arg2")
  61. if err != nil {
  62. t.Errorf("s.Send(c, ...) returned %v", err)
  63. }
  64. err = c.Flush()
  65. if err != nil {
  66. t.Errorf("s.Flush() returned %v", err)
  67. }
  68. v, err = c.Receive()
  69. if !reflect.DeepEqual(v, reply) {
  70. t.Errorf("s.Send(c, ..); s.Recevie() = %v, want %v", v, reply)
  71. }
  72. }