Skip to content

Commit

Permalink
add TemoFile fixture
Browse files Browse the repository at this point in the history
  • Loading branch information
rekby committed May 14, 2023
1 parent 150ed59 commit f703112
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
21 changes: 20 additions & 1 deletion sf/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import (
"os"
)

// TempDir return path for existet temporary folder
// the folder will remove after test finish with all contents
func TempDir(e fixenv.Env) string {
return e.CacheWithCleanup(nil, nil, func() (res interface{}, cleanup fixenv.FixtureCleanupFunc, err error) {
dir, err := os.MkdirTemp("", "")
dir, err := os.MkdirTemp("", "fixenv-auto-")
mustNoErr(e, err, "failed to create temp dir: %v", err)
e.T().Logf("Temp dir created: %v", dir)
clean := func() {
Expand All @@ -17,3 +19,20 @@ func TempDir(e fixenv.Env) string {
return dir, clean, nil
}).(string)
}

// TempFile return path to empty existed file in TempDir
func TempFile(e fixenv.Env) string {
return TempFileNamed(e, "fixenv-auto-")
}

// TempFileNamed return path to empty file in TempDir
// pattern is pattern for os.CreateTemp
func TempFileNamed(e fixenv.Env, pattern string) string {
return e.Cache(nil, nil, func() (res interface{}, err error) {
dir := TempDir(e)
f, err := os.CreateTemp(dir, pattern)
mustNoErr(e, err, "failed to create temp file: %w", err)
fName := f.Name()
return fName, f.Close()
}).(string)
}
16 changes: 16 additions & 0 deletions sf/filesystem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,19 @@ func TestTempDir(t *testing.T) {
t.Fatalf("Directory must be removed after test finished, have err: %v", err)
}
}

func TestTempFile(t *testing.T) {
var file string
t.Run("subtest", func(t *testing.T) {
e := fixenv.New(t)
file := TempFile(e)
if _, err := os.Stat(file); err != nil {
t.Fatal(err)
}
})

_, err := os.Stat(file)
if !os.IsNotExist(err) {
t.Fatal("File must be removed with temp directory")
}
}

0 comments on commit f703112

Please sign in to comment.