Debian Codegraph @

launcher/internal/systemctl/systemctl_test.go

raw
1 package systemctl
2
3 import (
4 "context"
5 "errors"
6 "testing"
7 )
8
9 func TestRunSystmedCmd(t *testing.T) {
10 doneUnitFunc := func(_ context.Context, _, _ string, progress chan<- string) (int, error) {
11 progress <- "done"
12 return 1, nil
13 }
14 failedCallUnitFunc := func(context.Context, string, string, chan<- string) (int, error) {
15 return 1, errors.New("something went wrong")
16 }
17 failedUnitFunc := func(_ context.Context, _, _ string, progress chan<- string) (int, error) {
18 progress <- "failed"
19 return 1, nil
20 }
21
22 testCases := []struct {
23 name string
24 sytemdCmdFunc func(ctx context.Context, unit string, flag string, progress chan<- string) (int, error)
25 wantErr bool
26 }{
27 {
28 name: "success",
29 sytemdCmdFunc: doneUnitFunc,
30 wantErr: false,
31 },
32 {
33 name: "failed call",
34 sytemdCmdFunc: failedCallUnitFunc,
35 wantErr: true,
36 },
37 {
38 name: "failed unit run",
39 sytemdCmdFunc: failedUnitFunc,
40 wantErr: true,
41 },
42 }
43
44 for _, tc := range testCases {
45 t.Run(tc.name, func(t *testing.T) {
46 if err := runSystemdCmd(tc.sytemdCmdFunc, "test", "test_unit"); (err != nil) != tc.wantErr {
47 t.Errorf("runSystemdCmd() did not return expected error, got error: %v, but wantErr %v", err, tc.wantErr)
48 }
49 })
50 }
51 }
52
53 // TestGetStatus reads the `-.mount` which should exist on all systemd
54 // systems and ensures that one of its properties is valid.
55 func TestGetStatus(t *testing.T) {
56 systemctl, err := New()
57 if err != nil {
58 t.Skipf("Failed to create systemctl client: %v", err)
59 }
60
61 t.Cleanup(systemctl.Close)
62
63 testCases := []struct {
64 name string
65 unit string
66 want string
67 }{
68 {
69 name: "success",
70 unit: "-.mount", //`-.mount` which should exist on all systemd systems,
71 want: "active",
72 },
73 {
74 name: "success with an inactive unit",
75 unit: "node-problem-detector.service",
76 want: "inactive",
77 },
78 }
79
80 for _, tc := range testCases {
81 t.Run(tc.name, func(t *testing.T) {
82 got, err := systemctl.IsActive(context.Background(), tc.unit)
83 if err != nil {
84 t.Fatalf("failed to read status for unit [%s]: %v", tc.unit, got)
85 }
86 if got != tc.want {
87 t.Errorf("GetStatus returned unexpected status for unit [%s], got %s, but want %s", tc.unit, got, tc.want)
88 }
89 })
90 }
91 }