summaryrefslogtreecommitdiff
path: root/internal/cli/root_test.go
blob: 28e7d237b72abf748db244d4bbf5b5f5a94c3415 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package cli_test

import (
	"testing"

	"github.com/roadrunner-server/roadrunner/v2/internal/cli"

	"github.com/spf13/cobra"
	"github.com/stretchr/testify/assert"
)

func TestCommandSubcommands(t *testing.T) {
	cmd := cli.NewCommand("unit test")

	cases := []struct {
		giveName string
	}{
		{giveName: "workers"},
		{giveName: "reset"},
		{giveName: "serve"},
	}

	// get all existing subcommands and put into the map
	subcommands := make(map[string]*cobra.Command)
	for _, sub := range cmd.Commands() {
		subcommands[sub.Name()] = sub
	}

	for _, tt := range cases {
		tt := tt
		t.Run(tt.giveName, func(t *testing.T) {
			if _, exists := subcommands[tt.giveName]; !exists {
				assert.Failf(t, "command not found", "command [%s] was not found", tt.giveName)
			}
		})
	}
}

func TestCommandFlags(t *testing.T) {
	cmd := cli.NewCommand("unit test")

	cases := []struct {
		giveName      string
		wantShorthand string
		wantDefault   string
	}{
		{giveName: "config", wantShorthand: "c", wantDefault: ".rr.yaml"},
		{giveName: "WorkDir", wantShorthand: "w", wantDefault: ""},
		{giveName: "dotenv", wantShorthand: "", wantDefault: ""},
		{giveName: "debug", wantShorthand: "d", wantDefault: "false"},
		{giveName: "override", wantShorthand: "o", wantDefault: "[]"},
	}

	for _, tt := range cases {
		tt := tt
		t.Run(tt.giveName, func(t *testing.T) {
			flag := cmd.Flag(tt.giveName)

			if flag == nil {
				assert.Failf(t, "flag not found", "flag [%s] was not found", tt.giveName)

				return
			}

			assert.Equal(t, tt.wantShorthand, flag.Shorthand)
			assert.Equal(t, tt.wantDefault, flag.DefValue)
		})
	}
}

func TestCommandSimpleExecuting(t *testing.T) {
	cmd := cli.NewCommand("unit test")
	cmd.SetArgs([]string{"-c", "./../../.rr.yaml"})

	var executed bool

	if cmd.Run == nil { // override "Run" property for test (if it was not set)
		cmd.Run = func(cmd *cobra.Command, args []string) {
			executed = true
		}
	}

	assert.NoError(t, cmd.Execute())
	assert.True(t, executed)
}