scan_test.go 11 KB

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