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 15package wal 16 17import ( 18 "bytes" 19 "hash/crc32" 20 "io" 21 "io/ioutil" 22 "reflect" 23 "testing" 24 25 "go.etcd.io/etcd/wal/walpb" 26) 27 28var ( 29 infoData = []byte("\b\xef\xfd\x02") 30 infoRecord = append([]byte("\x0e\x00\x00\x00\x00\x00\x00\x00\b\x01\x10\x99\xb5\xe4\xd0\x03\x1a\x04"), infoData...) 31) 32 33func TestReadRecord(t *testing.T) { 34 badInfoRecord := make([]byte, len(infoRecord)) 35 copy(badInfoRecord, infoRecord) 36 badInfoRecord[len(badInfoRecord)-1] = 'a' 37 38 tests := []struct { 39 data []byte 40 wr *walpb.Record 41 we error 42 }{ 43 {infoRecord, &walpb.Record{Type: 1, Crc: crc32.Checksum(infoData, crcTable), Data: infoData}, nil}, 44 {[]byte(""), &walpb.Record{}, io.EOF}, 45 {infoRecord[:8], &walpb.Record{}, io.ErrUnexpectedEOF}, 46 {infoRecord[:len(infoRecord)-len(infoData)-8], &walpb.Record{}, io.ErrUnexpectedEOF}, 47 {infoRecord[:len(infoRecord)-len(infoData)], &walpb.Record{}, io.ErrUnexpectedEOF}, 48 {infoRecord[:len(infoRecord)-8], &walpb.Record{}, io.ErrUnexpectedEOF}, 49 {badInfoRecord, &walpb.Record{}, walpb.ErrCRCMismatch}, 50 } 51 52 rec := &walpb.Record{} 53 for i, tt := range tests { 54 buf := bytes.NewBuffer(tt.data) 55 decoder := newDecoder(ioutil.NopCloser(buf)) 56 e := decoder.decode(rec) 57 if !reflect.DeepEqual(rec, tt.wr) { 58 t.Errorf("#%d: block = %v, want %v", i, rec, tt.wr) 59 } 60 if !reflect.DeepEqual(e, tt.we) { 61 t.Errorf("#%d: err = %v, want %v", i, e, tt.we) 62 } 63 rec = &walpb.Record{} 64 } 65} 66 67func TestWriteRecord(t *testing.T) { 68 b := &walpb.Record{} 69 typ := int64(0xABCD) 70 d := []byte("Hello world!") 71 buf := new(bytes.Buffer) 72 e := newEncoder(buf, 0, 0) 73 e.encode(&walpb.Record{Type: typ, Data: d}) 74 e.flush() 75 decoder := newDecoder(ioutil.NopCloser(buf)) 76 err := decoder.decode(b) 77 if err != nil { 78 t.Errorf("err = %v, want nil", err) 79 } 80 if b.Type != typ { 81 t.Errorf("type = %d, want %d", b.Type, typ) 82 } 83 if !reflect.DeepEqual(b.Data, d) { 84 t.Errorf("data = %v, want %v", b.Data, d) 85 } 86} 87