Files
nadir-agent/internal/modules/services/services_test.go
T
2026-06-24 17:29:45 +02:00

61 lines
2.1 KiB
Go

package services
import "testing"
func TestValidateUnit(t *testing.T) {
for _, tt := range []struct {
name string
value string
valid bool
}{
{name: "sshd.service", value: "sshd.service", valid: true},
{name: "template", value: "getty@tty1.service", valid: true},
{name: "dots and colons", value: "foo.bar:baz-1.service", valid: true},
{name: "timer", value: "a_b.timer", valid: true},
{name: "empty", value: "", valid: false},
{name: "flag injection", value: "-rf", valid: false},
{name: "double dash", value: "--now", valid: false},
{name: "space", value: "a b", valid: false},
{name: "shell metachar", value: "foo;rm -rf /", valid: false},
{name: "path sep", value: "a/b", valid: false},
{name: "subshell", value: "naughty$()", valid: false},
{name: "pipe", value: "x|y", valid: false},
} {
t.Run(tt.name, func(t *testing.T) {
err := validateUnit(tt.value)
if tt.valid && err != nil {
t.Errorf("validateUnit(%q) = %v, want nil", tt.value, err)
}
if !tt.valid && err == nil {
t.Errorf("validateUnit(%q) = nil, want error", tt.value)
}
})
}
}
// TestIsSelf pins the dispatch that detaches stop/restart-of-self into a
// Setsid subprocess. Both "nadir" and "nadir.service" must match; anything
// else (including substrings) must not, or unrelated services would also get
// detached and bypass the synchronous error path.
func TestIsSelf(t *testing.T) {
for _, tt := range []struct {
name string
value string
want bool
}{
{name: "bare name", value: "nadir", want: true},
{name: "with service suffix", value: "nadir.service", want: true},
{name: "empty", value: "", want: false},
{name: "other service", value: "sshd.service", want: false},
{name: "prefix substring", value: "nadir-something.service", want: false},
{name: "wrong suffix", value: "nadir.timer", want: false},
{name: "suffix mismatch", value: "not-nadir.service", want: false},
} {
t.Run(tt.name, func(t *testing.T) {
if got := isSelf(tt.value); got != tt.want {
t.Errorf("isSelf(%q) = %v, want %v", tt.value, got, tt.want)
}
})
}
}