Passed
Pull Request — master (#73)
by Stefano
02:12
created

cmd_test.TestRootCommand   A

Complexity

Conditions 1

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 11
dl 0
loc 15
rs 9.85
c 0
b 0
f 0
nop 1
1
package cmd_test
2
3
import (
4
	"bytes"
5
	"os"
6
	"strings"
7
	"testing"
8
9
	"github.com/pkg/errors"
10
	"github.com/sirupsen/logrus"
11
	"github.com/spf13/cobra"
12
	"github.com/stefanoj3/dirstalk/pkg/cmd"
13
	"github.com/stefanoj3/dirstalk/pkg/common/test"
14
	"github.com/stretchr/testify/assert"
15
)
16
17
func TestRootCommand(t *testing.T) {
18
	logger, _ := test.NewLogger()
19
20
	c, err := createCommand(logger)
21
	assert.NoError(t, err)
22
	assert.NotNil(t, c)
23
24
	_, out, err := executeCommand(c)
25
	assert.NoError(t, err)
26
27
	// ensure the summary is printed
28
	assert.Contains(t, out, "dirstalk is a tool that attempts")
29
	assert.Contains(t, out, "Usage")
30
	assert.Contains(t, out, "dictionary.generate")
31
	assert.Contains(t, out, "scan")
32
}
33
34
func TestVersionCommand(t *testing.T) {
35
	logger, buf := test.NewLogger()
36
37
	c, err := createCommand(logger)
38
	assert.NoError(t, err)
39
	assert.NotNil(t, c)
40
41
	_, _, err = executeCommand(c, "version")
42
	assert.NoError(t, err)
43
44
	// Ensure the command ran and produced some of the expected output
45
	// it is not in the scope of this test to ensure the correct output
46
	assert.Contains(t, buf.String(), "Version: ")
47
}
48
49
func executeCommand(root *cobra.Command, args ...string) (c *cobra.Command, output string, err error) {
50
	buf := new(bytes.Buffer)
51
	root.SetOut(buf)
52
53
	a := []string{""}
54
	os.Args = append(a, args...) //nolint
55
56
	c, err = root.ExecuteC()
57
58
	return c, buf.String(), err
59
}
60
61
func removeTestFile(path string) {
62
	if !strings.Contains(path, "testdata") {
63
		return
64
	}
65
66
	_ = os.Remove(path)
67
}
68
69
func createCommand(logger *logrus.Logger) (*cobra.Command, error) {
70
	dirStalkCmd, err := cmd.NewRootCommand(logger)
71
	if err != nil {
72
		return nil, err
73
	}
74
75
	scanCmd, err := cmd.NewScanCommand(logger)
76
	if err != nil {
77
		return nil, errors.Wrap(err, "failed to create scan command")
78
	}
79
80
	resultViewCommand, err := cmd.NewResultViewCommand(logger.Out)
81
	if err != nil {
82
		return nil, errors.Wrap(err, "failed to create result.view command")
83
	}
84
85
	resultDiffCommand, err := cmd.NewResultDiffCommand(logger.Out)
86
	if err != nil {
87
		return nil, errors.Wrap(err, "failed to create result.diff command")
88
	}
89
90
	dirStalkCmd.AddCommand(scanCmd)
91
	dirStalkCmd.AddCommand(resultViewCommand)
92
	dirStalkCmd.AddCommand(resultDiffCommand)
93
	dirStalkCmd.AddCommand(cmd.NewGenerateDictionaryCommand(logger.Out))
94
	dirStalkCmd.AddCommand(cmd.NewVersionCommand(logger.Out))
95
96
	return dirStalkCmd, nil
97
}
98