scan_test.go 12 KB

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