record_test.go 2.4 KB

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