scan_test.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. "math"
  19. "reflect"
  20. "testing"
  21. )
  22. var scanConversionTests = []struct {
  23. src interface{}
  24. dest interface{}
  25. }{
  26. {[]byte("-inf"), math.Inf(-1)},
  27. {[]byte("+inf"), math.Inf(1)},
  28. {[]byte("0"), float64(0)},
  29. {[]byte("3.14159"), float64(3.14159)},
  30. {[]byte("3.14"), float32(3.14)},
  31. {[]byte("-100"), int(-100)},
  32. {[]byte("101"), int(101)},
  33. {int64(102), int(102)},
  34. {[]byte("103"), uint(103)},
  35. {int64(104), uint(104)},
  36. {[]byte("105"), int8(105)},
  37. {int64(106), int8(106)},
  38. {[]byte("107"), uint8(107)},
  39. {int64(108), uint8(108)},
  40. {[]byte("0"), false},
  41. {int64(0), false},
  42. {[]byte("f"), false},
  43. {[]byte("1"), true},
  44. {int64(1), true},
  45. {[]byte("t"), true},
  46. {[]byte("hello"), "hello"},
  47. {[]byte("world"), []byte("world")},
  48. {[]interface{}{[]byte("foo")}, []interface{}{[]byte("foo")}},
  49. {[]interface{}{[]byte("foo")}, []string{"foo"}},
  50. {[]interface{}{[]byte("hello"), []byte("world")}, []string{"hello", "world"}},
  51. {[]interface{}{[]byte("bar")}, [][]byte{[]byte("bar")}},
  52. {[]interface{}{[]byte("1")}, []int{1}},
  53. {[]interface{}{[]byte("1"), []byte("2")}, []int{1, 2}},
  54. {[]interface{}{[]byte("1"), []byte("2")}, []float64{1, 2}},
  55. {[]interface{}{[]byte("1")}, []byte{1}},
  56. {[]interface{}{[]byte("1")}, []bool{true}},
  57. }
  58. func TestScanConversion(t *testing.T) {
  59. for _, tt := range scanConversionTests {
  60. values := []interface{}{tt.src}
  61. dest := reflect.New(reflect.TypeOf(tt.dest))
  62. values, err := redis.Scan(values, dest.Interface())
  63. if err != nil {
  64. t.Errorf("Scan(%v) returned error %v", tt, err)
  65. continue
  66. }
  67. if !reflect.DeepEqual(tt.dest, dest.Elem().Interface()) {
  68. t.Errorf("Scan(%v) returned %v, want %v", tt, dest.Elem().Interface(), tt.dest)
  69. }
  70. }
  71. }
  72. var scanConversionErrorTests = []struct {
  73. src interface{}
  74. dest interface{}
  75. }{
  76. {[]byte("1234"), byte(0)},
  77. {int64(1234), byte(0)},
  78. {[]byte("-1"), byte(0)},
  79. {int64(-1), byte(0)},
  80. {[]byte("junk"), false},
  81. {redis.Error("blah"), false},
  82. }
  83. func TestScanConversionError(t *testing.T) {
  84. for _, tt := range scanConversionErrorTests {
  85. values := []interface{}{tt.src}
  86. dest := reflect.New(reflect.TypeOf(tt.dest))
  87. values, err := redis.Scan(values, dest.Interface())
  88. if err == nil {
  89. t.Errorf("Scan(%v) did not return error", tt)
  90. }
  91. }
  92. }
  93. func ExampleScan() {
  94. c, err := dial()
  95. if err != nil {
  96. panic(err)
  97. }
  98. defer c.Close()
  99. c.Send("HMSET", "album:1", "title", "Red", "rating", 5)
  100. c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1)
  101. c.Send("HMSET", "album:3", "title", "Beat")
  102. c.Send("LPUSH", "albums", "1")
  103. c.Send("LPUSH", "albums", "2")
  104. c.Send("LPUSH", "albums", "3")
  105. values, err := redis.Values(c.Do("SORT", "albums",
  106. "BY", "album:*->rating",
  107. "GET", "album:*->title",
  108. "GET", "album:*->rating"))
  109. if err != nil {
  110. panic(err)
  111. }
  112. for len(values) > 0 {
  113. var title string
  114. rating := -1 // initialize to illegal value to detect nil.
  115. values, err = redis.Scan(values, &title, &rating)
  116. if err != nil {
  117. panic(err)
  118. }
  119. if rating == -1 {
  120. fmt.Println(title, "not-rated")
  121. } else {
  122. fmt.Println(title, rating)
  123. }
  124. }
  125. // Output:
  126. // Beat not-rated
  127. // Earthbound 1
  128. // Red 5
  129. }
  130. type s0 struct {
  131. X int
  132. Y int `redis:"y"`
  133. Bt bool
  134. }
  135. type s1 struct {
  136. X int `redis:"-"`
  137. I int `redis:"i"`
  138. U uint `redis:"u"`
  139. S string `redis:"s"`
  140. P []byte `redis:"p"`
  141. B bool `redis:"b"`
  142. Bt bool
  143. Bf bool
  144. s0
  145. }
  146. var scanStructTests = []struct {
  147. title string
  148. reply []string
  149. value interface{}
  150. }{
  151. {"basic",
  152. []string{"i", "-1234", "u", "5678", "s", "hello", "p", "world", "b", "t", "Bt", "1", "Bf", "0", "X", "123", "y", "456"},
  153. &s1{I: -1234, U: 5678, S: "hello", P: []byte("world"), B: true, Bt: true, Bf: false, s0: s0{X: 123, Y: 456}},
  154. },
  155. }
  156. func TestScanStruct(t *testing.T) {
  157. for _, tt := range scanStructTests {
  158. var reply []interface{}
  159. for _, v := range tt.reply {
  160. reply = append(reply, []byte(v))
  161. }
  162. value := reflect.New(reflect.ValueOf(tt.value).Type().Elem())
  163. if err := redis.ScanStruct(reply, value.Interface()); err != nil {
  164. t.Fatalf("ScanStruct(%s) returned error %v", tt.title, err)
  165. }
  166. if !reflect.DeepEqual(value.Interface(), tt.value) {
  167. t.Fatalf("ScanStruct(%s) returned %v, want %v", tt.title, value.Interface(), tt.value)
  168. }
  169. }
  170. }
  171. func TestBadScanStructArgs(t *testing.T) {
  172. x := []interface{}{"A", "b"}
  173. test := func(v interface{}) {
  174. if err := redis.ScanStruct(x, v); err == nil {
  175. t.Errorf("Expect error for ScanStruct(%T, %T)", x, v)
  176. }
  177. }
  178. test(nil)
  179. var v0 *struct{}
  180. test(v0)
  181. var v1 int
  182. test(&v1)
  183. x = x[:1]
  184. v2 := struct{ A string }{}
  185. test(&v2)
  186. }
  187. var scanSliceTests = []struct {
  188. src []interface{}
  189. fieldNames []string
  190. ok bool
  191. dest interface{}
  192. }{
  193. {
  194. []interface{}{[]byte("1"), nil, []byte("-1")},
  195. nil,
  196. true,
  197. []int{1, 0, -1},
  198. },
  199. {
  200. []interface{}{[]byte("1"), nil, []byte("2")},
  201. nil,
  202. true,
  203. []uint{1, 0, 2},
  204. },
  205. {
  206. []interface{}{[]byte("-1")},
  207. nil,
  208. false,
  209. []uint{1},
  210. },
  211. {
  212. []interface{}{[]byte("hello"), nil, []byte("world")},
  213. nil,
  214. true,
  215. [][]byte{[]byte("hello"), nil, []byte("world")},
  216. },
  217. {
  218. []interface{}{[]byte("hello"), nil, []byte("world")},
  219. nil,
  220. true,
  221. []string{"hello", "", "world"},
  222. },
  223. {
  224. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  225. nil,
  226. true,
  227. []struct{ A, B string }{{"a1", "b1"}, {"a2", "b2"}},
  228. },
  229. {
  230. []interface{}{[]byte("a1"), []byte("b1")},
  231. nil,
  232. false,
  233. []struct{ A, B, C string }{{"a1", "b1", ""}},
  234. },
  235. {
  236. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  237. nil,
  238. true,
  239. []*struct{ A, B string }{{"a1", "b1"}, {"a2", "b2"}},
  240. },
  241. {
  242. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  243. []string{"A", "B"},
  244. true,
  245. []struct{ A, C, B string }{{"a1", "", "b1"}, {"a2", "", "b2"}},
  246. },
  247. {
  248. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  249. nil,
  250. false,
  251. []struct{}{},
  252. },
  253. }
  254. func TestScanSlice(t *testing.T) {
  255. for _, tt := range scanSliceTests {
  256. typ := reflect.ValueOf(tt.dest).Type()
  257. dest := reflect.New(typ)
  258. err := redis.ScanSlice(tt.src, dest.Interface(), tt.fieldNames...)
  259. if tt.ok != (err == nil) {
  260. t.Errorf("ScanSlice(%v, []%s, %v) returned error %v", tt.src, typ, tt.fieldNames, err)
  261. continue
  262. }
  263. if tt.ok && !reflect.DeepEqual(dest.Elem().Interface(), tt.dest) {
  264. t.Errorf("ScanSlice(src, []%s) returned %#v, want %#v", typ, dest.Elem().Interface(), tt.dest)
  265. }
  266. }
  267. }
  268. func ExampleScanSlice() {
  269. c, err := dial()
  270. if err != nil {
  271. panic(err)
  272. }
  273. defer c.Close()
  274. c.Send("HMSET", "album:1", "title", "Red", "rating", 5)
  275. c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1)
  276. c.Send("HMSET", "album:3", "title", "Beat", "rating", 4)
  277. c.Send("LPUSH", "albums", "1")
  278. c.Send("LPUSH", "albums", "2")
  279. c.Send("LPUSH", "albums", "3")
  280. values, err := redis.Values(c.Do("SORT", "albums",
  281. "BY", "album:*->rating",
  282. "GET", "album:*->title",
  283. "GET", "album:*->rating"))
  284. if err != nil {
  285. panic(err)
  286. }
  287. var albums []struct {
  288. Title string
  289. Rating int
  290. }
  291. if err := redis.ScanSlice(values, &albums); err != nil {
  292. panic(err)
  293. }
  294. fmt.Printf("%v\n", albums)
  295. // Output:
  296. // [{Earthbound 1} {Beat 4} {Red 5}]
  297. }
  298. var argsTests = []struct {
  299. title string
  300. actual redis.Args
  301. expected redis.Args
  302. }{
  303. {"struct ptr",
  304. redis.Args{}.AddFlat(&struct {
  305. I int `redis:"i"`
  306. U uint `redis:"u"`
  307. S string `redis:"s"`
  308. P []byte `redis:"p"`
  309. Bt bool
  310. Bf bool
  311. }{
  312. -1234, 5678, "hello", []byte("world"), true, false,
  313. }),
  314. redis.Args{"i", int(-1234), "u", uint(5678), "s", "hello", "p", []byte("world"), "Bt", true, "Bf", false},
  315. },
  316. {"struct",
  317. redis.Args{}.AddFlat(struct{ I int }{123}),
  318. redis.Args{"I", 123},
  319. },
  320. {"slice",
  321. redis.Args{}.Add(1).AddFlat([]string{"a", "b", "c"}).Add(2),
  322. redis.Args{1, "a", "b", "c", 2},
  323. },
  324. }
  325. func TestArgs(t *testing.T) {
  326. for _, tt := range argsTests {
  327. if !reflect.DeepEqual(tt.actual, tt.expected) {
  328. t.Fatalf("%s is %v, want %v", tt.title, tt.actual, tt.expected)
  329. }
  330. }
  331. }
  332. func ExampleArgs() {
  333. c, err := dial()
  334. if err != nil {
  335. panic(err)
  336. }
  337. defer c.Close()
  338. var p1, p2 struct {
  339. Title string `redis:"title"`
  340. Author string `redis:"author"`
  341. Body string `redis:"body"`
  342. }
  343. p1.Title = "Example"
  344. p1.Author = "Gary"
  345. p1.Body = "Hello"
  346. if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
  347. panic(err)
  348. }
  349. m := map[string]string{
  350. "title": "Example2",
  351. "author": "Steve",
  352. "body": "Map",
  353. }
  354. if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
  355. panic(err)
  356. }
  357. for _, id := range []string{"id1", "id2"} {
  358. v, err := redis.Values(c.Do("HGETALL", id))
  359. if err != nil {
  360. panic(err)
  361. }
  362. if err := redis.ScanStruct(v, &p2); err != nil {
  363. panic(err)
  364. }
  365. fmt.Printf("%+v\n", p2)
  366. }
  367. // Output:
  368. // {Title:Example Author:Gary Body:Hello}
  369. // {Title:Example2 Author:Steve Body:Map}
  370. }