pbutil_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package pbutil
  14. import (
  15. "errors"
  16. "reflect"
  17. "testing"
  18. )
  19. func TestMarshaler(t *testing.T) {
  20. data := []byte("test data")
  21. m := &fakeMarshaler{data: data}
  22. if g := MustMarshal(m); !reflect.DeepEqual(g, data) {
  23. t.Errorf("data = %s, want %s", g, m)
  24. }
  25. }
  26. func TestMarshalerPanic(t *testing.T) {
  27. defer func() {
  28. if r := recover(); r == nil {
  29. t.Errorf("recover = nil, want error")
  30. }
  31. }()
  32. m := &fakeMarshaler{err: errors.New("blah")}
  33. MustMarshal(m)
  34. }
  35. func TestUnmarshaler(t *testing.T) {
  36. data := []byte("test data")
  37. m := &fakeUnmarshaler{}
  38. MustUnmarshal(m, data)
  39. if !reflect.DeepEqual(m.data, data) {
  40. t.Errorf("data = %s, want %s", m.data, m)
  41. }
  42. }
  43. func TestUnmarshalerPanic(t *testing.T) {
  44. defer func() {
  45. if r := recover(); r == nil {
  46. t.Errorf("recover = nil, want error")
  47. }
  48. }()
  49. m := &fakeUnmarshaler{err: errors.New("blah")}
  50. MustUnmarshal(m, nil)
  51. }
  52. func TestGetBool(t *testing.T) {
  53. tests := []struct {
  54. b *bool
  55. wb bool
  56. wset bool
  57. }{
  58. {nil, false, false},
  59. {Boolp(true), true, true},
  60. {Boolp(false), false, true},
  61. }
  62. for i, tt := range tests {
  63. b, set := GetBool(tt.b)
  64. if b != tt.wb {
  65. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  66. }
  67. if set != tt.wset {
  68. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  69. }
  70. }
  71. }
  72. type fakeMarshaler struct {
  73. data []byte
  74. err error
  75. }
  76. func (m *fakeMarshaler) Marshal() ([]byte, error) {
  77. return m.data, m.err
  78. }
  79. type fakeUnmarshaler struct {
  80. data []byte
  81. err error
  82. }
  83. func (m *fakeUnmarshaler) Unmarshal(data []byte) error {
  84. m.data = data
  85. return m.err
  86. }