forked from mitchellh/go-ps
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathprocess_nix_test.go
93 lines (81 loc) · 1.99 KB
/
process_nix_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// +build darwin linux netbsd
package ps
import (
"io"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestProcessExecRun(t *testing.T) {
procPath, cmd, _ := testExecRun(t)
defer cleanup(cmd, procPath)
}
func testProcessPath(t *testing.T, procPath string) Process {
matchPath := func(p Process) bool {
return matchPath(t, p, procPath)
}
procs, err := findProcessesWithFn(processes, matchPath, 1)
require.NoError(t, err)
require.Equal(t, 1, len(procs))
proc := procs[0]
path, err := proc.Path()
require.NoError(t, err)
require.Equal(t, procPath, path)
return proc
}
func cleanup(cmd *exec.Cmd, procPath string) {
if cmd != nil && cmd.Process != nil {
_ = cmd.Process.Kill()
}
_ = os.Remove(procPath)
}
func testExecPath(t *testing.T) string {
// Copy sleep executable to tmp
procPath := filepath.Join(os.TempDir(), "sleeptest")
err := copyFile("/bin/sleep", procPath, 0777)
require.NoError(t, err)
// Temp dir might have symlinks in which case we need the eval'ed path
procPath, err = filepath.EvalSymlinks(procPath)
require.NoError(t, err)
return procPath
}
func testExecRun(t *testing.T) (string, *exec.Cmd, Process) {
procPath := testExecPath(t)
cmd := exec.Command(procPath, "10")
err := cmd.Start()
require.NoError(t, err)
proc := testProcessPath(t, procPath)
return procPath, cmd, proc
}
func copyFile(sourcePath string, destinationPath string, mode os.FileMode) error {
in, err := os.Open(sourcePath)
if err != nil {
return err
}
defer func() { _ = in.Close() }()
out, err := os.Create(destinationPath)
if err != nil {
return err
}
defer func() { _ = out.Close() }()
_, err = io.Copy(out, in)
closeErr := out.Close()
if err != nil {
return err
}
err = os.Chmod(destinationPath, mode)
if err != nil {
return err
}
return closeErr
}
func matchPath(t *testing.T, p Process, match string) bool {
path, err := p.Path()
if err != nil {
t.Logf("Error trying to get path: %s", err)
return false
}
return path == match
}