From 748b14cfe651681ef295717d3bb24244b7e66014 Mon Sep 17 00:00:00 2001 From: Rodolfo Carvalho Date: Fri, 23 Aug 2019 22:55:01 +0200 Subject: [PATCH] Write temporary test files in temp directory Instead of writing to the current working directory, pick a random temp directory to test the CLI commands, keeping the working directory free of test side effects. In some cases the system default temp dir will also have some advantages like being mounted in an in-memory tmpfs. --- cobra/cmd/init_test.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/cobra/cmd/init_test.go b/cobra/cmd/init_test.go index 8ee39106..80cc1516 100644 --- a/cobra/cmd/init_test.go +++ b/cobra/cmd/init_test.go @@ -2,15 +2,15 @@ package cmd import ( "fmt" + "io/ioutil" "os" "path/filepath" "testing" ) func getProject() *Project { - wd, _ := os.Getwd() return &Project{ - AbsolutePath: fmt.Sprintf("%s/testproject", wd), + AbsolutePath: fmt.Sprintf("%s/testproject", mustTempDir()), Legal: getLicense(), Copyright: copyrightLine(), AppName: "testproject", @@ -19,6 +19,14 @@ func getProject() *Project { } } +func mustTempDir() string { + dir, err := ioutil.TempDir("", "cobra_cli_test_") + if err != nil { + panic(err) + } + return dir +} + func TestGoldenInitCmd(t *testing.T) { project := getProject() defer os.RemoveAll(project.AbsolutePath)