spf13--cobra/cobra/cmd/init_test.go
Rodolfo Carvalho 748b14cfe6 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.
2020-01-22 01:01:23 +01:00

47 lines
977 B
Go

package cmd
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func getProject() *Project {
return &Project{
AbsolutePath: fmt.Sprintf("%s/testproject", mustTempDir()),
Legal: getLicense(),
Copyright: copyrightLine(),
AppName: "testproject",
PkgName: "github.com/spf13/testproject",
Viper: true,
}
}
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)
if err := project.Create(); err != nil {
t.Fatal(err)
}
expectedFiles := []string{"LICENSE", "main.go", "cmd/root.go"}
for _, f := range expectedFiles {
generatedFile := fmt.Sprintf("%s/%s", project.AbsolutePath, f)
goldenFile := fmt.Sprintf("testdata/%s.golden", filepath.Base(f))
err := compareFiles(generatedFile, goldenFile)
if err != nil {
t.Fatal(err)
}
}
}