-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add GetUserHomeDir and WriteTmpFile (#78)
- Loading branch information
Showing
3 changed files
with
97 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package file | ||
|
||
import ( | ||
"os" | ||
"path/filepath" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
const helloWorld = "Hello, World!" | ||
|
||
func TestWriteTmpFile(t *testing.T) { | ||
tests := []struct { | ||
name string | ||
fileName string | ||
content string | ||
wantErr bool | ||
}{ | ||
{ | ||
name: "write to temp file", | ||
fileName: "test.txt", | ||
content: helloWorld, | ||
wantErr: false, | ||
}, | ||
{ | ||
name: "empty file name", | ||
fileName: "", | ||
content: helloWorld, | ||
wantErr: false, | ||
}, | ||
{ | ||
name: "empty file content", | ||
fileName: "test.txt", | ||
content: "", | ||
wantErr: false, | ||
}, | ||
{ | ||
name: "create temp file error", | ||
fileName: filepath.Join(os.TempDir(), "non-existent", "test.txt"), | ||
content: helloWorld, | ||
wantErr: true, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
tmpFile, err := WriteTmpFile(tt.fileName, tt.content) | ||
if tt.wantErr { | ||
assert.Error(t, err) | ||
|
||
return | ||
} | ||
|
||
assert.NoError(t, err) | ||
|
||
defer os.Remove(tmpFile) | ||
|
||
data, err := os.ReadFile(tmpFile) | ||
assert.NoError(t, err) | ||
assert.Equal(t, tt.content, string(data)) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package util | ||
|
||
import "os/user" | ||
|
||
// GetUserHomeDir returns the home directory path for the current user. | ||
// If the current user cannot be determined, it returns the default "/root" path. | ||
func GetUserHomeDir() string { | ||
home := "/root" | ||
|
||
if currentUser, err := user.Current(); err == nil { | ||
home = currentUser.HomeDir | ||
} | ||
|
||
return home | ||
} |