| 1 | package keepawake |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "regexp" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | func TestMacNativePowerRequest(t *testing.T) { |
| 15 | ctx, cancel := context.WithCancel(context.Background()) |
| 16 | defer cancel() |
| 17 | ready := make(chan struct{}) |
| 18 | done := make(chan error, 1) |
| 19 | go func() { done <- hold(ctx, func() { close(ready) }) }() |
| 20 | select { |
| 21 | case <-ready: |
| 22 | case err := <-done: |
| 23 | t.Fatal("power request failed", err) |
| 24 | case <-time.After(6 * time.Second): |
| 25 | t.Fatal("power request did not start") |
| 26 | } |
| 27 | owned := func(pid int) bool { |
| 28 | for i := 0; i < 8 && pid > 1; i++ { |
| 29 | if pid == os.Getpid() { |
| 30 | return true |
| 31 | } |
| 32 | value, err := exec.Command("/bin/ps", "-o", "ppid=", "-p", strconv.Itoa(pid)).Output() |
| 33 | if err != nil { |
| 34 | return false |
| 35 | } |
| 36 | pid, _ = strconv.Atoi(strings.TrimSpace(string(value))) |
| 37 | } |
| 38 | return false |
| 39 | } |
| 40 | pattern := regexp.MustCompile(`pid ([0-9]+)\(caffeinate\):[^\n]+`) |
| 41 | var assertionPID string |
| 42 | deadline := time.Now().Add(3 * time.Second) |
| 43 | for time.Now().Before(deadline) && assertionPID == "" { |
| 44 | data, err := exec.Command("/usr/bin/pmset", "-g", "assertions").Output() |
| 45 | if err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | for _, match := range pattern.FindAllStringSubmatch(string(data), -1) { |
| 49 | pid, _ := strconv.Atoi(match[1]) |
| 50 | if owned(pid) { |
| 51 | if !strings.Contains(match[0], "PreventUserIdleSystemSleep") || strings.Contains(match[0], "PreventUserIdleDisplaySleep") { |
| 52 | t.Fatal("wrong assertion", match[0]) |
| 53 | } |
| 54 | assertionPID = match[1] |
| 55 | } |
| 56 | } |
| 57 | if assertionPID == "" { |
| 58 | time.Sleep(50 * time.Millisecond) |
| 59 | } |
| 60 | } |
| 61 | if assertionPID == "" { |
| 62 | t.Fatal("no owned idle-system-sleep assertion found") |
| 63 | } |
| 64 | cancel() |
| 65 | select { |
| 66 | case <-done: |
| 67 | case <-time.After(3 * time.Second): |
| 68 | t.Fatal("power helper did not exit") |
| 69 | } |
| 70 | data, err := exec.Command("/usr/bin/pmset", "-g", "assertions").Output() |
| 71 | if err != nil || strings.Contains(string(data), "pid "+assertionPID+"(caffeinate):") { |
| 72 | t.Fatal("power assertion survived cancellation", err) |
| 73 | } |
| 74 | } |