scan_test.go 11 KB

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