Skip to content

Commit

Permalink
write temporary test files in temp directory (spf13#937)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
rhcarvalho authored and umarcor committed Jan 22, 2020
1 parent cafc355 commit f8a2118
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions cobra/cmd/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)
Expand Down

0 comments on commit f8a2118

Please sign in to comment.