github.com/stuarqi/moby@v1.13.1/pkg/testutil/tempfile/tempfile.go (about)

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