Tizen_4.0 base
[platform/upstream/docker-engine.git] / pkg / testutil / tempfile / tempfile.go
1 package tempfile
2
3 import (
4         "io/ioutil"
5         "os"
6
7         "github.com/stretchr/testify/require"
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 require.TestingT, prefix string, content string) *TempFile {
19         file, err := ioutil.TempFile("", prefix+"-")
20         require.NoError(t, err)
21
22         _, err = file.Write([]byte(content))
23         require.NoError(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 }
37
38 // TempDir is a temporary directory that can be used with unit tests. TempDir
39 // reduces the boilerplate setup required in each test case by handling
40 // setup errors.
41 type TempDir struct {
42         Path string
43 }
44
45 // NewTempDir returns a new temp file with contents
46 func NewTempDir(t require.TestingT, prefix string) *TempDir {
47         path, err := ioutil.TempDir("", prefix+"-")
48         require.NoError(t, err)
49
50         return &TempDir{Path: path}
51 }
52
53 // Remove removes the file
54 func (f *TempDir) Remove() {
55         os.Remove(f.Path)
56 }