Skip to content

Commit 7ed7e1c

Browse files
committed
systemd: implement 'Stop()' function
Implement and test the 'Stop()' function for 'systemd'-managed daemon processes. If the service is already stopped or doesn't exist, this function is a no-op. Signed-off-by: Victoria Dye <[email protected]>
1 parent 66c1411 commit 7ed7e1c

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

internal/daemon/systemd.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,5 +96,15 @@ func (s *systemd) Start(label string) error {
9696
}
9797

9898
func (s *systemd) Stop(label string) error {
99-
return fmt.Errorf("not implemented")
99+
// TODO: warn user if already stopped
100+
exitCode, err := s.cmdExec.Run("systemctl", "--user", "stop", label)
101+
if err != nil {
102+
return err
103+
}
104+
105+
if exitCode != 0 {
106+
return fmt.Errorf("'systemctl stop' exited with status %d", exitCode)
107+
}
108+
109+
return nil
100110
}

internal/daemon/systemd_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,45 @@ func TestSystemd_Start(t *testing.T) {
204204
mock.AssertExpectationsForObjects(t, testCommandExecutor)
205205
})
206206
}
207+
208+
func TestSystemd_Stop(t *testing.T) {
209+
// Set up mocks
210+
testUser := &user.User{
211+
Uid: "123",
212+
Username: "testuser",
213+
HomeDir: "/my/test/dir",
214+
}
215+
testUserProvider := &mockUserProvider{}
216+
testUserProvider.On("CurrentUser").Return(testUser, nil)
217+
218+
testCommandExecutor := &mockCommandExecutor{}
219+
220+
systemd := daemon.NewSystemdProvider(testUserProvider, testCommandExecutor, nil)
221+
222+
// Test #1: systemctl succeeds
223+
t.Run("Calls correct systemctl command", func(t *testing.T) {
224+
testCommandExecutor.On("Run",
225+
"systemctl",
226+
[]string{"--user", "stop", basicDaemonConfig.Label},
227+
).Return(0, nil).Once()
228+
229+
err := systemd.Stop(basicDaemonConfig.Label)
230+
assert.Nil(t, err)
231+
mock.AssertExpectationsForObjects(t, testCommandExecutor)
232+
})
233+
234+
// Reset the mock structure between tests
235+
testCommandExecutor.Mock = mock.Mock{}
236+
237+
// Test #2: systemctl fails with uncaught error
238+
t.Run("Returns error when systemctl fails", func(t *testing.T) {
239+
testCommandExecutor.On("Run",
240+
mock.AnythingOfType("string"),
241+
mock.AnythingOfType("[]string"),
242+
).Return(1, nil).Once()
243+
244+
err := systemd.Stop(basicDaemonConfig.Label)
245+
assert.NotNil(t, err)
246+
mock.AssertExpectationsForObjects(t, testCommandExecutor)
247+
})
248+
}

0 commit comments

Comments
 (0)