|
1 | 1 | package process
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bufio" |
4 | 5 | "errors"
|
5 | 6 | "fmt"
|
6 | 7 | "io/ioutil"
|
@@ -391,6 +392,62 @@ func Test_Process_Long_Name(t *testing.T) {
|
391 | 392 | cmd.Process.Kill()
|
392 | 393 | }
|
393 | 394 |
|
| 395 | +func Test_Process_Name_Against_Python(t *testing.T) { |
| 396 | + if runtime.GOOS == "windows" { |
| 397 | + t.Skip("only applies to posix") |
| 398 | + } |
| 399 | + py3Path, err := exec.LookPath("python3") |
| 400 | + if err != nil { |
| 401 | + t.Skipf("python3 not found: %s", err) |
| 402 | + } |
| 403 | + if out, err := exec.Command(py3Path, "-c", "import psutil").CombinedOutput(); err != nil { |
| 404 | + t.Skipf("psutil not found for %s: %s", py3Path, out) |
| 405 | + } |
| 406 | + |
| 407 | + tmpdir, err := ioutil.TempDir("", "") |
| 408 | + if err != nil { |
| 409 | + t.Fatalf("unable to create temp dir %v", err) |
| 410 | + } |
| 411 | + defer os.RemoveAll(tmpdir) // clean up |
| 412 | + tmpfilepath := filepath.Join(tmpdir, "looooooooooooooooooooong.py") |
| 413 | + tmpfile, err := os.Create(tmpfilepath) |
| 414 | + if err != nil { |
| 415 | + t.Fatalf("unable to create temp file %v", err) |
| 416 | + } |
| 417 | + tmpfilecontent := []byte("#!" + py3Path + "\nimport psutil, time\nprint(psutil.Process().name(), flush=True)\nwhile True:\n\ttime.sleep(1)") |
| 418 | + if _, err := tmpfile.Write(tmpfilecontent); err != nil { |
| 419 | + tmpfile.Close() |
| 420 | + t.Fatalf("unable to write temp file %v", err) |
| 421 | + } |
| 422 | + if err := tmpfile.Chmod(0o744); err != nil { |
| 423 | + t.Fatalf("unable to chmod u+x temp file %v", err) |
| 424 | + } |
| 425 | + if err := tmpfile.Close(); err != nil { |
| 426 | + t.Fatalf("unable to close temp file %v", err) |
| 427 | + } |
| 428 | + cmd := exec.Command(tmpfilepath) |
| 429 | + outPipe, _ := cmd.StdoutPipe() |
| 430 | + scanner := bufio.NewScanner(outPipe) |
| 431 | + cmd.Start() |
| 432 | + defer cmd.Process.Kill() |
| 433 | + scanner.Scan() |
| 434 | + pyName := scanner.Text() // first line printed by py3 script, its name |
| 435 | + t.Logf("pyName %s", pyName) |
| 436 | + p, err := NewProcess(int32(cmd.Process.Pid)) |
| 437 | + skipIfNotImplementedErr(t, err) |
| 438 | + if err != nil { |
| 439 | + t.Fatalf("getting process error %v", err) |
| 440 | + } |
| 441 | + name, err := p.Name() |
| 442 | + skipIfNotImplementedErr(t, err) |
| 443 | + if err != nil { |
| 444 | + t.Fatalf("getting name error %v", err) |
| 445 | + } |
| 446 | + if pyName != name { |
| 447 | + t.Fatalf("psutil and gopsutil process.Name() results differ: expected %s, got %s", pyName, name) |
| 448 | + } |
| 449 | +} |
| 450 | + |
394 | 451 | func Test_Process_Exe(t *testing.T) {
|
395 | 452 | p := testGetProcess()
|
396 | 453 |
|
|
0 commit comments