package service import ( "context" "os" "path/filepath" "testing" ) // fakeSystemctl installs a fake systemctl on PATH and returns the path to its // directory. func fakeSystemctl(t *testing.T, script string) string { t.Helper() dir := t.TempDir() path := filepath.Join(dir, "systemctl") if err := os.WriteFile(path, []byte("#!/bin/sh\n"+script), 0o755); err != nil { t.Fatal(err) } t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) return path } func TestRestartSuccess(t *testing.T) { fakeSystemctl(t, "exit 0\n") if err := New("galahad2lcd").Restart(context.Background()); err != nil { t.Fatalf("Restart error = %v", err) } } func TestRestartFailure(t *testing.T) { fakeSystemctl(t, "echo 'permission denied' >&2; exit 1\n") err := New("galahad2lcd").Restart(context.Background()) if err == nil { t.Fatal("Restart returned nil error, want failure") } } func TestRestartCancellation(t *testing.T) { fakeSystemctl(t, "sleep 5\n") ctx, cancel := context.WithCancel(context.Background()) cancel() err := New("galahad2lcd").Restart(ctx) if err == nil { t.Fatal("Restart returned nil error for cancelled context") } } // Ensure the default constructor wires up the real exec.CommandContext. func TestNewDefaultRunCmd(t *testing.T) { s := New("x") if s.runCmd == nil { t.Fatal("runCmd not initialised") } cmd := s.runCmd(context.Background(), "true") if cmd == nil { t.Fatal("runCmd returned nil command") } }