go.starlark.net@v0.0.0-20231101134539-556fd59b42f6/starlark/profile_test.go (about)

     1  // Copyright 2019 The Bazel Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package starlark_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"os"
    11  	"os/exec"
    12  	"strings"
    13  	"testing"
    14  
    15  	"go.starlark.net/starlark"
    16  )
    17  
    18  // TestProfile is a simple integration test that the profiler
    19  // emits minimally plausible pprof-compatible output.
    20  func TestProfile(t *testing.T) {
    21  	prof, err := os.CreateTemp(t.TempDir(), "profile_test")
    22  	if err != nil {
    23  		t.Fatal(err)
    24  	}
    25  	defer prof.Close()
    26  	if err := starlark.StartProfile(prof); err != nil {
    27  		t.Fatal(err)
    28  	}
    29  
    30  	const src = `
    31  def fibonacci(n):
    32  	x, y = 1, 1
    33  	for i in range(n):
    34  		x, y = y, x+y
    35  	return y
    36  
    37  fibonacci(100000)
    38  `
    39  
    40  	thread := new(starlark.Thread)
    41  	if _, err := starlark.ExecFile(thread, "foo.star", src, nil); err != nil {
    42  		_ = starlark.StopProfile()
    43  		t.Fatal(err)
    44  	}
    45  	if err := starlark.StopProfile(); err != nil {
    46  		t.Fatal(err)
    47  	}
    48  	prof.Sync()
    49  	cmd := exec.Command("go", "tool", "pprof", "-top", prof.Name())
    50  	cmd.Stderr = new(bytes.Buffer)
    51  	cmd.Stdout = new(bytes.Buffer)
    52  	if err := cmd.Run(); err != nil {
    53  		t.Fatalf("pprof failed: %v; output=<<%s>>", err, cmd.Stderr)
    54  	}
    55  
    56  	// Typical output (may vary by go release):
    57  	//
    58  	// Type: wall
    59  	// Time: Apr 4, 2019 at 11:10am (EDT)
    60  	// Duration: 251.62ms, Total samples = 250ms (99.36%)
    61  	// Showing nodes accounting for 250ms, 100% of 250ms total
    62  	//  flat  flat%   sum%        cum   cum%
    63  	// 320ms   100%   100%      320ms   100%  fibonacci
    64  	//     0     0%   100%      320ms   100%  foo.star
    65  	//
    66  	// We'll assert a few key substrings are present.
    67  	got := fmt.Sprint(cmd.Stdout)
    68  	for _, want := range []string{
    69  		"flat%",
    70  		"fibonacci",
    71  		"foo.star",
    72  	} {
    73  		if !strings.Contains(got, want) {
    74  			t.Errorf("output did not contain %q", want)
    75  		}
    76  	}
    77  	if t.Failed() {
    78  		t.Logf("stderr=%v", cmd.Stderr)
    79  		t.Logf("stdout=%v", cmd.Stdout)
    80  	}
    81  }