process_test.go 839 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package process
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "runtime"
  7. "testing"
  8. )
  9. func TestAlive(t *testing.T) {
  10. for _, pid := range []int{0, -1, -123} {
  11. t.Run(fmt.Sprintf("invalid process (%d)", pid), func(t *testing.T) {
  12. if Alive(pid) {
  13. t.Errorf("PID %d should not be alive", pid)
  14. }
  15. })
  16. }
  17. t.Run("current process", func(t *testing.T) {
  18. if pid := os.Getpid(); !Alive(pid) {
  19. t.Errorf("current PID (%d) should be alive", pid)
  20. }
  21. })
  22. t.Run("exited process", func(t *testing.T) {
  23. if runtime.GOOS == "windows" {
  24. t.Skip("TODO: make this work on Windows")
  25. }
  26. // Get a PID of an exited process.
  27. cmd := exec.Command("echo", "hello world")
  28. err := cmd.Run()
  29. if err != nil {
  30. t.Fatal(err)
  31. }
  32. exitedPID := cmd.ProcessState.Pid()
  33. if Alive(exitedPID) {
  34. t.Errorf("PID %d should not be alive", exitedPID)
  35. }
  36. })
  37. }