github.com/uber/kraken@v0.1.4/lib/store/testing.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, 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 store 15 16 import ( 17 "bytes" 18 "io" 19 "io/ioutil" 20 "os" 21 22 "github.com/uber/kraken/core" 23 "github.com/uber/kraken/utils/testutil" 24 ) 25 26 // MockFileReadWriter is a mock FileReadWriter that is backed by a 27 // physical file. This is preferred to a gomock struct because read/write 28 // operations are greatly simplified. 29 type MockFileReadWriter struct { 30 *os.File 31 Committed bool 32 } 33 34 // Commit implements FileReadWriter.Commit 35 func (f *MockFileReadWriter) Commit() error { panic("commit not implemented") } 36 37 // Cancel implements FileReadWriter.Cancel 38 func (f *MockFileReadWriter) Cancel() error { panic("cancel not implemented") } 39 40 // Size implements FileReadWriter.Size 41 func (f *MockFileReadWriter) Size() int64 { panic("size not implemented") } 42 43 var _ FileReadWriter = (*MockFileReadWriter)(nil) 44 45 // NewMockFileReadWriter returns a new MockFileReadWriter and a cleanup function. 46 func NewMockFileReadWriter(content []byte) (*MockFileReadWriter, func()) { 47 cleanup := new(testutil.Cleanup) 48 defer cleanup.Recover() 49 50 tmp, err := ioutil.TempFile("", "") 51 if err != nil { 52 panic(err) 53 } 54 name := tmp.Name() 55 cleanup.Add(func() { os.Remove(name) }) 56 57 if _, err := tmp.Write(content); err != nil { 58 panic(err) 59 } 60 if err := tmp.Close(); err != nil { 61 panic(err) 62 } 63 64 // Open fresh file. 65 f, err := os.OpenFile(name, os.O_RDWR, 0775) 66 if err != nil { 67 panic(err) 68 } 69 70 return &MockFileReadWriter{File: f}, cleanup.Run 71 } 72 73 // RunDownload downloads content to cads. 74 func RunDownload(cads *CADownloadStore, d core.Digest, content []byte) error { 75 if err := cads.CreateDownloadFile(d.Hex(), int64(len(content))); err != nil { 76 return err 77 } 78 w, err := cads.GetDownloadFileReadWriter(d.Hex()) 79 if err != nil { 80 return err 81 } 82 if _, err := io.Copy(w, bytes.NewReader(content)); err != nil { 83 return err 84 } 85 return cads.MoveDownloadFileToCache(d.Hex()) 86 }