ruspa/dir_utils_test.go

96 lines
2.1 KiB
Go
Raw Normal View History

2020-03-01 23:09:00 +01:00
package main
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
)
var subdirs = map[string][]string{"sub1": []string{"s1s1", "s1s2", "s1s3"}, "sub2": []string{"s2s1", "s2s2"}, "sub3": []string{}}
var dirWithSubdirs string
var dirWithoutSubdirs string
func mkchild(root, dir string) (string, error) {
childPath := filepath.Join(root, dir)
var mode os.FileMode = 2_148_532_735 // means "dtrwxrwxrwx"
err := os.Mkdir(childPath, mode)
return childPath, err
}
func createTestDirs() string {
root, err := ioutil.TempDir("", "ruspa_*")
if err != nil {
panic(err)
}
for dirName, subdirList := range subdirs {
dir, err := mkchild(root, dirName)
if err != nil {
panic(err)
}
for _, subdir := range subdirList {
if _, err = mkchild(dir, subdir); err != nil {
panic(err)
}
}
}
return root
}
func removeTestDirs(root string) {
for dirName, subdirList := range subdirs {
dirPath := filepath.Join(root, dirName)
for _, subdir := range subdirList {
subdirPath := filepath.Join(dirPath, subdir)
if err := os.Remove(subdirPath); err != nil {
panic(err)
}
}
err := os.Remove(dirPath)
if err != nil {
panic(err)
}
}
if err := os.Remove(root); err != nil {
panic(err)
}
}
func TestListDir(t *testing.T) {
root := createTestDirs()
defer removeTestDirs(root)
dirs, err := ListDir(root)
if err != nil {
t.Error(err)
}
for _, dir := range dirs {
if _, ok := subdirs[dir.Name()]; !ok {
t.Errorf("missing %s in %s\n", dir, dirs)
}
}
shouldBeEmpty, err := ListDir(filepath.Join(root, "sub3"))
if err != nil {
panic(err)
}
if len(shouldBeEmpty) != 0 {
t.Error("ListDir of sub3 should be empty")
}
}
func TestAnyDirectoryDownThere(t *testing.T) {
root := createTestDirs()
defer removeTestDirs(root)
pathNotEmpty := filepath.Join(root, "sub1")
if !AnyDirectoryDownThere(pathNotEmpty) {
list, _ := ListDir(pathNotEmpty)
t.Logf("%s -> %s\n", pathNotEmpty, list)
t.Error("sub1 is empty, but should be")
}
pathEmpty := filepath.Join(root, "sub3")
if AnyDirectoryDownThere(pathEmpty) {
list, _ := ListDir(pathEmpty)
t.Logf("%s -> %s\n", pathEmpty, list)
t.Error("sub3 is NOT empty, but it should be")
}
}