tempfile.go 778 B

123456789101112131415161718192021222324252627282930313233343536
  1. package tempfile
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "github.com/stretchr/testify/require"
  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 require.TestingT, prefix string, content string) *TempFile {
  15. file, err := ioutil.TempFile("", prefix+"-")
  16. require.NoError(t, err)
  17. _, err = file.Write([]byte(content))
  18. require.NoError(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. }