pbutil_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  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,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package pbutil
  15. import (
  16. "errors"
  17. "reflect"
  18. "testing"
  19. )
  20. func TestMarshaler(t *testing.T) {
  21. data := []byte("test data")
  22. m := &fakeMarshaler{data: data}
  23. if g := MustMarshal(m); !reflect.DeepEqual(g, data) {
  24. t.Errorf("data = %s, want %s", g, m)
  25. }
  26. }
  27. func TestMarshalerPanic(t *testing.T) {
  28. defer func() {
  29. if r := recover(); r == nil {
  30. t.Errorf("recover = nil, want error")
  31. }
  32. }()
  33. m := &fakeMarshaler{err: errors.New("blah")}
  34. MustMarshal(m)
  35. }
  36. func TestUnmarshaler(t *testing.T) {
  37. data := []byte("test data")
  38. m := &fakeUnmarshaler{}
  39. MustUnmarshal(m, data)
  40. if !reflect.DeepEqual(m.data, data) {
  41. t.Errorf("data = %s, want %s", m.data, m)
  42. }
  43. }
  44. func TestUnmarshalerPanic(t *testing.T) {
  45. defer func() {
  46. if r := recover(); r == nil {
  47. t.Errorf("recover = nil, want error")
  48. }
  49. }()
  50. m := &fakeUnmarshaler{err: errors.New("blah")}
  51. MustUnmarshal(m, nil)
  52. }
  53. func TestGetBool(t *testing.T) {
  54. tests := []struct {
  55. b *bool
  56. wb bool
  57. wset bool
  58. }{
  59. {nil, false, false},
  60. {Boolp(true), true, true},
  61. {Boolp(false), false, true},
  62. }
  63. for i, tt := range tests {
  64. b, set := GetBool(tt.b)
  65. if b != tt.wb {
  66. t.Errorf("#%d: value = %v, want %v", i, b, tt.wb)
  67. }
  68. if set != tt.wset {
  69. t.Errorf("#%d: set = %v, want %v", i, set, tt.wset)
  70. }
  71. }
  72. }
  73. type fakeMarshaler struct {
  74. data []byte
  75. err error
  76. }
  77. func (m *fakeMarshaler) Marshal() ([]byte, error) {
  78. return m.data, m.err
  79. }
  80. type fakeUnmarshaler struct {
  81. data []byte
  82. err error
  83. }
  84. func (m *fakeUnmarshaler) Unmarshal(data []byte) error {
  85. m.data = data
  86. return m.err
  87. }