package daemon import ( "errors" "os" "os/signal" "path/filepath" "strconv" "strings" "syscall" "testing" "time" ) // selfComm points the pid check at the test binary, so the check itself runs // for real instead of being stubbed out. func selfComm(t *testing.T) { t.Helper() raw, err := os.ReadFile("/proc/self/comm") if err != nil { t.Skip("no /proc: pid verification cannot be exercised here") } old := daemonComm daemonComm = strings.TrimSpace(string(raw)) t.Cleanup(func() { daemonComm = old }) } func runtimeDir(t *testing.T) string { t.Helper() dir := t.TempDir() t.Setenv("XDG_RUNTIME_DIR", dir) return dir } func TestRefreshSignalsTheRecordedProcess(t *testing.T) { runtimeDir(t) selfComm(t) remove, err := WritePID() if err != nil { t.Fatalf("WritePID: %v", err) } // The signal has to reach this very process: SIGUSR1 is ignored by // default in Go, so a test that only checks for no error would pass even // if the pid were wrong. got := make(chan os.Signal, 1) signal.Notify(got, syscall.SIGUSR1) defer signal.Stop(got) if err := Refresh(); err != nil { t.Fatalf("Refresh: %v", err) } select { case <-got: case <-time.After(2 * time.Second): t.Fatal("SIGUSR1 never arrived") } remove() if err := Refresh(); !errors.Is(err, ErrNotRunning) { t.Fatalf("after the pidfile is gone: got %v, want ErrNotRunning", err) } } func TestRefreshRefusesAStalePID(t *testing.T) { dir := runtimeDir(t) selfComm(t) // A pid that is either free or belongs to something that is not dipstick: // either way the refresh must not signal it. path := filepath.Join(dir, "dipstick", "daemon.pid") if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(path, []byte(strconv.Itoa(1)+"\n"), 0o644); err != nil { t.Fatal(err) } if err := Refresh(); !errors.Is(err, ErrNotRunning) { t.Fatalf("stale pid: got %v, want ErrNotRunning", err) } } func TestRefreshRejectsGarbage(t *testing.T) { dir := runtimeDir(t) path := filepath.Join(dir, "dipstick", "daemon.pid") if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(path, []byte("not a pid\n"), 0o644); err != nil { t.Fatal(err) } if err := Refresh(); !errors.Is(err, ErrNotRunning) { t.Fatalf("garbage pidfile: got %v, want ErrNotRunning", err) } }