scan_test.go 12 KB

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