Skip to content

Commit 275ce95

Browse files
committed
Add File function to create specified file
1 parent 70fb4a6 commit 275ce95

File tree

3 files changed

+45
-2
lines changed

3 files changed

+45
-2
lines changed

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,16 @@ func TestFoo(t *testing.T) {
3939
}
4040
```
4141

42+
### Creating specified files:
43+
```
44+
func TestFoo(t *testing.T) {
45+
filet.File(t, "conf.yaml", "") // Creates a specified file
46+
47+
// Creates a specified file with string "some content"
48+
filet.File(t, "/tmp/conf.yaml", "some content")
49+
}
50+
```
51+
4252
### Cleaning up after yourself:
4353
Filet lets you clean up after your files with `CleanUp`, which is
4454
most cleanly used at the beginning of a function with `defer`. For example:

filet.go

+19-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ package filet
22

33
import (
44
"bytes"
5-
"github.com/spf13/afero"
5+
"os"
66
"path/filepath"
77
"testing"
8+
9+
"github.com/spf13/afero"
810
)
911

1012
// Files keeps track of files that we've used so we can clean up.
@@ -39,6 +41,22 @@ func TmpFile(t *testing.T, dir string, content string) afero.File {
3941
return file
4042
}
4143

44+
/*
45+
File Creates a specified file for us to use when testing
46+
*/
47+
func File(t *testing.T, path string, content string) afero.File {
48+
file, err := appFs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
49+
if err != nil {
50+
t.Error("Failed to create the file: "+path, err)
51+
return nil
52+
}
53+
54+
file.WriteString(content)
55+
Files = append(Files, file.Name())
56+
57+
return file
58+
}
59+
4260
/*
4361
FileSays returns true if the file at the path contains the expected byte array
4462
content.

filet_test.go

+16-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package filet
22

33
import (
4-
"github.com/stretchr/testify/assert"
54
"path/filepath"
65
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
"github.com/stretchr/testify/require"
79
)
810

911
func TestTmpDir(t *testing.T) {
@@ -29,6 +31,19 @@ func TestTmpFile(t *testing.T) {
2931
"TmpFile should create a file with content")
3032
}
3133

34+
func TestFile(t *testing.T) {
35+
defer CleanUp(t)
36+
37+
// Test that file is actually created
38+
file := File(t, "conf.yaml", "")
39+
require.FileExists(t, file.Name(), "File should create the file")
40+
41+
// Test that the content exists in the file
42+
file = File(t, "conf.yaml", "hey there")
43+
result := FileSays(t, file.Name(), []byte("hey there"))
44+
assert.True(t, result, "File should create a file with content")
45+
}
46+
3247
func TestFileSays(t *testing.T) {
3348
defer CleanUp(t)
3449

0 commit comments

Comments
 (0)