Skip to content

Commit

Permalink
gfile
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Jan 8, 2024
1 parent 6fb1d48 commit 84c67e5
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions util/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,19 @@ func Bytes(file string) (d []byte) {
return
}

// Content returns the contents of file,
// if read fail, returns "".
func Content(file string) (d string) {
return string(Bytes(file))
}

// Write writes []byte to file.
func Write(file string, data []byte, append bool) (err error) {
mode := os.O_CREATE | os.O_WRONLY
if append {
mode |= os.O_APPEND
} else {
mode |= os.O_TRUNC
}
f, err := os.OpenFile(file, mode, 0755)
if err != nil {
Expand Down
34 changes: 34 additions & 0 deletions util/file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,37 @@ func TestCopyFile(t *testing.T) {
t.Logf("Expected error: %v", err)
}
}

func TestContent(t *testing.T) {
// Create a temporary file for testing
content := "This is a test file content."
tmpFile, err := ioutil.TempFile("", "testfile.txt")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())

// Write content to the temporary file
_, err = tmpFile.WriteString(content)
if err != nil {
t.Fatal(err)
}
tmpFile.Close()

// Run the Content function with the temporary file
result := Content(tmpFile.Name())

// Check if the result matches the expected content
if result != content {
t.Errorf("Content(%s) = %s, want %s", tmpFile.Name(), result, content)
}

// Test case for a non-existing file
nonExistentFile := "nonexistentfile.txt"
result = Content(nonExistentFile)

// Check if the result is an empty string for a non-existing file
if result != "" {
t.Errorf("Content(%s) = %s, want %s", nonExistentFile, result, "")
}
}

0 comments on commit 84c67e5

Please sign in to comment.