I'm trying to write a test for a file reading function. The function accepts directory path & start scanning to categorize files with the sub-directories.
func FileScan(dir string) (map[string][]string, error) {
var dataset = make(map[string][]string)
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
for _, file := range files {
if file.IsDir() {
dirFiles, err := ioutil.ReadDir(fmt.Sprintf("%s/%s", dir, file.Name()))
if err != nil {
return nil, err
}
for _, dirFile := range dirFiles {
if !dirFile.IsDir() {
dataset[file.Name()] = append(dataset[file.Name()], dirFile.Name())
}
}
}
}
return dataset, nil
}
For testing, I created a temporary directory next to the test file & put some sub-directories & files insides them, then start to test the function & call a cleaner function via defer to delete the directory after test.
Is this a good practice?
or maybe it's better to pass an array of []fs.FileInfo instead of directory path, so I can implement a mocked FileInfo in testing.