filesystem.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2015 CoreOS, 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 test
  15. import (
  16. "fmt"
  17. "os"
  18. "path"
  19. )
  20. type MockFilesystem map[string]File
  21. type File struct {
  22. Path string
  23. Contents string
  24. Directory bool
  25. }
  26. func (m MockFilesystem) ReadFile(filename string) ([]byte, error) {
  27. if f, ok := m[path.Clean(filename)]; ok {
  28. if f.Directory {
  29. return nil, fmt.Errorf("read %s: is a directory", filename)
  30. }
  31. return []byte(f.Contents), nil
  32. }
  33. return nil, os.ErrNotExist
  34. }
  35. func NewMockFilesystem(files ...File) MockFilesystem {
  36. fs := MockFilesystem{}
  37. for _, file := range files {
  38. fs[file.Path] = file
  39. // Create the directories leading up to the file
  40. p := path.Dir(file.Path)
  41. for p != "/" && p != "." {
  42. if f, ok := fs[p]; ok && !f.Directory {
  43. panic(fmt.Sprintf("%q already exists and is not a directory (%#v)", p, f))
  44. }
  45. fs[p] = File{Path: p, Directory: true}
  46. p = path.Dir(p)
  47. }
  48. }
  49. return fs
  50. }