scan_test.go 9.9 KB

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