record_test.go 2.4 KB

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