go.etcd.io/etcd@v3.3.27+incompatible/pkg/pbutil/pbutil_test.go (about) 1 // Copyright 2015 The etcd Authors 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 15 package pbutil 16 17 import ( 18 "errors" 19 "reflect" 20 "testing" 21 ) 22 23 func TestMarshaler(t *testing.T) { 24 data := []byte("test data") 25 m := &fakeMarshaler{data: data} 26 if g := MustMarshal(m); !reflect.DeepEqual(g, data) { 27 t.Errorf("data = %s, want %s", g, m.data) 28 } 29 } 30 31 func TestMarshalerPanic(t *testing.T) { 32 defer func() { 33 if r := recover(); r == nil { 34 t.Errorf("recover = nil, want error") 35 } 36 }() 37 m := &fakeMarshaler{err: errors.New("blah")} 38 MustMarshal(m) 39 } 40 41 func TestUnmarshaler(t *testing.T) { 42 data := []byte("test data") 43 m := &fakeUnmarshaler{} 44 MustUnmarshal(m, data) 45 if !reflect.DeepEqual(m.data, data) { 46 t.Errorf("data = %s, want %s", m.data, data) 47 } 48 } 49 50 func TestUnmarshalerPanic(t *testing.T) { 51 defer func() { 52 if r := recover(); r == nil { 53 t.Errorf("recover = nil, want error") 54 } 55 }() 56 m := &fakeUnmarshaler{err: errors.New("blah")} 57 MustUnmarshal(m, nil) 58 } 59 60 func TestGetBool(t *testing.T) { 61 tests := []struct { 62 b *bool 63 wb bool 64 wset bool 65 }{ 66 {nil, false, false}, 67 {Boolp(true), true, true}, 68 {Boolp(false), false, true}, 69 } 70 for i, tt := range tests { 71 b, set := GetBool(tt.b) 72 if b != tt.wb { 73 t.Errorf("#%d: value = %v, want %v", i, b, tt.wb) 74 } 75 if set != tt.wset { 76 t.Errorf("#%d: set = %v, want %v", i, set, tt.wset) 77 } 78 } 79 } 80 81 type fakeMarshaler struct { 82 data []byte 83 err error 84 } 85 86 func (m *fakeMarshaler) Marshal() ([]byte, error) { 87 return m.data, m.err 88 } 89 90 type fakeUnmarshaler struct { 91 data []byte 92 err error 93 } 94 95 func (m *fakeUnmarshaler) Unmarshal(data []byte) error { 96 m.data = data 97 return m.err 98 }