github.com/gofunct/common@v0.0.0-20190131174352-fd058c7fbf22/pkg/temp/temptest/dir.go (about) 1 package temptest 2 3 import ( 4 "errors" 5 "fmt" 6 "io" 7 8 "github.com/gofunct/common/pkg/temp" 9 ) 10 11 // FakeDir implements a Directory that is not backed on the 12 // filesystem. This is useful for testing since the created "files" are 13 // simple bytes.Buffer that can be inspected. 14 type FakeDir struct { 15 Files map[string]*FakeFile 16 Deleted bool 17 } 18 19 var _ temp.Directory = &FakeDir{} 20 21 // NewFile returns a new FakeFile if the filename doesn't exist already. 22 // This function will fail if the directory has already been deleted. 23 func (d *FakeDir) NewFile(name string) (io.WriteCloser, error) { 24 if d.Deleted { 25 return nil, errors.New("can't create file in deleted FakeDir") 26 } 27 if d.Files == nil { 28 d.Files = map[string]*FakeFile{} 29 } 30 f := d.Files[name] 31 if f != nil { 32 return nil, fmt.Errorf( 33 "FakeDir already has file named %q", 34 name, 35 ) 36 } 37 f = &FakeFile{} 38 d.Files[name] = f 39 return f, nil 40 } 41 42 // Delete doesn't remove anything, but records that the directory has 43 // been deleted. 44 func (d *FakeDir) Delete() error { 45 if d.Deleted { 46 return errors.New("failed to re-delete FakeDir") 47 } 48 d.Deleted = true 49 return nil 50 }