0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-11-23 06:40:40 +00:00

fix: fix IsDirEmpty and add tests (#76)

This commit is contained in:
Robert Kaussow 2024-05-05 16:53:03 +02:00 committed by GitHub
parent 211b38e908
commit d2c3493d68
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 72 additions and 3 deletions

View File

@ -32,8 +32,8 @@ func IsDir(path string) (bool, error) {
return false, err return false, err
} }
// IsDirEmpty returns whether the given directory path is empty. // IsDirEmpty checks if the directory at the given path is empty.
// If the path does not exist or is not a directory, it returns (false, err). // It returns true if the directory is empty, false if not empty, or an error if there was a problem checking it.
func IsDirEmpty(path string) (bool, error) { func IsDirEmpty(path string) (bool, error) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
@ -43,7 +43,7 @@ func IsDirEmpty(path string) (bool, error) {
_, err = f.Readdir(1) _, err = f.Readdir(1)
if err == nil { if err == nil {
return true, nil return false, nil
} }
if errors.Is(err, io.EOF) { if errors.Is(err, io.EOF) {

69
file/dir_test.go Normal file
View File

@ -0,0 +1,69 @@
package file
import (
"errors"
"io/fs"
"os"
"path/filepath"
"testing"
)
func TestIsDirEmpty(t *testing.T) {
t.Run("empty directory", func(t *testing.T) {
dir, err := os.MkdirTemp("", "test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(dir)
isEmpty, err := IsDirEmpty(dir)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !isEmpty {
t.Error("expected directory to be empty")
}
})
t.Run("non-empty directory", func(t *testing.T) {
dir, err := os.MkdirTemp("", "test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(dir)
file, err := os.CreateTemp(dir, "test")
if err != nil {
t.Fatalf("failed to create temp file: %v", err)
}
file.Close()
isEmpty, err := IsDirEmpty(dir)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if isEmpty {
t.Error("expected directory to be non-empty")
}
})
t.Run("non-existent directory", func(t *testing.T) {
dir := filepath.Join(os.TempDir(), "non-existent")
isEmpty, err := IsDirEmpty(dir)
if err == nil {
t.Error("expected an error for non-existent directory")
}
if isEmpty {
t.Error("expected directory to be non-empty")
}
if !errors.Is(err, fs.ErrNotExist) {
t.Errorf("unexpected error: %v", err)
}
})
}