scan_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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("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{{Duration: time.Minute}}},
  82. {[]interface{}{[]byte("1m")}, []*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. {"absent values",
  212. []string{},
  213. &s1{},
  214. },
  215. }
  216. func TestScanStruct(t *testing.T) {
  217. for _, tt := range scanStructTests {
  218. var reply []interface{}
  219. for _, v := range tt.reply {
  220. reply = append(reply, []byte(v))
  221. }
  222. value := reflect.New(reflect.ValueOf(tt.value).Type().Elem())
  223. if err := redis.ScanStruct(reply, value.Interface()); err != nil {
  224. t.Fatalf("ScanStruct(%s) returned error %v", tt.title, err)
  225. }
  226. if !reflect.DeepEqual(value.Interface(), tt.value) {
  227. t.Fatalf("ScanStruct(%s) returned %v, want %v", tt.title, value.Interface(), tt.value)
  228. }
  229. }
  230. }
  231. func TestBadScanStructArgs(t *testing.T) {
  232. x := []interface{}{"A", "b"}
  233. test := func(v interface{}) {
  234. if err := redis.ScanStruct(x, v); err == nil {
  235. t.Errorf("Expect error for ScanStruct(%T, %T)", x, v)
  236. }
  237. }
  238. test(nil)
  239. var v0 *struct{}
  240. test(v0)
  241. var v1 int
  242. test(&v1)
  243. x = x[:1]
  244. v2 := struct{ A string }{}
  245. test(&v2)
  246. }
  247. var scanSliceTests = []struct {
  248. src []interface{}
  249. fieldNames []string
  250. ok bool
  251. dest interface{}
  252. }{
  253. {
  254. []interface{}{[]byte("1"), nil, []byte("-1")},
  255. nil,
  256. true,
  257. []int{1, 0, -1},
  258. },
  259. {
  260. []interface{}{[]byte("1"), nil, []byte("2")},
  261. nil,
  262. true,
  263. []uint{1, 0, 2},
  264. },
  265. {
  266. []interface{}{[]byte("-1")},
  267. nil,
  268. false,
  269. []uint{1},
  270. },
  271. {
  272. []interface{}{[]byte("hello"), nil, []byte("world")},
  273. nil,
  274. true,
  275. [][]byte{[]byte("hello"), nil, []byte("world")},
  276. },
  277. {
  278. []interface{}{[]byte("hello"), nil, []byte("world")},
  279. nil,
  280. true,
  281. []string{"hello", "", "world"},
  282. },
  283. {
  284. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  285. nil,
  286. true,
  287. []struct{ A, B string }{{"a1", "b1"}, {"a2", "b2"}},
  288. },
  289. {
  290. []interface{}{[]byte("a1"), []byte("b1")},
  291. nil,
  292. false,
  293. []struct{ A, B, C string }{{"a1", "b1", ""}},
  294. },
  295. {
  296. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  297. nil,
  298. true,
  299. []*struct{ A, B string }{{A: "a1", B: "b1"}, {A: "a2", B: "b2"}},
  300. },
  301. {
  302. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  303. []string{"A", "B"},
  304. true,
  305. []struct{ A, C, B string }{{"a1", "", "b1"}, {"a2", "", "b2"}},
  306. },
  307. {
  308. []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")},
  309. nil,
  310. false,
  311. []struct{}{},
  312. },
  313. }
  314. func TestScanSlice(t *testing.T) {
  315. for _, tt := range scanSliceTests {
  316. typ := reflect.ValueOf(tt.dest).Type()
  317. dest := reflect.New(typ)
  318. err := redis.ScanSlice(tt.src, dest.Interface(), tt.fieldNames...)
  319. if tt.ok != (err == nil) {
  320. t.Errorf("ScanSlice(%v, []%s, %v) returned error %v", tt.src, typ, tt.fieldNames, err)
  321. continue
  322. }
  323. if tt.ok && !reflect.DeepEqual(dest.Elem().Interface(), tt.dest) {
  324. t.Errorf("ScanSlice(src, []%s) returned %#v, want %#v", typ, dest.Elem().Interface(), tt.dest)
  325. }
  326. }
  327. }
  328. func ExampleScanSlice() {
  329. c, err := dial()
  330. if err != nil {
  331. fmt.Println(err)
  332. return
  333. }
  334. defer c.Close()
  335. c.Send("HMSET", "album:1", "title", "Red", "rating", 5)
  336. c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1)
  337. c.Send("HMSET", "album:3", "title", "Beat", "rating", 4)
  338. c.Send("LPUSH", "albums", "1")
  339. c.Send("LPUSH", "albums", "2")
  340. c.Send("LPUSH", "albums", "3")
  341. values, err := redis.Values(c.Do("SORT", "albums",
  342. "BY", "album:*->rating",
  343. "GET", "album:*->title",
  344. "GET", "album:*->rating"))
  345. if err != nil {
  346. fmt.Println(err)
  347. return
  348. }
  349. var albums []struct {
  350. Title string
  351. Rating int
  352. }
  353. if err := redis.ScanSlice(values, &albums); err != nil {
  354. fmt.Println(err)
  355. return
  356. }
  357. fmt.Printf("%v\n", albums)
  358. // Output:
  359. // [{Earthbound 1} {Beat 4} {Red 5}]
  360. }
  361. var argsTests = []struct {
  362. title string
  363. actual redis.Args
  364. expected redis.Args
  365. }{
  366. {"struct ptr",
  367. redis.Args{}.AddFlat(&struct {
  368. I int `redis:"i"`
  369. U uint `redis:"u"`
  370. S string `redis:"s"`
  371. P []byte `redis:"p"`
  372. M map[string]string `redis:"m"`
  373. Bt bool
  374. Bf bool
  375. }{
  376. -1234, 5678, "hello", []byte("world"), map[string]string{"hello": "world"}, true, false,
  377. }),
  378. redis.Args{"i", int(-1234), "u", uint(5678), "s", "hello", "p", []byte("world"), "m", map[string]string{"hello": "world"}, "Bt", true, "Bf", false},
  379. },
  380. {"struct",
  381. redis.Args{}.AddFlat(struct{ I int }{123}),
  382. redis.Args{"I", 123},
  383. },
  384. {"slice",
  385. redis.Args{}.Add(1).AddFlat([]string{"a", "b", "c"}).Add(2),
  386. redis.Args{1, "a", "b", "c", 2},
  387. },
  388. {"struct omitempty",
  389. redis.Args{}.AddFlat(&struct {
  390. Sdp *durationArg `redis:"Sdp,omitempty"`
  391. }{
  392. nil,
  393. }),
  394. redis.Args{},
  395. },
  396. }
  397. func TestArgs(t *testing.T) {
  398. for _, tt := range argsTests {
  399. if !reflect.DeepEqual(tt.actual, tt.expected) {
  400. t.Fatalf("%s is %v, want %v", tt.title, tt.actual, tt.expected)
  401. }
  402. }
  403. }
  404. func ExampleArgs() {
  405. c, err := dial()
  406. if err != nil {
  407. fmt.Println(err)
  408. return
  409. }
  410. defer c.Close()
  411. var p1, p2 struct {
  412. Title string `redis:"title"`
  413. Author string `redis:"author"`
  414. Body string `redis:"body"`
  415. }
  416. p1.Title = "Example"
  417. p1.Author = "Gary"
  418. p1.Body = "Hello"
  419. if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
  420. fmt.Println(err)
  421. return
  422. }
  423. m := map[string]string{
  424. "title": "Example2",
  425. "author": "Steve",
  426. "body": "Map",
  427. }
  428. if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
  429. fmt.Println(err)
  430. return
  431. }
  432. for _, id := range []string{"id1", "id2"} {
  433. v, err := redis.Values(c.Do("HGETALL", id))
  434. if err != nil {
  435. fmt.Println(err)
  436. return
  437. }
  438. if err := redis.ScanStruct(v, &p2); err != nil {
  439. fmt.Println(err)
  440. return
  441. }
  442. fmt.Printf("%+v\n", p2)
  443. }
  444. // Output:
  445. // {Title:Example Author:Gary Body:Hello}
  446. // {Title:Example2 Author:Steve Body:Map}
  447. }