我有两个对象编写器,第一个封装io.Writer
并沿写入它还计算内容的 SHA1 校验和,第二个首先封装并写入 zlib 压缩数据。
我的带有一些测试数据的单元测试用例通过了第一位作者,但第二位作者失败了。
我在哪里做错了什么?
代码片段:
import (
"compress/zlib"
"crypto/sha1"
"hash"
"io"
)
type ObjectWriter interface {
io.Writer
Commit() ([]byte, error)
}
type oWriter struct {
writer io.Writer
sum hash.Hash
}
func (ow *oWriter) Write(b []byte) (int, error) {
ow.sum.Write(b) // Hash writer never returs error -> hash.Hash docs
return ow.writer.Write(b)
}
func (ow *oWriter) Commit() ([]byte, error) {
return ow.sum.Sum(nil), nil
}
func NewWriter(w io.Writer) ObjectWriter {
return &oWriter{w, sha1.New()}
}
type compressedWriter struct {
oWriter ObjectWriter
zWriter io.WriteCloser
}
func (ow *compressedWriter) Write(b []byte) (int, error) {
return ow.zWriter.Write(b)
}
func (ow *compressedWriter) Commit() ([]byte, error) {
if err := ow.zWriter.Close(); err != nil {
return nil, err
}
return ow.oWriter.Commit()
}
func NewCompressedWriter(w io.Writer) ObjectWriter {
ow := NewWriter(w)
zw := zlib.NewWriter(ow)
return &compressedWriter{ow, zw}
}
通过测试用例:
func TestObjectWriter(t *testing.T) {
var buf bytes.Buffer
ow := NewWriter(&buf)
ow.Write([]byte("test content"))
sum, err := ow.Commit()
if err != nil {
t.Errorf("Commit error: %s", err)
}
expected := "1eebdf4fdc9fc7bf283031b93f9aef3338de9052"
given := fmt.Sprintf("%x", sum)
if expected != given {
t.Errorf("Invalid SHA1 sum: <%s> != <%s>", expected, given)
}
}
失败的测试用例:
func TestCompressedObjectWriter(t *testing.T) {
var buf bytes.Buffer
ow := NewCompressedWriter(&buf)
ow.Write([]byte("test content"))
sum, err := ow.Commit()
if err != nil {
t.Errorf("Commit error: %s", err)
}
expected := "7efbe4015afd95478282c3774f47b4195031d27e"
given := fmt.Sprintf("%x", sum)
if expected != given {
t.Errorf("Invalid SHA1 sum: <%s> != <%s>", expected, given)
}
}