gunk-dev/the-valley

supervise.go

sourcef961a59e125emain's published tip history
1.9 KiB
1package exporttest
2
3import (
4 "os/exec"
5 "strings"
6 "testing"
7 "time"
8)
9
10// waitDelay is how long a program a test runs may hold its output open
11// once it has exited or been killed, as exec.Cmd.WaitDelay bounds it.
12const waitDelay = 5 * time.Second
13
14// Start starts cmd, a program a test runs, so that no process of it
15// outlives the test. cmd runs in a session of its own, which every process
16// it starts stays in unless it leaves the session. Where the kernel has no
17// sessions to list, cmd runs in a process group of its own instead.
18//
19// Start returns kill, which kills every process in the session, even once
20// cmd has exited, and registers a cleanup that calls it when the test
21// ends. If the test process dies first, as on a timeout or an external
22// kill, the kernel kills cmd, and on Linux a watchdog kills the rest of
23// the session (see watchdog).
24func Start(t testing.TB, cmd *exec.Cmd) (kill func(), err error) {
25 cmd.SysProcAttr = sysProcAttr()
26 if cmd.WaitDelay == 0 {
27 cmd.WaitDelay = waitDelay
28 }
29 if err := cmd.Start(); err != nil {
30 return func() {}, err
31 }
32 sid := cmd.Process.Pid
33 watch(sid)
34 kill = func() { killSession(sid) }
35 t.Cleanup(func() {
36 kill()
37 unwatch(sid)
38 })
39 return kill, nil
40}
41
42// Run runs cmd as Start does and waits for it, for at most d, and then
43// kills whatever cmd left running in its session. A cmd that has not
44// exited within d is killed, with its session, and fails the test. Run
45// returns cmd's error, as cmd.Run does.
46func Run(t testing.TB, cmd *exec.Cmd, d time.Duration) error {
47 t.Helper()
48 kill, err := Start(t, cmd)
49 if err != nil {
50 return err
51 }
52 done := make(chan error, 1)
53 go func() { done <- cmd.Wait() }()
54 select {
55 case err := <-done:
56 kill()
57 return err
58 case <-time.After(d):
59 }
60 // Once the session is killed, nothing holds cmd's output open but a
61 // process that left it, and cmd.WaitDelay bounds that.
62 kill()
63 <-done
64 t.Fatalf("%s did not exit within %v", strings.Join(cmd.Args, " "), d)
65 return nil
66}