10 "github.com/spf13/viper"
13 // TestGoldenInitCmd initializes the project "github.com/spf13/testproject"
14 // in GOPATH and compares the content of files in initialized project with
15 // appropriate golden files ("testdata/*.golden").
16 // Use -update to update existing golden files.
17 func TestGoldenInitCmd(t *testing.T) {
18 projectName := "github.com/spf13/testproject"
19 project := NewProject(projectName)
20 defer os.RemoveAll(project.AbsPath())
22 viper.Set("author", "NAME HERE <EMAIL ADDRESS>")
23 viper.Set("license", "apache")
24 viper.Set("year", 2017)
25 defer viper.Set("author", nil)
26 defer viper.Set("license", nil)
27 defer viper.Set("year", nil)
29 os.Args = []string{"cobra", "init", projectName}
30 if err := rootCmd.Execute(); err != nil {
31 t.Fatal("Error by execution:", err)
34 expectedFiles := []string{".", "cmd", "LICENSE", "main.go", "cmd/root.go"}
35 gotFiles := []string{}
37 // Check project file hierarchy and compare the content of every single file
38 // with appropriate golden file.
39 err := filepath.Walk(project.AbsPath(), func(path string, info os.FileInfo, err error) error {
44 // Make path relative to project.AbsPath().
45 // E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
46 // then it returns just "cmd/root.go".
47 relPath, err := filepath.Rel(project.AbsPath(), path)
51 relPath = filepath.ToSlash(relPath)
52 gotFiles = append(gotFiles, relPath)
53 goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
60 case "LICENSE", "main.go", "cmd/root.go":
62 got, err := ioutil.ReadFile(path)
66 if err := ioutil.WriteFile(goldenPath, got, 0644); err != nil {
67 t.Fatal("Error while updating file:", err)
70 return compareFiles(path, goldenPath)
73 return errors.New("unknown file: " + path)
79 // Check if some files lack.
80 if err := checkLackFiles(expectedFiles, gotFiles); err != nil {