tempfile.go 785 B

1234567891011121314151617181920212223242526272829303132333435
  1. package tempfile
  2. import (
  3. "github.com/docker/docker/pkg/testutil/assert"
  4. "io/ioutil"
  5. "os"
  6. )
  7. // TempFile is a temporary file that can be used with unit tests. TempFile
  8. // reduces the boilerplate setup required in each test case by handling
  9. // setup errors.
  10. type TempFile struct {
  11. File *os.File
  12. }
  13. // NewTempFile returns a new temp file with contents
  14. func NewTempFile(t assert.TestingT, prefix string, content string) *TempFile {
  15. file, err := ioutil.TempFile("", prefix+"-")
  16. assert.NilError(t, err)
  17. _, err = file.Write([]byte(content))
  18. assert.NilError(t, err)
  19. file.Close()
  20. return &TempFile{File: file}
  21. }
  22. // Name returns the filename
  23. func (f *TempFile) Name() string {
  24. return f.File.Name()
  25. }
  26. // Remove removes the file
  27. func (f *TempFile) Remove() {
  28. os.Remove(f.Name())
  29. }