Source file src/cmd/internal/script/scripttest/run.go

     1  // Copyright 2022 The Go 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 scripttest adapts the script engine for use in tests.
     6  package scripttest
     7  
     8  import (
     9  	"bytes"
    10  	"cmd/internal/script"
    11  	"context"
    12  	"fmt"
    13  	"internal/testenv"
    14  	"internal/txtar"
    15  	"io/fs"
    16  	"os"
    17  	"os/exec"
    18  	"path/filepath"
    19  	"runtime"
    20  	"strings"
    21  	"testing"
    22  	"time"
    23  )
    24  
    25  // ToolReplacement records the name of a tool to replace
    26  // within a given GOROOT for script testing purposes.
    27  type ToolReplacement struct {
    28  	ToolName        string // e.g. compile, link, addr2line, etc
    29  	ReplacementPath string // path to replacement tool exe
    30  	EnvVar          string // env var setting (e.g. "FOO=BAR")
    31  }
    32  
    33  // NewEngine constructs a new [script.Engine] and environment to be used with
    34  // [RunTests].
    35  func NewEngine(t *testing.T, repls []ToolReplacement) (*script.Engine, []string) {
    36  	// Nearly all script tests involve doing builds, so don't
    37  	// bother here if we don't have "go build".
    38  	testenv.MustHaveGoBuild(t)
    39  
    40  	// Skip this path on plan9, which doesn't support symbolic
    41  	// links (we would have to copy too much).
    42  	if runtime.GOOS == "plan9" {
    43  		t.Skipf("no symlinks on plan9")
    44  	}
    45  
    46  	// Locate our Go tool.
    47  	gotool, err := testenv.GoTool()
    48  	if err != nil {
    49  		t.Fatalf("locating go tool: %v", err)
    50  	}
    51  
    52  	goEnv := func(name string) string {
    53  		out, err := exec.Command(gotool, "env", name).CombinedOutput()
    54  		if err != nil {
    55  			t.Fatalf("go env %s: %v\n%s", name, err, out)
    56  		}
    57  		return strings.TrimSpace(string(out))
    58  	}
    59  
    60  	// Construct an initial set of commands + conditions to make available
    61  	// to the script tests.
    62  	cmds := DefaultCmds()
    63  	conds := DefaultConds()
    64  
    65  	addcmd := func(name string, cmd script.Cmd) {
    66  		if _, ok := cmds[name]; ok {
    67  			panic(fmt.Sprintf("command %q is already registered", name))
    68  		}
    69  		cmds[name] = cmd
    70  	}
    71  
    72  	prependToPath := func(env []string, dir string) {
    73  		found := false
    74  		for k := range env {
    75  			ev := env[k]
    76  			if !strings.HasPrefix(ev, "PATH=") {
    77  				continue
    78  			}
    79  			oldpath := ev[5:]
    80  			env[k] = "PATH=" + dir + string(filepath.ListSeparator) + oldpath
    81  			found = true
    82  			break
    83  		}
    84  		if !found {
    85  			t.Fatalf("could not update PATH")
    86  		}
    87  	}
    88  
    89  	setenv := func(env []string, varname, val string) []string {
    90  		pref := varname + "="
    91  		found := false
    92  		for k := range env {
    93  			if !strings.HasPrefix(env[k], pref) {
    94  				continue
    95  			}
    96  			env[k] = pref + val
    97  			found = true
    98  			break
    99  		}
   100  		if !found {
   101  			env = append(env, varname+"="+val)
   102  		}
   103  		return env
   104  	}
   105  
   106  	// Customize the subprocess termination grace period to reduce flakes on busy builders (#76685).
   107  	// The grace period is the max of 100ms or 5% of the time remaining until any t.Deadline.
   108  	gracePeriod := subprocessGracePeriod(t.Deadline())
   109  
   110  	cmdExec := script.Exec(script.InterruptCmd, gracePeriod)
   111  	cmds["exec"] = cmdExec
   112  
   113  	// Set up an alternate go root for running script tests, since it
   114  	// is possible that we might want to replace one of the installed
   115  	// tools with a unit test executable.
   116  	goroot := goEnv("GOROOT")
   117  	tmpdir := t.TempDir()
   118  	tgr := SetupTestGoRoot(t, tmpdir, goroot)
   119  
   120  	// Replace tools if appropriate
   121  	for _, repl := range repls {
   122  		ReplaceGoToolInTestGoRoot(t, tgr, repl.ToolName, repl.ReplacementPath)
   123  	}
   124  
   125  	// Add in commands for "go" and "cc".
   126  	testgo := filepath.Join(tgr, "bin", "go")
   127  	gocmd := script.Program(testgo, script.InterruptCmd, gracePeriod)
   128  	addcmd("go", gocmd)
   129  	addcmd("cc", scriptCC(cmdExec, goEnv("CC")))
   130  
   131  	// Add various helpful conditions related to builds and toolchain use.
   132  	goHostOS, goHostArch := goEnv("GOHOSTOS"), goEnv("GOHOSTARCH")
   133  	AddToolChainScriptConditions(t, conds, goHostOS, goHostArch)
   134  
   135  	// Environment setup.
   136  	env := os.Environ()
   137  	prependToPath(env, filepath.Join(tgr, "bin"))
   138  	env = setenv(env, "GOROOT", tgr)
   139  	// GOOS and GOARCH are expected to be set by the toolchain script conditions.
   140  	env = setenv(env, "GOOS", runtime.GOOS)
   141  	env = setenv(env, "GOARCH", runtime.GOARCH)
   142  	for _, repl := range repls {
   143  		// consistency check
   144  		chunks := strings.Split(repl.EnvVar, "=")
   145  		if len(chunks) != 2 {
   146  			t.Fatalf("malformed env var setting: %s", repl.EnvVar)
   147  		}
   148  		env = append(env, repl.EnvVar)
   149  	}
   150  
   151  	// Manufacture engine...
   152  	engine := &script.Engine{
   153  		Conds: conds,
   154  		Cmds:  cmds,
   155  		Quiet: !testing.Verbose(),
   156  	}
   157  
   158  	return engine, env
   159  }
   160  
   161  // RunToolScriptTest kicks off a set of script tests runs for
   162  // a tool of some sort (compiler, linker, etc). The expectation
   163  // is that we'll be called from the top level cmd/X dir for tool X,
   164  // and that instead of executing the install tool X we'll use the
   165  // test binary instead.
   166  func RunToolScriptTest(t *testing.T, repls []ToolReplacement, scriptsdir string, fixReadme bool) {
   167  	// Locate our Go tool.
   168  	gotool, err := testenv.GoTool()
   169  	if err != nil {
   170  		t.Fatalf("locating go tool: %v", err)
   171  	}
   172  
   173  	engine, env := NewEngine(t, repls)
   174  
   175  	t.Run("README", func(t *testing.T) {
   176  		checkScriptReadme(t, engine, env, scriptsdir, gotool, fixReadme)
   177  	})
   178  
   179  	// ... and kick off tests.
   180  	ctx := context.Background()
   181  	pattern := filepath.Join(scriptsdir, "*.txt")
   182  	RunTests(t, ctx, engine, env, pattern)
   183  }
   184  
   185  // ScriptTestContext returns a context with a grace period for cleaning up
   186  // subprocesses of a script test.
   187  //
   188  // When we run commands that execute subprocesses, we want to reserve two grace
   189  // periods to clean up. We will send the first termination signal when the
   190  // context expires, then wait one grace period for the process to produce
   191  // whatever useful output it can (such as a stack trace). After the first grace
   192  // period expires, we'll escalate to os.Kill, leaving the second grace period
   193  // for the test function to record its output before the test process itself
   194  // terminates.
   195  //
   196  // The grace period is 100ms or 5% of the time remaining until
   197  // [testing.T.Deadline], whichever is greater.
   198  func ScriptTestContext(t *testing.T, ctx context.Context) context.Context {
   199  	deadline, ok := t.Deadline()
   200  	if !ok {
   201  		return ctx
   202  	}
   203  
   204  	gracePeriod := subprocessGracePeriod(deadline, ok)
   205  
   206  	// Reserve two grace periods to clean up
   207  	timeout := time.Until(deadline)
   208  	timeout -= 2 * gracePeriod
   209  
   210  	ctx, cancel := context.WithTimeout(ctx, timeout)
   211  	t.Cleanup(cancel)
   212  	return ctx
   213  }
   214  
   215  // subprocessGracePeriod returns a grace period for terminating subprocesses
   216  // created by the commands of a script test.
   217  func subprocessGracePeriod(deadline time.Time, hasDeadline bool) time.Duration {
   218  	gracePeriod := 100 * time.Millisecond // arbitrary
   219  	if !hasDeadline {
   220  		return gracePeriod
   221  	}
   222  
   223  	// If time allows, increase the termination grace period to 5% of the
   224  	// remaining time.
   225  	timeout := time.Until(deadline)
   226  	return max(gracePeriod, timeout/20)
   227  }
   228  
   229  // RunTests kicks off one or more script-based tests using the
   230  // specified engine, running all test files that match pattern.
   231  // This function adapted from Russ's rsc.io/script/scripttest#Run
   232  // function, which was in turn forked off cmd/go's runner.
   233  func RunTests(t *testing.T, ctx context.Context, engine *script.Engine, env []string, pattern string) {
   234  	ctx = ScriptTestContext(t, ctx)
   235  
   236  	files, _ := filepath.Glob(pattern)
   237  	if len(files) == 0 {
   238  		t.Fatal("no testdata")
   239  	}
   240  	for _, file := range files {
   241  		file := file
   242  		name := strings.TrimSuffix(filepath.Base(file), ".txt")
   243  		t.Run(name, func(t *testing.T) {
   244  			t.Parallel()
   245  
   246  			workdir := t.TempDir()
   247  			s, err := script.NewState(ctx, workdir, env)
   248  			if err != nil {
   249  				t.Fatal(err)
   250  			}
   251  
   252  			// Call fixPermissions at the end of the test case in case
   253  			// it uses the go modcache, which writes read-only files.
   254  			// fixPermissions fixes up the permissions so a later removal can succeed.
   255  			defer fixPermissions(t, workdir)
   256  
   257  			// Unpack archive.
   258  			a, err := txtar.ParseFile(file)
   259  			if err != nil {
   260  				t.Fatal(err)
   261  			}
   262  			InitScriptDirs(t, s)
   263  			if err := s.ExtractFiles(a); err != nil {
   264  				t.Fatal(err)
   265  			}
   266  
   267  			t.Log(time.Now().UTC().Format(time.RFC3339))
   268  			work, _ := s.LookupEnv("WORK")
   269  			t.Logf("$WORK=%s", work)
   270  
   271  			// Note: Do not use filepath.Base(file) here:
   272  			// editors that can jump to file:line references in the output
   273  			// will work better seeing the full path relative to the
   274  			// directory containing the command being tested
   275  			// (e.g. where "go test" command is usually run).
   276  			Run(t, engine, s, file, bytes.NewReader(a.Comment))
   277  		})
   278  	}
   279  }
   280  
   281  func fixPermissions(t *testing.T, dir string) {
   282  	t.Helper()
   283  
   284  	// module cache has 0444 directories;
   285  	// make them writable in order to remove content.
   286  	filepath.WalkDir(dir, func(path string, info fs.DirEntry, err error) error {
   287  		// chmod not only directories, but also things that we couldn't even stat
   288  		// due to permission errors: they may also be unreadable directories.
   289  		if err != nil || info.IsDir() {
   290  			os.Chmod(path, 0777)
   291  		}
   292  		return nil
   293  	})
   294  }
   295  
   296  // InitScriptDirs sets up directories for executing a script test.
   297  //
   298  //   - WORK (env var) is set to the current working directory.
   299  //   - TMPDIR (env var; TMP on Windows) is set to $WORK/tmp.
   300  //   - $TMPDIR is created.
   301  func InitScriptDirs(t testing.TB, s *script.State) {
   302  	must := func(err error) {
   303  		if err != nil {
   304  			t.Helper()
   305  			t.Fatal(err)
   306  		}
   307  	}
   308  
   309  	work := s.Getwd()
   310  	must(s.Setenv("WORK", work))
   311  	must(os.MkdirAll(filepath.Join(work, "tmp"), 0777))
   312  	must(s.Setenv(tempEnvName(), filepath.Join(work, "tmp")))
   313  }
   314  
   315  func tempEnvName() string {
   316  	switch runtime.GOOS {
   317  	case "windows":
   318  		return "TMP"
   319  	case "plan9":
   320  		return "TMPDIR" // actually plan 9 doesn't have one at all but this is fine
   321  	default:
   322  		return "TMPDIR"
   323  	}
   324  }
   325  
   326  // scriptCC runs the platform C compiler.
   327  func scriptCC(cmdExec script.Cmd, ccexe string) script.Cmd {
   328  	return script.Command(
   329  		script.CmdUsage{
   330  			Summary: "run the platform C compiler",
   331  			Args:    "args...",
   332  		},
   333  		func(s *script.State, args ...string) (script.WaitFunc, error) {
   334  			return cmdExec.Run(s, append([]string{ccexe}, args...)...)
   335  		})
   336  }
   337  

View as plain text