10 "github.com/spf13/viper"
13 // TestGoldenAddCmd initializes the project "github.com/spf13/testproject"
14 // in GOPATH, adds "test" command
15 // and compares the content of all files in cmd directory of testproject
16 // with appropriate golden files.
17 // Use -update to update existing golden files.
18 func TestGoldenAddCmd(t *testing.T) {
19 projectName := "github.com/spf13/testproject"
20 project := NewProject(projectName)
21 defer os.RemoveAll(project.AbsPath())
23 viper.Set("author", "NAME HERE <EMAIL ADDRESS>")
24 viper.Set("license", "apache")
25 viper.Set("year", 2017)
26 defer viper.Set("author", nil)
27 defer viper.Set("license", nil)
28 defer viper.Set("year", nil)
30 // Initialize the project first.
31 initializeProject(project)
33 // Then add the "test" command.
35 cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
36 createCmdFile(project.License(), cmdPath, cmdName)
38 expectedFiles := []string{".", "root.go", "test.go"}
39 gotFiles := []string{}
41 // Check project file hierarchy and compare the content of every single file
42 // with appropriate golden file.
43 err := filepath.Walk(project.CmdPath(), func(path string, info os.FileInfo, err error) error {
48 // Make path relative to project.CmdPath().
49 // E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
50 // then it returns just "root.go".
51 relPath, err := filepath.Rel(project.CmdPath(), path)
55 relPath = filepath.ToSlash(relPath)
56 gotFiles = append(gotFiles, relPath)
57 goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
64 case "root.go", "test.go":
66 got, err := ioutil.ReadFile(path)
70 ioutil.WriteFile(goldenPath, got, 0644)
72 return compareFiles(path, goldenPath)
75 return errors.New("unknown file: " + path)
81 // Check if some files lack.
82 if err := checkLackFiles(expectedFiles, gotFiles); err != nil {
87 func TestValidateCmdName(t *testing.T) {
88 testCases := []struct {
92 {"cmdName", "cmdName"},
93 {"cmd_name", "cmdName"},
94 {"cmd-name", "cmdName"},
95 {"cmd______Name", "cmdName"},
96 {"cmd------Name", "cmdName"},
97 {"cmd______name", "cmdName"},
98 {"cmd------name", "cmdName"},
99 {"cmdName-----", "cmdName"},
100 {"cmdname-", "cmdname"},
103 for _, testCase := range testCases {
104 got := validateCmdName(testCase.input)
105 if testCase.expected != got {
106 t.Errorf("Expected %q, got %q", testCase.expected, got)