|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "os" |
| 6 | + "testing" |
| 7 | + |
| 8 | + fakeruntime "github.com/linuxsuren/go-fake-runtime" |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | +) |
| 11 | + |
| 12 | +func TestService(t *testing.T) { |
| 13 | + root := NewRootCmd(fakeruntime.FakeExecer{ExpectOS: "linux"}) |
| 14 | + root.SetArgs([]string{"service", "fake"}) |
| 15 | + err := root.Execute() |
| 16 | + assert.NotNil(t, err) |
| 17 | + |
| 18 | + notLinux := NewRootCmd(fakeruntime.FakeExecer{ExpectOS: "fake"}) |
| 19 | + notLinux.SetArgs([]string{"service", "--action", "install"}) |
| 20 | + err = notLinux.Execute() |
| 21 | + assert.NotNil(t, err) |
| 22 | + |
| 23 | + tmpFile, err := os.CreateTemp(os.TempDir(), "service") |
| 24 | + assert.Nil(t, err) |
| 25 | + defer func() { |
| 26 | + os.RemoveAll(tmpFile.Name()) |
| 27 | + }() |
| 28 | + |
| 29 | + targetScript := NewRootCmd(fakeruntime.FakeExecer{ExpectOS: "linux"}) |
| 30 | + targetScript.SetArgs([]string{"service", "--action", "install", "--script-path", tmpFile.Name()}) |
| 31 | + err = targetScript.Execute() |
| 32 | + assert.Nil(t, err) |
| 33 | + data, err := os.ReadFile(tmpFile.Name()) |
| 34 | + assert.Nil(t, err) |
| 35 | + assert.Equal(t, script, string(data)) |
| 36 | + |
| 37 | + tests := []struct { |
| 38 | + name string |
| 39 | + action string |
| 40 | + expectOutput string |
| 41 | + }{{ |
| 42 | + name: "action: start", |
| 43 | + action: "start", |
| 44 | + expectOutput: "output1", |
| 45 | + }, { |
| 46 | + name: "action: stop", |
| 47 | + action: "stop", |
| 48 | + expectOutput: "output2", |
| 49 | + }, { |
| 50 | + name: "action: restart", |
| 51 | + action: "restart", |
| 52 | + expectOutput: "output3", |
| 53 | + }, { |
| 54 | + name: "action: status", |
| 55 | + action: "status", |
| 56 | + expectOutput: "output4", |
| 57 | + }} |
| 58 | + for _, tt := range tests { |
| 59 | + t.Run(tt.name, func(t *testing.T) { |
| 60 | + buf := new(bytes.Buffer) |
| 61 | + normalRoot := NewRootCmd(fakeruntime.FakeExecer{ExpectOS: "linux", ExpectOutput: tt.expectOutput}) |
| 62 | + normalRoot.SetOut(buf) |
| 63 | + normalRoot.SetArgs([]string{"service", "--action", tt.action}) |
| 64 | + err = normalRoot.Execute() |
| 65 | + assert.Nil(t, err) |
| 66 | + assert.Equal(t, tt.expectOutput+"\n", buf.String()) |
| 67 | + }) |
| 68 | + } |
| 69 | +} |
0 commit comments