struct_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 redisx_test
  15. import (
  16. "github.com/garyburd/redigo/redisx"
  17. "reflect"
  18. "testing"
  19. )
  20. var scanStructTests = []struct {
  21. title string
  22. reply []string
  23. value interface{}
  24. }{
  25. {"basic",
  26. []string{"i", "-1234", "u", "5678", "s", "hello", "p", "world", "b", "", "Bt", "1", "Bf", "0"},
  27. &struct {
  28. I int `redis:"i"`
  29. U uint `redis:"u"`
  30. S string `redis:"s"`
  31. P []byte `redis:"p"`
  32. B bool `redis:"b"`
  33. Bt bool
  34. Bf bool
  35. }{
  36. -1234, 5678, "hello", []byte("world"), false, true, false,
  37. },
  38. },
  39. }
  40. func TestScanStruct(t *testing.T) {
  41. for _, tt := range scanStructTests {
  42. var reply []interface{}
  43. for _, v := range tt.reply {
  44. reply = append(reply, []byte(v))
  45. }
  46. value := reflect.New(reflect.ValueOf(tt.value).Type().Elem())
  47. if err := redisx.ScanStruct(reply, value.Interface()); err != nil {
  48. t.Fatalf("ScanStruct(%s) returned error %v", tt.title, err)
  49. }
  50. if !reflect.DeepEqual(value.Interface(), tt.value) {
  51. t.Fatalf("ScanStruct(%s) returned %v, want %v", tt.title, value.Interface(), tt.value)
  52. }
  53. }
  54. }
  55. var formatStructTests = []struct {
  56. title string
  57. args []interface{}
  58. value interface{}
  59. }{
  60. {"basic",
  61. []interface{}{"i", int(-1234), "u", uint(5678), "s", "hello", "p", []byte("world"), "Bt", true, "Bf", false},
  62. &struct {
  63. I int `redis:"i"`
  64. U uint `redis:"u"`
  65. S string `redis:"s"`
  66. P []byte `redis:"p"`
  67. Bt bool
  68. Bf bool
  69. }{
  70. -1234, 5678, "hello", []byte("world"), true, false,
  71. },
  72. },
  73. }
  74. func TestFormatStruct(t *testing.T) {
  75. for _, tt := range formatStructTests {
  76. args := redisx.AppendStruct(nil, tt.value)
  77. if !reflect.DeepEqual(args, tt.args) {
  78. t.Fatalf("FormatStruct(%s) returned %v, want %v", tt.title, args, tt.args)
  79. }
  80. }
  81. }