github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/bytes_test.go (about) 1 // Copyright 2020 DataStax 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 primitive 16 17 import ( 18 "bytes" 19 "errors" 20 "fmt" 21 "io/ioutil" 22 "testing" 23 24 "github.com/stretchr/testify/assert" 25 ) 26 27 func TestReadBytes(t *testing.T) { 28 tests := []struct { 29 name string 30 source []byte 31 expected []byte 32 remaining []byte 33 err error 34 }{ 35 {"empty bytes", []byte{0, 0, 0, 0}, []byte{}, []byte{}, nil}, 36 {"nil bytes", []byte{0xff, 0xff, 0xff, 0xff}, nil, []byte{}, nil}, 37 {"singleton bytes", []byte{0, 0, 0, 1, 1}, []byte{1}, []byte{}, nil}, 38 {"simple bytes", []byte{0, 0, 0, 2, 1, 2}, []byte{1, 2}, []byte{}, nil}, 39 { 40 "cannot read bytes length", 41 []byte{0, 0, 0}, 42 nil, 43 []byte{}, 44 fmt.Errorf("cannot read [bytes] length: %w", fmt.Errorf("cannot read [int]: %w", errors.New("unexpected EOF"))), 45 }, 46 { 47 "cannot read bytes content", 48 []byte{0, 0, 0, 2, 1}, 49 nil, 50 []byte{}, 51 fmt.Errorf("cannot read [bytes] content: %w", errors.New("unexpected EOF")), 52 }, 53 } 54 for _, tt := range tests { 55 t.Run(tt.name, func(t *testing.T) { 56 buf := bytes.NewReader(tt.source) 57 actual, err := ReadBytes(buf) 58 assert.Equal(t, tt.err, err) 59 assert.Equal(t, tt.expected, actual) 60 61 remaining, _ := ioutil.ReadAll(buf) 62 assert.Equal(t, tt.remaining, remaining) 63 }) 64 } 65 } 66 67 func TestWriteBytes(t *testing.T) { 68 tests := []struct { 69 name string 70 input []byte 71 expected []byte 72 err error 73 }{ 74 { 75 "empty bytes", 76 []byte{}, 77 []byte{0, 0, 0, 0}, 78 nil, 79 }, 80 { 81 "nil bytes", 82 nil, 83 []byte{0xff, 0xff, 0xff, 0xff}, 84 nil, 85 }, 86 { 87 "singleton bytes", 88 []byte{1}, 89 []byte{0, 0, 0, 1, 1}, 90 nil, 91 }, 92 { 93 "simple bytes", 94 []byte{1, 2}, 95 []byte{0, 0, 0, 2, 1, 2}, 96 nil, 97 }, 98 } 99 for _, tt := range tests { 100 t.Run(tt.name, func(t *testing.T) { 101 buf := &bytes.Buffer{} 102 err := WriteBytes(tt.input, buf) 103 assert.Equal(t, tt.expected, buf.Bytes()) 104 assert.Equal(t, tt.err, err) 105 }) 106 } 107 }