| 1 |
//go:build pprof |
| 2 |
// +build pprof |
| 3 |
|
| 4 |
package fzf |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"flag" |
| 9 |
"os" |
| 10 |
"os/exec" |
| 11 |
"path/filepath" |
| 12 |
"testing" |
| 13 |
|
| 14 |
"github.com/junegunn/fzf/src/util" |
| 15 |
) |
| 16 |
|
| 17 |
// runInitProfileTests is an internal flag used TestInitProfiling |
| 18 |
var runInitProfileTests = flag.Bool("test-init-profile", false, "run init profile tests") |
| 19 |
|
| 20 |
func TestInitProfiling(t *testing.T) { |
| 21 |
if testing.Short() { |
| 22 |
t.Skip("short test") |
| 23 |
} |
| 24 |
|
| 25 |
// Run this test in a separate process since it interferes with |
| 26 |
// profiling and modifies the global atexit state. Without this |
| 27 |
// running `go test -bench . -cpuprofile cpu.out` will fail. |
| 28 |
if !*runInitProfileTests { |
| 29 |
t.Parallel() |
| 30 |
|
| 31 |
// Make sure we are not the child process. |
| 32 |
if os.Getenv("_FZF_CHILD_PROC") != "" { |
| 33 |
t.Fatal("already running as child process!") |
| 34 |
} |
| 35 |
|
| 36 |
cmd := exec.Command(os.Args[0], |
| 37 |
"-test.timeout", "30s", |
| 38 |
"-test.run", "^"+t.Name()+"$", |
| 39 |
"-test-init-profile", |
| 40 |
) |
| 41 |
cmd.Env = append(os.Environ(), "_FZF_CHILD_PROC=1") |
| 42 |
|
| 43 |
out, err := cmd.CombinedOutput() |
| 44 |
out = bytes.TrimSpace(out) |
| 45 |
if err != nil { |
| 46 |
t.Fatalf("Child test process failed: %v:\n%s", err, out) |
| 47 |
} |
| 48 |
// Make sure the test actually ran |
| 49 |
if bytes.Contains(out, []byte("no tests to run")) { |
| 50 |
t.Fatalf("Failed to run test %q:\n%s", t.Name(), out) |
| 51 |
} |
| 52 |
return |
| 53 |
} |
| 54 |
|
| 55 |
// Child process |
| 56 |
|
| 57 |
tempdir := t.TempDir() |
| 58 |
t.Cleanup(util.RunAtExitFuncs) |
| 59 |
|
| 60 |
o := Options{ |
| 61 |
CPUProfile: filepath.Join(tempdir, "cpu.prof"), |
| 62 |
MEMProfile: filepath.Join(tempdir, "mem.prof"), |
| 63 |
BlockProfile: filepath.Join(tempdir, "block.prof"), |
| 64 |
MutexProfile: filepath.Join(tempdir, "mutex.prof"), |
| 65 |
} |
| 66 |
if err := o.initProfiling(); err != nil { |
| 67 |
t.Fatal(err) |
| 68 |
} |
| 69 |
|
| 70 |
profiles := []string{ |
| 71 |
o.CPUProfile, |
| 72 |
o.MEMProfile, |
| 73 |
o.BlockProfile, |
| 74 |
o.MutexProfile, |
| 75 |
} |
| 76 |
for _, name := range profiles { |
| 77 |
if _, err := os.Stat(name); err != nil { |
| 78 |
t.Errorf("Failed to create profile %s: %v", filepath.Base(name), err) |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
util.RunAtExitFuncs() |
| 83 |
|
| 84 |
for _, name := range profiles { |
| 85 |
if _, err := os.Stat(name); err != nil { |
| 86 |
t.Errorf("Failed to write profile %s: %v", filepath.Base(name), err) |
| 87 |
} |
| 88 |
} |
| 89 |
} |