-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_utils.go
More file actions
34 lines (28 loc) · 908 Bytes
/
file_utils.go
File metadata and controls
34 lines (28 loc) · 908 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package testutils
import (
"os"
"path/filepath"
"testing"
)
// WriteTestFile creates a temporary file with the given content and returns its path.
// The file is automatically cleaned up after the test completes.
func WriteTestFile(t *testing.T, content string) string {
t.Helper()
// create a temporary directory for the file
tempDir, err := os.MkdirTemp("", "testutils-")
if err != nil {
t.Fatalf("failed to create temp directory: %v", err)
}
// register cleanup to remove the temporary directory and its contents
t.Cleanup(func() {
if err := os.RemoveAll(tempDir); err != nil {
t.Logf("failed to remove temporary directory %s: %v", tempDir, err)
}
})
// create a file with a unique name
tempFile := filepath.Join(tempDir, "testfile")
if err := os.WriteFile(tempFile, []byte(content), 0o600); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
return tempFile
}