Skip to content

Commit 7147b31

Browse files
committed
add a simple test
1 parent edfa9ba commit 7147b31

File tree

2 files changed

+51
-22
lines changed

2 files changed

+51
-22
lines changed

cli-files/go-ls/cmd/root.go

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,32 +7,36 @@ import (
77
"github.com/spf13/cobra"
88
)
99

10-
var rootCmd = &cobra.Command{
11-
Use: "go-ls",
12-
Short: "go-ls is a re-implementation of the ls command",
13-
RunE: func(cmd *cobra.Command, args []string) error {
14-
// By default, ls the current directory
15-
dir := "."
16-
// If an argument was passed, use the first as our directory
17-
if len(args) > 0 {
18-
dir = args[0]
19-
}
10+
func NewRoodCmd() *cobra.Command {
11+
return &cobra.Command{
12+
Use: "go-ls",
13+
Short: "go-ls is a re-implementation of the ls command",
14+
Args: cobra.ArbitraryArgs,
15+
RunE: func(cmd *cobra.Command, args []string) error {
16+
// By default, ls the current directory
17+
dir := "."
18+
// If an argument was passed, use the first as our directory
19+
if len(args) > 0 {
20+
dir = args[0]
21+
}
2022

21-
// Read this directory to get a list of files
22-
// https://pkg.go.dev/os#ReadDir
23-
files, err := os.ReadDir(dir)
24-
if err != nil {
25-
return err
26-
}
27-
// Iterate through each file in the directory, printing the file name
28-
for _, file := range files {
29-
fmt.Println(file.Name())
30-
}
31-
return nil
32-
},
23+
// Read this directory to get a list of files
24+
// https://pkg.go.dev/os#ReadDir
25+
files, err := os.ReadDir(dir)
26+
if err != nil {
27+
return err
28+
}
29+
// Iterate through each file in the directory, printing the file name
30+
for _, file := range files {
31+
fmt.Fprintln(cmd.OutOrStdout(), file.Name())
32+
}
33+
return nil
34+
},
35+
}
3336
}
3437

3538
func Execute() {
39+
rootCmd := NewRoodCmd()
3640
if err := rootCmd.Execute(); err != nil {
3741
fmt.Fprintln(os.Stderr, err)
3842
os.Exit(1)

cli-files/go-ls/cmd/root_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package cmd
2+
3+
import (
4+
"bytes"
5+
"io/ioutil"
6+
"testing"
7+
)
8+
9+
func TestRootCmd(t *testing.T) {
10+
cmd := NewRoodCmd()
11+
b := bytes.NewBufferString("")
12+
cmd.SetOut(b)
13+
cmd.SetArgs([]string{})
14+
cmd.Execute()
15+
out, err := ioutil.ReadAll(b)
16+
if err != nil {
17+
t.Fatal(err)
18+
}
19+
expected := `root.go
20+
root_test.go
21+
`
22+
if string(out) != expected {
23+
t.Fatalf("expected \"%s\" got \"%s\"", expected, string(out))
24+
}
25+
}

0 commit comments

Comments
 (0)