github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/pkg/test/blob.go (about) 1 /* 2 Copyright 2011 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package test 18 19 import ( 20 "crypto/sha1" 21 "io" 22 "strings" 23 "testing" 24 25 "camlistore.org/pkg/blob" 26 "camlistore.org/pkg/blobserver" 27 ) 28 29 // Blob is a utility class for unit tests. 30 type Blob struct { 31 Contents string // the contents of the blob 32 } 33 34 func (tb *Blob) BlobRef() blob.Ref { 35 h := sha1.New() 36 h.Write([]byte(tb.Contents)) 37 return blob.RefFromHash(h) 38 } 39 40 func (tb *Blob) SizedRef() blob.SizedRef { 41 return blob.SizedRef{tb.BlobRef(), int64(len(tb.Contents))} 42 } 43 44 func (tb *Blob) BlobRefSlice() []blob.Ref { 45 return []blob.Ref{tb.BlobRef()} 46 } 47 48 func (tb *Blob) Size() int64 { 49 return int64(len(tb.Contents)) 50 } 51 52 func (tb *Blob) Reader() io.Reader { 53 return strings.NewReader(tb.Contents) 54 } 55 56 func (tb *Blob) AssertMatches(t *testing.T, sb blob.SizedRef) { 57 if sb.Size != tb.Size() { 58 t.Fatalf("Got size %d; expected %d", sb.Size, tb.Size()) 59 } 60 if sb.Ref != tb.BlobRef() { 61 t.Fatalf("Got blob %q; expected %q", sb.Ref.String(), tb.BlobRef()) 62 } 63 } 64 65 func (tb *Blob) MustUpload(t *testing.T, ds blobserver.BlobReceiver) { 66 sb, err := ds.ReceiveBlob(tb.BlobRef(), tb.Reader()) 67 if err != nil { 68 t.Fatalf("failed to upload blob %v (%q): %v", tb.BlobRef(), tb.Contents, err) 69 } 70 tb.AssertMatches(t, sb) // TODO: better error reporting 71 }