Files
atlantis/testing/temp_files.go
Eng Zer Jun 49c5eba458 test: use T.TempDir to create temporary test directory (#2671)
This commit replaces `os.MkdirTemp` with `t.TempDir` in tests. The
directory created by `t.TempDir` is automatically removed when the test
and all its subtests complete.

Prior to this commit, temporary directory created using `os.MkdirTemp`
needs to be removed manually by calling `os.RemoveAll`, which is omitted
in some tests. The error handling boilerplate e.g.
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Fatal(err)
		}
	}
is also tedious, but `t.TempDir` handles this for us nicely.

Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2022-11-13 14:13:29 -06:00

59 lines
1.7 KiB
Go

package testing
import (
"os"
"path/filepath"
"testing"
)
// DirStructure creates a directory structure in a temporary directory.
// structure describes the dir structure. If the value is another map, then the
// key is the name of a directory. If the value is nil, then the key is the name
// of a file. If val is a string then key is a file name and val is the file's content.
// It returns the path to the temp directory containing the defined
// structure.
// Example usage:
//
// versionConfig := `
// terraform {
// required_version = "= 0.12.8"
// }
// `
// tmpDir := DirStructure(t, map[string]interface{}{
// "pulldir": map[string]interface{}{
// "project1": map[string]interface{}{
// "main.tf": nil,
// },
// "project2": map[string]interface{}{,
// "main.tf": versionConfig,
// },
// },
// })
func DirStructure(t *testing.T, structure map[string]interface{}) string {
tmpDir := t.TempDir()
dirStructureGo(t, tmpDir, structure)
return tmpDir
}
func dirStructureGo(t *testing.T, parentDir string, structure map[string]interface{}) {
for key, val := range structure {
// If val is nil then key is a filename and we just create it
if val == nil {
_, err := os.Create(filepath.Join(parentDir, key))
Ok(t, err)
continue
}
// If val is another map then key is a dir
if dirContents, ok := val.(map[string]interface{}); ok {
subDir := filepath.Join(parentDir, key)
Ok(t, os.Mkdir(subDir, 0700))
// Recurse and create contents.
dirStructureGo(t, subDir, dirContents)
} else if fileContent, ok := val.(string); ok {
// If val is a string then key is a file name and val is the file's content
err := os.WriteFile(filepath.Join(parentDir, key), []byte(fileContent), 0600)
Ok(t, err)
}
}
}