| 1 | // Package tmuxtest keeps a package's tests off every real tmux server. |
| 2 | package tmuxtest |
| 3 | |
| 4 | import ( |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "testing" |
| 10 | |
| 11 | "the-valley/flow/internal/tmux" |
| 12 | ) |
| 13 | |
| 14 | // Main runs a package's tests as launch runs a worker: without $TMUX, |
| 15 | // $TMUX_PANE or $KLAUS_TMUX_SOCKET, and with a TMUX_TMPDIR of their own. A |
| 16 | // klaus agent's `go test` inherits its environment, and a coordinator's |
| 17 | // carries $TMUX, so without this any code under test that reaches the real |
| 18 | // tmux client talks to the shared server (issue #295). A test that wants a |
| 19 | // server starts its own with -S. Use it as |
| 20 | // |
| 21 | // func TestMain(m *testing.M) { os.Exit(tmuxtest.Main(m)) } |
| 22 | func Main(m *testing.M) int { |
| 23 | dir, err := os.MkdirTemp("", "klaus-tmux-") |
| 24 | if err != nil { |
| 25 | fmt.Fprintln(os.Stderr, "tmuxtest:", err) |
| 26 | return 1 |
| 27 | } |
| 28 | defer os.RemoveAll(dir) |
| 29 | for _, k := range []string{"TMUX", "TMUX_PANE", tmux.SocketEnv} { |
| 30 | os.Unsetenv(k) |
| 31 | } |
| 32 | os.Setenv("TMUX_TMPDIR", dir) |
| 33 | |
| 34 | code := m.Run() |
| 35 | |
| 36 | // A server something started at the private default goes too. The socket |
| 37 | // is named outright, so this can't reach any other server. |
| 38 | sock := filepath.Join(dir, fmt.Sprintf("tmux-%d", os.Getuid()), "default") |
| 39 | if _, err := os.Stat(sock); err == nil { |
| 40 | _ = exec.Command("tmux", "-S", sock, "kill-server").Run() |
| 41 | } |
| 42 | return code |
| 43 | } |