restic/backend/writer_test.go

82 lines
2.0 KiB
Go
Raw Normal View History

2015-02-15 22:21:35 +00:00
package backend_test
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"io"
"io/ioutil"
"testing"
"github.com/restic/restic/backend"
2015-04-09 19:15:48 +00:00
. "github.com/restic/restic/test"
2015-02-15 22:21:35 +00:00
)
func TestHashAppendWriter(t *testing.T) {
tests := []int{5, 23, 2<<18 + 23, 1 << 20}
for _, size := range tests {
data := make([]byte, size)
_, err := io.ReadFull(rand.Reader, data)
if err != nil {
t.Fatalf("ReadFull: %v", err)
}
expectedHash := sha256.Sum256(data)
target := bytes.NewBuffer(nil)
wr := backend.NewHashAppendWriter(target, sha256.New())
_, err = wr.Write(data)
2015-04-09 19:15:48 +00:00
OK(t, err)
OK(t, wr.Close())
2015-02-15 22:21:35 +00:00
2015-04-09 19:15:48 +00:00
Assert(t, len(target.Bytes()) == size+len(expectedHash),
2015-02-15 22:21:35 +00:00
"HashAppendWriter: invalid number of bytes written: got %d, expected %d",
len(target.Bytes()), size+len(expectedHash))
r := target.Bytes()
resultingHash := r[len(r)-len(expectedHash):]
2015-04-09 19:15:48 +00:00
Assert(t, bytes.Equal(expectedHash[:], resultingHash),
2015-02-15 22:21:35 +00:00
"HashAppendWriter: hashes do not match: expected %02x, got %02x",
expectedHash, resultingHash)
// write again, this must return an error
_, err = wr.Write([]byte{23})
2015-04-09 19:15:48 +00:00
Assert(t, err != nil,
2015-02-15 22:21:35 +00:00
"HashAppendWriter: Write() after Close() did not return an error")
}
}
func TestHashingWriter(t *testing.T) {
tests := []int{5, 23, 2<<18 + 23, 1 << 20}
for _, size := range tests {
data := make([]byte, size)
_, err := io.ReadFull(rand.Reader, data)
if err != nil {
t.Fatalf("ReadFull: %v", err)
}
expectedHash := sha256.Sum256(data)
wr := backend.NewHashingWriter(ioutil.Discard, sha256.New())
n, err := io.Copy(wr, bytes.NewReader(data))
2015-04-09 19:15:48 +00:00
OK(t, err)
2015-02-15 22:21:35 +00:00
2015-04-09 19:15:48 +00:00
Assert(t, n == int64(size),
2015-02-15 22:21:35 +00:00
"HashAppendWriter: invalid number of bytes written: got %d, expected %d",
n, size)
2015-04-09 19:15:48 +00:00
Assert(t, wr.Size() == size,
2015-02-15 23:24:43 +00:00
"HashAppendWriter: invalid number of bytes returned: got %d, expected %d",
wr.Size, size)
2015-02-15 22:21:35 +00:00
resultingHash := wr.Sum(nil)
2015-04-09 19:15:48 +00:00
Assert(t, bytes.Equal(expectedHash[:], resultingHash),
2015-02-15 22:21:35 +00:00
"HashAppendWriter: hashes do not match: expected %02x, got %02x",
expectedHash, resultingHash)
}
}