1package cmd 2 3import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "testing" 9 10 "github.com/spf13/viper" 11) 12 13func getProject() *Project { 14 wd, _ := os.Getwd() 15 return &Project{ 16 AbsolutePath: fmt.Sprintf("%s/testproject", wd), 17 Legal: getLicense(), 18 Copyright: copyrightLine(), 19 AppName: "testproject", 20 PkgName: "github.com/spf13/testproject", 21 Viper: true, 22 } 23} 24 25func TestGoldenInitCmd(t *testing.T) { 26 27 dir, err := ioutil.TempDir("", "cobra-init") 28 if err != nil { 29 t.Fatal(err) 30 } 31 defer os.RemoveAll(dir) 32 33 tests := []struct { 34 name string 35 args []string 36 pkgName string 37 expectErr bool 38 }{ 39 { 40 name: "successfully creates a project with name", 41 args: []string{"testproject"}, 42 pkgName: "github.com/spf13/testproject", 43 expectErr: false, 44 }, 45 { 46 name: "returns error when passing an absolute path for project", 47 args: []string{dir}, 48 pkgName: "github.com/spf13/testproject", 49 expectErr: true, 50 }, 51 { 52 name: "returns error when passing an relative path for project", 53 args: []string{"github.com/spf13/testproject"}, 54 pkgName: "github.com/spf13/testproject", 55 expectErr: true, 56 }, 57 } 58 59 for _, tt := range tests { 60 t.Run(tt.name, func(t *testing.T) { 61 62 initCmd.Flags().Set("pkg-name", tt.pkgName) 63 viper.Set("useViper", true) 64 projectPath, err := initializeProject(tt.args) 65 defer func() { 66 if projectPath != "" { 67 os.RemoveAll(projectPath) 68 } 69 }() 70 71 if !tt.expectErr && err != nil { 72 t.Fatalf("did not expect an error, got %s", err) 73 } 74 if tt.expectErr { 75 if err == nil { 76 t.Fatal("expected an error but got none") 77 } else { 78 // got an expected error nothing more to do 79 return 80 } 81 } 82 83 expectedFiles := []string{"LICENSE", "main.go", "cmd/root.go"} 84 for _, f := range expectedFiles { 85 generatedFile := fmt.Sprintf("%s/%s", projectPath, f) 86 goldenFile := fmt.Sprintf("testdata/%s.golden", filepath.Base(f)) 87 err := compareFiles(generatedFile, goldenFile) 88 if err != nil { 89 t.Fatal(err) 90 } 91 } 92 }) 93 } 94} 95