Debian Codegraph @

testscript/testscript.go

raw symbols SCIP
1 // Copyright 2018 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 // Script-driven tests.
6 // See testdata/script/README for an overview.
7
8 package testscript
9
10 import (
11 "bytes"
12 "context"
13 "errors"
14 "flag"
15 "fmt"
16 "go/build"
17 "io"
18 "io/fs"
19 "os"
20 "os/exec"
21 "path/filepath"
22 "regexp"
23 "runtime"
24 "slices"
25 "strconv"
26 "strings"
27 "sync/atomic"
28 "syscall"
29 "testing"
30 "time"
31
32 "github.com/rogpeppe/go-internal/imports"
33 "github.com/rogpeppe/go-internal/internal/misspell"
34 "github.com/rogpeppe/go-internal/internal/os/execpath"
35 "github.com/rogpeppe/go-internal/par"
36 "github.com/rogpeppe/go-internal/testenv"
37 "github.com/rogpeppe/go-internal/testscript/internal/pty"
38 "github.com/rogpeppe/go-internal/txtar"
39 )
40
41 var goVersionRegex = regexp.MustCompile(`^go([1-9][0-9]*)\.([1-9][0-9]*)$`)
42
43 var execCache par.Cache
44
45 // If -testwork is specified, the test prints the name of the temp directory
46 // and does not remove it when done, so that a programmer can
47 // poke at the test file tree afterward.
48 var testWork = flag.Bool("testwork", false, "")
49
50 // timeSince is defined as a variable so that it can be overridden
51 // for the local testscript tests so that we can test against predictable
52 // output.
53 var timeSince = time.Since
54
55 // showVerboseEnv specifies whether the environment should be displayed
56 // automatically when in verbose mode. This is set to false for the local testscript tests so we
57 // can test against predictable output.
58 var showVerboseEnv = true
59
60 // Env holds the environment to use at the start of a test script invocation.
61 type Env struct {
62 // WorkDir holds the path to the root directory of the
63 // extracted files.
64 WorkDir string
65 // Vars holds the initial set environment variables that will be passed to the
66 // testscript commands.
67 Vars []string
68 // Cd holds the initial current working directory.
69 Cd string
70 // Values holds a map of arbitrary values for use by custom
71 // testscript commands. This enables Setup to pass arbitrary
72 // values (not just strings) through to custom commands.
73 Values map[any]any
74
75 ts *TestScript
76 }
77
78 // Value returns a value from Env.Values, or nil if no
79 // value was set by Setup.
80 func (ts *TestScript) Value(key any) any {
81 return ts.values[key]
82 }
83
84 // Defer arranges for f to be called at the end
85 // of the test. If Defer is called multiple times, the
86 // defers are executed in reverse order (similar
87 // to Go's defer statement)
88 func (e *Env) Defer(f func()) {
89 e.ts.Defer(f)
90 }
91
92 // Getenv retrieves the value of the environment variable named by the key. It
93 // returns the value, which will be empty if the variable is not present.
94 func (e *Env) Getenv(key string) string {
95 key = envvarname(key)
96 for i := len(e.Vars) - 1; i >= 0; i-- {
97 if pair := strings.SplitN(e.Vars[i], "=", 2); len(pair) == 2 && envvarname(pair[0]) == key {
98 return pair[1]
99 }
100 }
101 return ""
102 }
103
104 func envvarname(k string) string {
105 if runtime.GOOS == "windows" {
106 return strings.ToLower(k)
107 }
108 return k
109 }
110
111 // Setenv sets the value of the environment variable named by the key. It
112 // panics if key is invalid.
113 func (e *Env) Setenv(key, value string) {
114 if key == "" || strings.IndexByte(key, '=') != -1 {
115 panic(fmt.Errorf("invalid environment variable key %q", key))
116 }
117 e.Vars = append(e.Vars, key+"="+value)
118 }
119
120 // T returns the t argument passed to the current test by the T.Run method.
121 // Note that if the tests were started by calling Run,
122 // the returned value will implement testing.TB.
123 // Note that, despite that, the underlying value will not be of type
124 // *testing.T because *testing.T does not implement T.
125 //
126 // If Cleanup is called on the returned value, the function will run
127 // after any functions passed to Env.Defer.
128 func (e *Env) T() T {
129 return e.ts.t
130 }
131
132 // Params holds parameters for a call to Run.
133 type Params struct {
134 // Dir holds the name of the directory holding the scripts.
135 // All files in the directory with a .txtar or .txt suffix will be
136 // considered as test scripts. By default the current directory is used.
137 // Dir is interpreted relative to the current test directory.
138 Dir string
139
140 // Files holds a set of script filenames. If Dir is empty and this
141 // is non-nil, these files will be used instead of reading
142 // a directory.
143 Files []string
144
145 // Setup is called, if not nil, to complete any setup required
146 // for a test. The WorkDir and Vars fields will have already
147 // been initialized and all the files extracted into WorkDir,
148 // and Cd will be the same as WorkDir.
149 // The Setup function may modify Vars and Cd as it wishes.
150 Setup func(*Env) error
151
152 // Condition is called, if not nil, to determine whether a particular
153 // condition is true. It's called only for conditions not in the
154 // standard set, and may be nil.
155 Condition func(cond string) (bool, error)
156
157 // Cmds holds a map of commands available to the script.
158 // It will only be consulted for commands not part of the standard set.
159 Cmds map[string]func(ts *TestScript, neg bool, args []string)
160
161 // TestWork specifies that working directories should be
162 // left intact for later inspection.
163 TestWork bool
164
165 // WorkdirRoot specifies the directory within which scripts' work
166 // directories will be created. Setting WorkdirRoot implies TestWork=true.
167 // If empty, the work directories will be created inside
168 // $GOTMPDIR/go-test-script*, where $GOTMPDIR defaults to os.TempDir().
169 WorkdirRoot string
170
171 // Deprecated: this option is no longer used.
172 IgnoreMissedCoverage bool
173
174 // UpdateScripts specifies that if a `cmp` command fails and its second
175 // argument refers to a file inside the testscript file, the command will
176 // succeed and the testscript file will be updated to reflect the actual
177 // content (which could be stdout, stderr or a real file).
178 //
179 // The content will be quoted with txtar.Quote if needed;
180 // a manual change will be needed if it is not unquoted in the
181 // script.
182 UpdateScripts bool
183
184 // RequireExplicitExec requires that commands passed to [Main] must be used
185 // in test scripts via `exec cmd` and not simply `cmd`. This can help keep
186 // consistency across test scripts as well as keep separate process
187 // executions explicit.
188 RequireExplicitExec bool
189
190 // RequireUniqueNames requires that names in the txtar archive are unique.
191 // By default, later entries silently overwrite earlier ones.
192 RequireUniqueNames bool
193
194 // ContinueOnError causes a testscript to try to continue in
195 // the face of errors. Once an error has occurred, the script
196 // will continue as if in verbose mode.
197 ContinueOnError bool
198
199 // Deadline, if not zero, specifies the time at which the test run will have
200 // exceeded the timeout. It is equivalent to testing.T's Deadline method,
201 // and Run will set it to the method's return value if this field is zero.
202 Deadline time.Time
203 }
204
205 // RunDir runs the tests in the given directory. All files in dir with a ".txt"
206 // or ".txtar" extension are considered to be test files.
207 func Run(t *testing.T, p Params) {
208 if deadline, ok := t.Deadline(); ok && p.Deadline.IsZero() {
209 p.Deadline = deadline
210 }
211 RunT(tshim{t}, p)
212 }
213
214 // T holds all the methods of the *testing.T type that
215 // are used by testscript.
216 type T interface {
217 Skip(...any)
218 Fatal(...any)
219 Parallel()
220 Log(...any)
221 FailNow()
222 Run(string, func(T))
223 // Verbose is usually implemented by the testing package
224 // directly rather than on the *testing.T type.
225 Verbose() bool
226 }
227
228 // Deprecated: this type is unused.
229 type TFailed interface {
230 Failed() bool
231 }
232
233 type tshim struct {
234 *testing.T
235 }
236
237 func (t tshim) Run(name string, f func(T)) {
238 t.T.Run(name, func(t *testing.T) {
239 f(tshim{t})
240 })
241 }
242
243 func (t tshim) Verbose() bool {
244 return testing.Verbose()
245 }
246
247 // RunT is like Run but uses an interface type instead of the concrete *testing.T
248 // type to make it possible to use testscript functionality outside of go test.
249 func RunT(t T, p Params) {
250 var files []string
251 if p.Dir == "" && p.Files != nil {
252 files = p.Files
253 } else {
254 entries, err := os.ReadDir(p.Dir)
255 if os.IsNotExist(err) {
256 // Continue so we give a helpful error on len(files)==0 below.
257 } else if err != nil {
258 t.Fatal(err)
259 }
260 for _, entry := range entries {
261 name := entry.Name()
262 if strings.HasSuffix(name, ".txtar") || strings.HasSuffix(name, ".txt") {
263 files = append(files, filepath.Join(p.Dir, name))
264 }
265 }
266
267 if len(files) == 0 {
268 t.Fatal(fmt.Sprintf("no txtar nor txt scripts found in dir %s", p.Dir))
269 }
270 }
271 testTempDir := p.WorkdirRoot
272 var err error
273 if testTempDir == "" {
274 testTempDir, err = os.MkdirTemp(os.Getenv("GOTMPDIR"), "go-test-script")
275 if err != nil {
276 t.Fatal(err)
277 }
278 } else {
279 p.TestWork = true
280 }
281 // The temp dir returned by os.MkdirTemp might be a sym linked dir (default
282 // behaviour in macOS). That could mess up matching that includes $WORK if,
283 // for example, an external program outputs resolved paths. Evaluating the
284 // dir here will ensure consistency.
285 testTempDir, err = filepath.EvalSymlinks(testTempDir)
286 if err != nil {
287 t.Fatal(err)
288 }
289
290 var (
291 ctx = context.Background()
292 gracePeriod = 100 * time.Millisecond
293 cancel context.CancelFunc
294 )
295 if !p.Deadline.IsZero() {
296 timeout := time.Until(p.Deadline)
297
298 // If time allows, increase the termination grace period to 5% of the
299 // remaining time.
300 if gp := timeout / 20; gp > gracePeriod {
301 gracePeriod = gp
302 }
303
304 // When we run commands that execute subprocesses, we want to reserve two
305 // grace periods to clean up. We will send the first termination signal when
306 // the context expires, then wait one grace period for the process to
307 // produce whatever useful output it can (such as a stack trace). After the
308 // first grace period expires, we'll escalate to os.Kill, leaving the second
309 // grace period for the test function to record its output before the test
310 // process itself terminates.
311 timeout -= 2 * gracePeriod
312
313 ctx, cancel = context.WithTimeout(ctx, timeout)
314 // We don't defer cancel() because RunT returns before the sub-tests,
315 // and we don't have access to Cleanup due to the T interface. Instead,
316 // we call it after the refCount goes to zero below.
317 _ = cancel
318 }
319
320 refCount := int32(len(files))
321 names := make(map[string]bool)
322 for _, file := range files {
323 name := filepath.Base(file)
324 if name1, ok := strings.CutSuffix(name, ".txt"); ok {
325 name = name1
326 } else if name1, ok := strings.CutSuffix(name, ".txtar"); ok {
327 name = name1
328 }
329 // We can have duplicate names when files are passed explicitly,
330 // so disambiguate by adding a counter.
331 // Take care to handle the situation where a name with a counter-like
332 // suffix already exists, for example:
333 // a/foo.txt
334 // b/foo.txtar
335 // c/foo#1.txt
336 prefix := name
337 for i := 1; names[name]; i++ {
338 name = prefix + "#" + strconv.Itoa(i)
339 }
340 names[name] = true
341 t.Run(name, func(t T) {
342 t.Parallel()
343 ts := &TestScript{
344 t: t,
345 testTempDir: testTempDir,
346 name: name,
347 file: file,
348 params: p,
349 ctxt: ctx,
350 gracePeriod: gracePeriod,
351 deferred: func() {},
352 scriptFiles: make(map[string]string),
353 scriptUpdates: make(map[string]string),
354 }
355 defer func() {
356 if p.TestWork || *testWork {
357 return
358 }
359 removeAll(ts.workdir)
360 if atomic.AddInt32(&refCount, -1) == 0 {
361 // This is the last subtest to finish. Remove the
362 // parent directory too, and cancel the context.
363 os.Remove(testTempDir)
364 if cancel != nil {
365 cancel()
366 }
367 }
368 }()
369 ts.run()
370 })
371 }
372 }
373
374 // A TestScript holds execution state for a single test script.
375 type TestScript struct {
376 params Params
377 t T
378 testTempDir string
379 workdir string // temporary work dir ($WORK)
380 log bytes.Buffer // test execution log (printed at end of test)
381 mark int // offset of next log truncation
382 cd string // current directory during test execution; initially $WORK/gopath/src
383 name string // short name of test ("foo")
384 file string // full file name ("testdata/script/foo.txt")
385 lineno int // line number currently executing
386 line string // line currently executing
387 env []string // environment list (for os/exec)
388 envMap map[string]string // environment mapping (matches env; on Windows keys are lowercase)
389 values map[any]any // values for custom commands
390
391 // localCmds holds commands registered for the current test only,
392 // via SetCmd. It takes precedence over Params.Cmds but not over the
393 // builtin commands. It is only ever accessed from the test's own
394 // goroutine, so needs no locking.
395 localCmds map[string]func(*TestScript, bool, []string)
396
397 stdin string // standard input to next 'go' command; set by 'stdin' command.
398 stdout string // standard output from last 'go' command; for 'stdout' command
399 stderr string // standard error from last 'go' command; for 'stderr' command
400 ttyin string // terminal input; set by 'ttyin' command
401 stdinPty bool // connect pty to standard input; set by 'ttyin -stdin' command
402 ttyout string // terminal output; for 'ttyout' command
403 stopped bool // test wants to stop early
404 start time.Time // time phase started
405 background []backgroundCmd // backgrounded 'exec' and 'go' commands
406 deferred func() // deferred cleanup actions.
407 archive *txtar.Archive // the testscript being run.
408 scriptFiles map[string]string // files stored in the txtar archive (absolute paths -> path in script)
409 scriptUpdates map[string]string // updates to testscript files via UpdateScripts.
410
411 // runningBuiltin indicates if we are running a user-supplied builtin
412 // command. These commands are specified via Params.Cmds.
413 runningBuiltin bool
414
415 // builtinStd(out|err) are established if a user-supplied builtin command
416 // requests Stdout() or Stderr(). Either both are non-nil, or both are nil.
417 // This invariant is maintained by both setBuiltinStd() and
418 // clearBuiltinStd().
419 builtinStdout *strings.Builder
420 builtinStderr *strings.Builder
421
422 ctxt context.Context // per TestScript context
423 gracePeriod time.Duration // time between SIGQUIT and SIGKILL
424 }
425
426 type backgroundCmd struct {
427 name string
428 cmd *exec.Cmd
429 wait <-chan struct{}
430 neg bool // if true, cmd should fail
431 }
432
433 func writeFile(name string, data []byte, perm fs.FileMode, excl bool) error {
434 oflags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
435 if excl {
436 oflags |= os.O_EXCL
437 }
438 f, err := os.OpenFile(name, oflags, perm)
439 if err != nil {
440 return err
441 }
442 defer f.Close()
443 if _, err := f.Write(data); err != nil {
444 return fmt.Errorf("cannot write file contents: %v", err)
445 }
446 return nil
447 }
448
449 // Name returns the short name or basename of the test script.
450 func (ts *TestScript) Name() string { return ts.name }
451
452 // SetCmd registers cmd as the implementation of the named command for the
453 // remainder of the current test only. It is intended for commands (such as
454 // those provided by plugins) that become available partway through a script.
455 // A nil cmd removes any previously registered command of that name.
456 //
457 // A command registered with SetCmd takes precedence over a command of the
458 // same name in [Params.Cmds] but cannot override a builtin command.
459 func (ts *TestScript) SetCmd(name string, cmd func(ts *TestScript, neg bool, args []string)) {
460 if cmd == nil {
461 delete(ts.localCmds, name)
462 return
463 }
464 if ts.localCmds == nil {
465 ts.localCmds = make(map[string]func(*TestScript, bool, []string))
466 }
467 ts.localCmds[name] = cmd
468 }
469
470 // setup sets up the test execution temporary directory and environment.
471 // It returns the comment section of the txtar archive.
472 func (ts *TestScript) setup() string {
473 defer catchFailNow(func() {
474 // There's been a failure in setup; fail immediately regardless
475 // of the ContinueOnError flag.
476 ts.t.FailNow()
477 })
478 ts.workdir = filepath.Join(ts.testTempDir, "script-"+ts.name)
479
480 // Establish a temporary directory in workdir, but use a prefix that ensures
481 // this directory will not be walked when resolving the ./... pattern from
482 // workdir. This is important because when resolving a ./... pattern, cmd/go
483 // (which is used by go/packages) creates temporary build files and
484 // directories. This can, and does, therefore interfere with the ./...
485 // pattern when used from workdir and can lead to race conditions within
486 // cmd/go as it walks directories to match the ./... pattern.
487 tmpDir := filepath.Join(ts.workdir, ".tmp")
488
489 ts.Check(os.MkdirAll(tmpDir, 0o777))
490 env := &Env{
491 Vars: []string{
492 "WORK=" + ts.workdir, // must be first for ts.abbrev
493 "PATH=" + os.Getenv("PATH"),
494 "GOTRACEBACK=system",
495 homeEnvName() + "=/no-home",
496 tempEnvName() + "=" + tmpDir,
497 "devnull=" + os.DevNull,
498 "/=" + string(os.PathSeparator),
499 ":=" + string(os.PathListSeparator),
500 "$=$",
501 },
502 WorkDir: ts.workdir,
503 Values: make(map[any]any),
504 Cd: ts.workdir,
505 ts: ts,
506 }
507
508 // These env vars affect how a Go program behaves at run-time;
509 // If the user or `go test` wrapper set them, we should propagate them
510 // so that sub-process commands run via the test binary see them as well.
511 for _, name := range []string{
512 // If we are collecting coverage profiles, e.g. `go test -coverprofile`.
513 "GOCOVERDIR",
514 // If the user set GORACE when running a command like `go test -race`,
515 // such as GORACE=atexit_sleep_ms=10 to avoid the default 1s sleeps.
516 "GORACE",
517 } {
518 if val := os.Getenv(name); val != "" {
519 env.Vars = append(env.Vars, name+"="+val)
520 }
521 }
522 if runtime.GOOS == "windows" {
523 env.Vars = append(env.Vars, "exe=.exe")
524 } else {
525 env.Vars = append(env.Vars, "exe=")
526 }
527 ts.cd = env.Cd
528 // Unpack archive.
529 a, err := txtar.ParseFile(ts.file)
530 ts.Check(err)
531 ts.archive = a
532 for _, f := range a.Files {
533 name := ts.MkAbs(ts.expand(f.Name))
534 ts.scriptFiles[name] = f.Name
535 ts.Check(os.MkdirAll(filepath.Dir(name), 0o777))
536 switch err := writeFile(name, f.Data, 0o666, ts.params.RequireUniqueNames); {
537 case ts.params.RequireUniqueNames && errors.Is(err, fs.ErrExist):
538 ts.Check(fmt.Errorf("%s would overwrite %s (because RequireUniqueNames is enabled)", f.Name, name))
539 default:
540 ts.Check(err)
541 }
542 }
543 // Run any user-defined setup.
544 if ts.params.Setup != nil {
545 ts.Check(ts.params.Setup(env))
546 }
547 ts.cd = env.Cd
548 ts.env = env.Vars
549 ts.values = env.Values
550
551 ts.envMap = make(map[string]string)
552 for _, kv := range ts.env {
553 if before, after, ok := strings.Cut(kv, "="); ok {
554 ts.envMap[envvarname(before)] = after
555 }
556 }
557 return string(a.Comment)
558 }
559
560 // run runs the test script.
561 func (ts *TestScript) run() {
562 // Truncate log at end of last phase marker,
563 // discarding details of successful phase.
564 verbose := ts.t.Verbose()
565 rewind := func() {
566 if !verbose {
567 ts.log.Truncate(ts.mark)
568 }
569 }
570
571 // Insert elapsed time for phase at end of phase marker
572 markTime := func() {
573 if ts.mark > 0 && !ts.start.IsZero() {
574 afterMark := slices.Clone(ts.log.Bytes()[ts.mark:])
575 ts.log.Truncate(ts.mark - 1) // cut \n and afterMark
576 fmt.Fprintf(&ts.log, " (%.3fs)\n", timeSince(ts.start).Seconds())
577 ts.log.Write(afterMark)
578 }
579 ts.start = time.Time{}
580 }
581
582 failed := false
583
584 // lastBlockFailed tracks the failure state of the last block.
585 // This allows us to rewind the last block if it didn't fail,
586 // but an earlier block _did_ fail, in the case of ContinueOnError.
587 lastBlockFailed := false
588
589 defer func() {
590 // On a normal exit from the test loop, background processes are cleaned up
591 // before we print PASS. If we return early (e.g., due to a test failure),
592 // don't print anything about the processes that were still running.
593 for _, bg := range ts.background {
594 interruptProcess(bg.cmd.Process)
595 }
596 if ts.t.Verbose() || failed {
597 // In verbose mode or on test failure, we want to see what happened in the background
598 // processes too.
599 ts.waitBackground(false)
600 } else {
601 for _, bg := range ts.background {
602 <-bg.wait
603 }
604 ts.background = nil
605 }
606
607 markTime()
608 // Flush testScript log to testing.T log.
609 ts.t.Log(ts.abbrev(ts.log.String()))
610 }()
611 defer func() {
612 ts.deferred()
613 }()
614 script := ts.setup()
615
616 // With -v or -testwork, start log with full environment.
617 if *testWork || (showVerboseEnv && ts.t.Verbose()) {
618 // Display environment.
619 ts.cmdEnv(false, nil)
620 fmt.Fprintf(&ts.log, "\n")
621 ts.mark = ts.log.Len()
622 }
623 defer ts.applyScriptUpdates()
624
625 // Run script.
626 // See testdata/script/README for documentation of script form.
627 for script != "" {
628 // Extract next line.
629 ts.lineno++
630 var line string
631 if before, after, ok := strings.Cut(script, "\n"); ok {
632 line, script = before, after
633 } else {
634 line, script = script, ""
635 }
636
637 // # is a comment indicating the start of new phase.
638 if strings.HasPrefix(line, "#") {
639 // If there was a previous phase, it succeeded,
640 // so rewind the log to delete its details (unless -v is in use or
641 // ContinueOnError was enabled and there was a previous error,
642 // causing verbose to be set to true).
643 // If nothing has happened at all since the mark,
644 // rewinding is a no-op and adding elapsed time
645 // for doing nothing is meaningless, so don't.
646 if ts.log.Len() > ts.mark {
647 rewind()
648 markTime()
649 }
650
651 // "Reset" verbose in the case that we are using ContinueOnError
652 // so that the next block only shows verbose output in case it
653 // is also in error. This ensures that later blocks that are not
654 // in error, do not needlessly show verbose output because of an
655 // earlier block that was in error.
656 verbose = ts.t.Verbose()
657 lastBlockFailed = false
658
659 // Print phase heading and mark start of phase output.
660 fmt.Fprintf(&ts.log, "%s\n", line)
661 ts.mark = ts.log.Len()
662 ts.start = time.Now()
663 continue
664 }
665
666 ok := ts.runLine(line)
667 if !ok {
668 failed = true
669 lastBlockFailed = true
670 if ts.params.ContinueOnError {
671 verbose = true
672 } else {
673 ts.t.FailNow()
674 }
675 }
676
677 // Command can ask script to stop early.
678 if ts.stopped {
679 // Break instead of returning, so that we check the status of any
680 // background processes and print PASS.
681 break
682 }
683 }
684
685 for _, bg := range ts.background {
686 interruptProcess(bg.cmd.Process)
687 }
688 // On some platforms like Windows, we kill background commands directly
689 // as we can't send them an interrupt signal, so they always fail.
690 // Moreover, it's relatively common for a process to fail when interrupted.
691 // Once we've reached the end of the script, ignore the status of background commands.
692 ts.waitBackground(false)
693
694 if !lastBlockFailed {
695 rewind()
696 }
697
698 // If we reached here but we've failed (probably because ContinueOnError
699 // was set), don't wipe the log and print "PASS".
700 if failed {
701 ts.t.FailNow()
702 }
703
704 // Final phase ended.
705 markTime()
706 if !ts.stopped {
707 fmt.Fprintf(&ts.log, "PASS\n")
708 }
709 }
710
711 func (ts *TestScript) runLine(line string) (runOK bool) {
712 defer catchFailNow(func() {
713 runOK = false
714 })
715
716 // Parse input line. Ignore blanks entirely.
717 args := ts.parse(line)
718 if len(args) == 0 {
719 return true
720 }
721
722 // Echo command to log.
723 fmt.Fprintf(&ts.log, "> %s\n", line)
724
725 // Command prefix [cond] means only run this command if cond is satisfied.
726 for strings.HasPrefix(args[0], "[") && strings.HasSuffix(args[0], "]") {
727 cond := args[0]
728 cond = cond[1 : len(cond)-1]
729 cond = strings.TrimSpace(cond)
730 args = args[1:]
731 if len(args) == 0 {
732 ts.Fatalf("missing command after condition")
733 }
734 want := true
735 if strings.HasPrefix(cond, "!") {
736 want = false
737 cond = strings.TrimSpace(cond[1:])
738 }
739 ok, err := ts.condition(cond)
740 if err != nil {
741 ts.Fatalf("bad condition %q: %v", cond, err)
742 }
743 if ok != want {
744 // Don't run rest of line.
745 return true
746 }
747 }
748
749 // Command prefix ! means negate the expectations about this command:
750 // go command should fail, match should not be found, etc.
751 neg := false
752 if args[0] == "!" {
753 neg = true
754 args = args[1:]
755 if len(args) == 0 {
756 ts.Fatalf("! on line by itself")
757 }
758 }
759
760 // Run command. Builtins take precedence, then commands registered
761 // for this test via SetCmd, then the static Params.Cmds.
762 cmd := scriptCmds[args[0]]
763 if cmd == nil {
764 cmd = ts.localCmds[args[0]]
765 }
766 if cmd == nil {
767 cmd = ts.params.Cmds[args[0]]
768 }
769 if cmd == nil {
770 // try to find spelling corrections. We arbitrarily limit the number of
771 // corrections, to not be too noisy.
772 switch c := ts.cmdSuggestions(args[0]); len(c) {
773 case 1:
774 ts.Fatalf("unknown command %q (did you mean %q?)", args[0], c[0])
775 case 2, 3, 4:
776 ts.Fatalf("unknown command %q (did you mean one of %q?)", args[0], c)
777 default:
778 ts.Fatalf("unknown command %q", args[0])
779 }
780 }
781 ts.callBuiltinCmd(func() {
782 cmd(ts, neg, args[1:])
783 })
784 return true
785 }
786
787 func (ts *TestScript) callBuiltinCmd(runCmd func()) {
788 ts.runningBuiltin = true
789 defer func() {
790 r := recover()
791 ts.runningBuiltin = false
792 ts.clearBuiltinStd()
793 switch r {
794 case nil:
795 // we did not panic
796 default:
797 // re-"throw" the panic
798 panic(r)
799 }
800 }()
801 runCmd()
802 }
803
804 func (ts *TestScript) cmdSuggestions(name string) []string {
805 // special case: spell-correct `!cmd` to `! cmd`
806 if strings.HasPrefix(name, "!") {
807 if _, ok := scriptCmds[name[1:]]; ok {
808 return []string{"! " + name[1:]}
809 }
810 if _, ok := ts.localCmds[name[1:]]; ok {
811 return []string{"! " + name[1:]}
812 }
813 if _, ok := ts.params.Cmds[name[1:]]; ok {
814 return []string{"! " + name[1:]}
815 }
816 }
817 var candidates []string
818 for c := range scriptCmds {
819 if misspell.AlmostEqual(name, c) {
820 candidates = append(candidates, c)
821 }
822 }
823 for c := range ts.localCmds {
824 if misspell.AlmostEqual(name, c) {
825 candidates = append(candidates, c)
826 }
827 }
828 for c := range ts.params.Cmds {
829 if misspell.AlmostEqual(name, c) {
830 candidates = append(candidates, c)
831 }
832 }
833 if len(candidates) == 0 {
834 return nil
835 }
836 // deduplicate candidates
837 slices.Sort(candidates)
838 return slices.Compact(candidates)
839 }
840
841 func (ts *TestScript) applyScriptUpdates() {
842 if len(ts.scriptUpdates) == 0 {
843 return
844 }
845 for name, content := range ts.scriptUpdates {
846 found := false
847 for i := range ts.archive.Files {
848 f := &ts.archive.Files[i]
849 if f.Name != name {
850 continue
851 }
852 data := []byte(content)
853 if txtar.NeedsQuote(data) {
854 data1, err := txtar.Quote(data)
855 if err != nil {
856 ts.Fatalf("cannot update script file %q: %v", f.Name, err)
857 continue
858 }
859 data = data1
860 }
861 f.Data = data
862 found = true
863 }
864 // Sanity check.
865 if !found {
866 panic("script update file not found")
867 }
868 }
869 if err := os.WriteFile(ts.file, txtar.Format(ts.archive), 0o666); err != nil {
870 ts.t.Fatal("cannot update script: ", err)
871 }
872 ts.Logf("%s updated", ts.file)
873 }
874
875 var failNow = errors.New("fail now!")
876
877 // catchFailNow catches any panic from Fatalf and calls
878 // f if it did so. It must be called in a defer.
879 func catchFailNow(f func()) {
880 e := recover()
881 if e == nil {
882 return
883 }
884 if e != failNow {
885 panic(e)
886 }
887 f()
888 }
889
890 // condition reports whether the given condition is satisfied.
891 func (ts *TestScript) condition(cond string) (bool, error) {
892 switch {
893 case cond == "short":
894 return testing.Short(), nil
895 case cond == "net":
896 return testenv.HasExternalNetwork(), nil
897 case cond == "link":
898 return testenv.HasLink(), nil
899 case cond == "symlink":
900 return testenv.HasSymlink(), nil
901 case imports.KnownOS[cond]:
902 return cond == runtime.GOOS, nil
903 case cond == "unix":
904 return imports.UnixOS[runtime.GOOS], nil
905 case imports.KnownArch[cond]:
906 return cond == runtime.GOARCH, nil
907 case strings.HasPrefix(cond, "exec:"):
908 prog := cond[len("exec:"):]
909 ok := execCache.Do(prog, func() any {
910 _, err := execpath.Look(prog, ts.Getenv)
911 return err == nil
912 }).(bool)
913 return ok, nil
914 case cond == "gc" || cond == "gccgo":
915 // TODO this reflects the compiler that the current
916 // binary was built with but not necessarily the compiler
917 // that will be used.
918 return cond == runtime.Compiler, nil
919 case goVersionRegex.MatchString(cond):
920 if slices.Contains(build.Default.ReleaseTags, cond) {
921 return true, nil
922 }
923 return false, nil
924 case ts.params.Condition != nil:
925 return ts.params.Condition(cond)
926 default:
927 ts.Fatalf("unknown condition %q", cond)
928 panic("unreachable")
929 }
930 }
931
932 // Helpers for command implementations.
933
934 // abbrev abbreviates the actual work directory in the string s to the literal string "$WORK".
935 func (ts *TestScript) abbrev(s string) string {
936 s = strings.Replace(s, ts.workdir, "$WORK", -1)
937 if *testWork || ts.params.TestWork {
938 // Expose actual $WORK value in environment dump on first line of work script,
939 // so that the user can find out what directory -testwork left behind.
940 s = "WORK=" + ts.workdir + "\n" + strings.TrimPrefix(s, "WORK=$WORK\n")
941 }
942 return s
943 }
944
945 // Defer arranges for f to be called at the end
946 // of the test. If Defer is called multiple times, the
947 // defers are executed in reverse order (similar
948 // to Go's defer statement)
949 func (ts *TestScript) Defer(f func()) {
950 old := ts.deferred
951 ts.deferred = func() {
952 defer old()
953 f()
954 }
955 }
956
957 // Check calls ts.Fatalf if err != nil.
958 func (ts *TestScript) Check(err error) {
959 if err != nil {
960 ts.Fatalf("%v", err)
961 }
962 }
963
964 // Stdout returns an io.Writer that can be used by a user-supplied builtin
965 // command (declared via Params.Cmds) to write to stdout. If this method is
966 // called outside of the execution of a user-supplied builtin command, the
967 // call panics.
968 func (ts *TestScript) Stdout() io.Writer {
969 if !ts.runningBuiltin {
970 panic("can only call TestScript.Stdout when running a builtin command")
971 }
972 ts.setBuiltinStd()
973 return ts.builtinStdout
974 }
975
976 // Stderr returns an io.Writer that can be used by a user-supplied builtin
977 // command (declared via Params.Cmds) to write to stderr. If this method is
978 // called outside of the execution of a user-supplied builtin command, the
979 // call panics.
980 func (ts *TestScript) Stderr() io.Writer {
981 if !ts.runningBuiltin {
982 panic("can only call TestScript.Stderr when running a builtin command")
983 }
984 ts.setBuiltinStd()
985 return ts.builtinStderr
986 }
987
988 // setBuiltinStd ensures that builtinStdout and builtinStderr are non nil.
989 func (ts *TestScript) setBuiltinStd() {
990 // This method must maintain the invariant that both builtinStdout and
991 // builtinStderr are set or neither are set
992
993 // If both are set, nothing to do
994 if ts.builtinStdout != nil && ts.builtinStderr != nil {
995 return
996 }
997 ts.builtinStdout = new(strings.Builder)
998 ts.builtinStderr = new(strings.Builder)
999 }
1000
1001 // clearBuiltinStd sets ts.stdout and ts.stderr from the builtin command
1002 // buffers, logs both, and resets both builtinStdout and builtinStderr to nil.
1003 func (ts *TestScript) clearBuiltinStd() {
1004 // This method must maintain the invariant that both builtinStdout and
1005 // builtinStderr are set or neither are set
1006
1007 // If neither set, nothing to do
1008 if ts.builtinStdout == nil && ts.builtinStderr == nil {
1009 return
1010 }
1011 ts.stdout = ts.builtinStdout.String()
1012 ts.builtinStdout = nil
1013 ts.stderr = ts.builtinStderr.String()
1014 ts.builtinStderr = nil
1015 ts.logStd()
1016 }
1017
1018 // Logf appends the given formatted message to the test log transcript.
1019 func (ts *TestScript) Logf(format string, args ...any) {
1020 format = strings.TrimSuffix(format, "\n")
1021 fmt.Fprintf(&ts.log, format, args...)
1022 ts.log.WriteByte('\n')
1023 }
1024
1025 // exec runs the given command line (an actual subprocess, not simulated)
1026 // in ts.cd with environment ts.env and then returns collected standard output and standard error.
1027 func (ts *TestScript) exec(command string, args ...string) (stdout, stderr string, err error) {
1028 cmd, err := ts.buildExecCmd(command, args...)
1029 if err != nil {
1030 return "", "", err
1031 }
1032 cmd.Dir = ts.cd
1033 cmd.Env = append(ts.env, "PWD="+ts.cd)
1034 cmd.Stdin = strings.NewReader(ts.stdin)
1035 var stdoutBuf, stderrBuf strings.Builder
1036 cmd.Stdout = &stdoutBuf
1037 cmd.Stderr = &stderrBuf
1038 if ts.ttyin != "" {
1039 ctrl, tty, err := pty.Open()
1040 if err != nil {
1041 return "", "", err
1042 }
1043 doneR, doneW := make(chan struct{}), make(chan struct{})
1044 var ptyBuf strings.Builder
1045 go func() {
1046 io.Copy(ctrl, strings.NewReader(ts.ttyin))
1047 ctrl.Write([]byte{4 /* EOT */})
1048 close(doneW)
1049 }()
1050 go func() {
1051 io.Copy(&ptyBuf, ctrl)
1052 close(doneR)
1053 }()
1054 defer func() {
1055 tty.Close()
1056 ctrl.Close()
1057 <-doneR
1058 <-doneW
1059 ts.ttyin = ""
1060 ts.ttyout = ptyBuf.String()
1061 }()
1062 pty.SetCtty(cmd, tty)
1063 if ts.stdinPty {
1064 cmd.Stdin = tty
1065 }
1066 }
1067 if err = cmd.Start(); err == nil {
1068 err = waitOrStop(ts.ctxt, cmd, ts.gracePeriod)
1069 }
1070 ts.stdin = ""
1071 ts.stdinPty = false
1072 return stdoutBuf.String(), stderrBuf.String(), err
1073 }
1074
1075 // execBackground starts the given command line (an actual subprocess, not simulated)
1076 // in ts.cd with environment ts.env.
1077 func (ts *TestScript) execBackground(command string, args ...string) (*exec.Cmd, error) {
1078 if ts.ttyin != "" {
1079 return nil, errors.New("ttyin is not supported by background commands")
1080 }
1081 cmd, err := ts.buildExecCmd(command, args...)
1082 if err != nil {
1083 return nil, err
1084 }
1085 cmd.Dir = ts.cd
1086 cmd.Env = append(ts.env, "PWD="+ts.cd)
1087 var stdoutBuf, stderrBuf strings.Builder
1088 cmd.Stdin = strings.NewReader(ts.stdin)
1089 cmd.Stdout = &stdoutBuf
1090 cmd.Stderr = &stderrBuf
1091 ts.stdin = ""
1092 return cmd, cmd.Start()
1093 }
1094
1095 func (ts *TestScript) buildExecCmd(command string, args ...string) (*exec.Cmd, error) {
1096 if filepath.Base(command) == command {
1097 if lp, err := execpath.Look(command, ts.Getenv); err != nil {
1098 return nil, err
1099 } else {
1100 command = lp
1101 }
1102 }
1103 return exec.Command(command, args...), nil
1104 }
1105
1106 // BackgroundCmds returns a slice containing all the commands that have
1107 // been started in the background since the most recent wait command, or
1108 // the start of the script if wait has not been called.
1109 func (ts *TestScript) BackgroundCmds() []*exec.Cmd {
1110 cmds := make([]*exec.Cmd, len(ts.background))
1111 for i, b := range ts.background {
1112 cmds[i] = b.cmd
1113 }
1114 return cmds
1115 }
1116
1117 // Chdir changes the current directory of the script.
1118 // The path may be relative to the current directory.
1119 func (ts *TestScript) Chdir(dir string) error {
1120 if !filepath.IsAbs(dir) {
1121 dir = filepath.Join(ts.cd, dir)
1122 }
1123 info, err := os.Stat(dir)
1124 if err != nil {
1125 return err
1126 }
1127 if !info.IsDir() {
1128 return fmt.Errorf("%s is not a directory", dir)
1129 }
1130
1131 ts.cd = dir
1132 return nil
1133 }
1134
1135 // waitOrStop waits for the already-started command cmd by calling its Wait method.
1136 //
1137 // If cmd does not return before ctx is done, waitOrStop sends it an interrupt
1138 // signal. If killDelay is positive, waitOrStop waits that additional period for
1139 // Wait to return before sending os.Kill.
1140 func waitOrStop(ctx context.Context, cmd *exec.Cmd, killDelay time.Duration) error {
1141 if cmd.Process == nil {
1142 panic("waitOrStop called with a nil cmd.Process — missing Start call?")
1143 }
1144
1145 errc := make(chan error)
1146 go func() {
1147 select {
1148 case errc <- nil:
1149 return
1150 case <-ctx.Done():
1151 }
1152
1153 var interrupt os.Signal = syscall.SIGQUIT
1154 if runtime.GOOS == "windows" {
1155 // Per https://golang.org/pkg/os/#Signal, “Interrupt is not implemented on
1156 // Windows; using it with os.Process.Signal will return an error.”
1157 // Fall back directly to Kill instead.
1158 interrupt = os.Kill
1159 }
1160
1161 err := cmd.Process.Signal(interrupt)
1162 if err == nil {
1163 err = ctx.Err() // Report ctx.Err() as the reason we interrupted.
1164 } else if err == os.ErrProcessDone {
1165 errc <- nil
1166 return
1167 }
1168
1169 if killDelay > 0 {
1170 timer := time.NewTimer(killDelay)
1171 select {
1172 // Report ctx.Err() as the reason we interrupted the process...
1173 case errc <- ctx.Err():
1174 timer.Stop()
1175 return
1176 // ...but after killDelay has elapsed, fall back to a stronger signal.
1177 case <-timer.C:
1178 }
1179
1180 // Wait still hasn't returned.
1181 // Kill the process harder to make sure that it exits.
1182 //
1183 // Ignore any error: if cmd.Process has already terminated, we still
1184 // want to send ctx.Err() (or the error from the Interrupt call)
1185 // to properly attribute the signal that may have terminated it.
1186 _ = cmd.Process.Kill()
1187 }
1188
1189 errc <- err
1190 }()
1191
1192 waitErr := cmd.Wait()
1193 if interruptErr := <-errc; interruptErr != nil {
1194 return interruptErr
1195 }
1196 return waitErr
1197 }
1198
1199 // interruptProcess sends os.Interrupt to p if supported, or os.Kill otherwise.
1200 func interruptProcess(p *os.Process) {
1201 if err := p.Signal(os.Interrupt); err != nil {
1202 // Per https://golang.org/pkg/os/#Signal, “Interrupt is not implemented on
1203 // Windows; using it with os.Process.Signal will return an error.”
1204 // Fall back to Kill instead.
1205 p.Kill()
1206 }
1207 }
1208
1209 // Exec runs the given command and saves its stdout and stderr so
1210 // they can be inspected by subsequent script commands.
1211 func (ts *TestScript) Exec(command string, args ...string) error {
1212 var err error
1213 ts.stdout, ts.stderr, err = ts.exec(command, args...)
1214 ts.logStd()
1215 return err
1216 }
1217
1218 // logStd logs the current non-empty values of stdout and stderr.
1219 func (ts *TestScript) logStd() {
1220 if ts.stdout != "" {
1221 ts.Logf("[stdout]\n%s", ts.stdout)
1222 }
1223 if ts.stderr != "" {
1224 ts.Logf("[stderr]\n%s", ts.stderr)
1225 }
1226 }
1227
1228 // expand applies environment variable expansion to the string s.
1229 func (ts *TestScript) expand(s string) string {
1230 return os.Expand(s, func(key string) string {
1231 if key1 := strings.TrimSuffix(key, "@R"); len(key1) != len(key) {
1232 return regexp.QuoteMeta(ts.Getenv(key1))
1233 }
1234 return ts.Getenv(key)
1235 })
1236 }
1237
1238 // fatalf aborts the test with the given failure message.
1239 func (ts *TestScript) Fatalf(format string, args ...any) {
1240 // In user-supplied builtins, the only way we have of aborting
1241 // is via Fatalf. Hence if we are aborting from a user-supplied
1242 // builtin, it's important we first log stdout and stderr. If
1243 // we are not, the following call is a no-op.
1244 ts.clearBuiltinStd()
1245
1246 fmt.Fprintf(&ts.log, "FAIL: %s:%d: %s\n", ts.file, ts.lineno, fmt.Sprintf(format, args...))
1247 // This should be caught by the defer inside the TestScript.runLine method.
1248 // We do this rather than calling ts.t.FailNow directly because we want to
1249 // be able to continue on error when Params.ContinueOnError is set.
1250 panic(failNow)
1251 }
1252
1253 // MkAbs interprets file relative to the test script's current directory
1254 // and returns the corresponding absolute path.
1255 func (ts *TestScript) MkAbs(file string) string {
1256 if filepath.IsAbs(file) {
1257 return file
1258 }
1259 return filepath.Join(ts.cd, file)
1260 }
1261
1262 // ReadFile returns the contents of the file with the
1263 // given name, interpreted relative to the test script's
1264 // current directory. It interprets "stdout" and "stderr" to
1265 // mean the standard output or standard error from
1266 // the most recent exec or wait command respectively.
1267 //
1268 // If the file cannot be read, the script fails.
1269 func (ts *TestScript) ReadFile(file string) string {
1270 switch file {
1271 case "stdout":
1272 return ts.stdout
1273 case "stderr":
1274 return ts.stderr
1275 case "ttyout":
1276 return ts.ttyout
1277 default:
1278 file = ts.MkAbs(file)
1279 data, err := os.ReadFile(file)
1280 ts.Check(err)
1281 return string(data)
1282 }
1283 }
1284
1285 // Setenv sets the value of the environment variable named by the key.
1286 func (ts *TestScript) Setenv(key, value string) {
1287 ts.env = append(ts.env, key+"="+value)
1288 ts.envMap[envvarname(key)] = value
1289 }
1290
1291 // Getenv gets the value of the environment variable named by the key.
1292 func (ts *TestScript) Getenv(key string) string {
1293 return ts.envMap[envvarname(key)]
1294 }
1295
1296 // parse parses a single line as a list of space-separated arguments
1297 // subject to environment variable expansion (but not resplitting).
1298 // Single quotes around text disable splitting and expansion.
1299 // To embed a single quote, double it: 'Don”t communicate by sharing memory.'
1300 func (ts *TestScript) parse(line string) []string {
1301 ts.line = line
1302
1303 var (
1304 args []string
1305 arg string // text of current arg so far (need to add line[start:i])
1306 start = -1 // if >= 0, position where current arg text chunk starts
1307 quoted = false // currently processing quoted text
1308 )
1309 for i := 0; ; i++ {
1310 if !quoted && (i >= len(line) || line[i] == ' ' || line[i] == '\t' || line[i] == '\r' || line[i] == '#') {
1311 // Found arg-separating space.
1312 if start >= 0 {
1313 arg += ts.expand(line[start:i])
1314 args = append(args, arg)
1315 start = -1
1316 arg = ""
1317 }
1318 if i >= len(line) || line[i] == '#' {
1319 break
1320 }
1321 continue
1322 }
1323 if i >= len(line) {
1324 ts.Fatalf("unterminated quoted argument")
1325 }
1326 if line[i] == '\'' {
1327 if !quoted {
1328 // starting a quoted chunk
1329 if start >= 0 {
1330 arg += ts.expand(line[start:i])
1331 }
1332 start = i + 1
1333 quoted = true
1334 continue
1335 }
1336 // 'foo''bar' means foo'bar, like in rc shell and Pascal.
1337 if i+1 < len(line) && line[i+1] == '\'' {
1338 arg += line[start:i]
1339 start = i + 1
1340 i++ // skip over second ' before next iteration
1341 continue
1342 }
1343 // ending a quoted chunk
1344 arg += line[start:i]
1345 start = i + 1
1346 quoted = false
1347 continue
1348 }
1349 // found character worth saving; make sure we're saving
1350 if start < 0 {
1351 start = i
1352 }
1353 }
1354 return args
1355 }
1356
1357 func removeAll(dir string) error {
1358 // module cache has 0o444 directories;
1359 // make them writable in order to remove content.
1360 filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error {
1361 if err != nil {
1362 return nil // ignore errors walking in file system
1363 }
1364 if entry.IsDir() {
1365 os.Chmod(path, 0o777)
1366 }
1367 return nil
1368 })
1369 return os.RemoveAll(dir)
1370 }
1371
1372 func homeEnvName() string {
1373 switch runtime.GOOS {
1374 case "windows":
1375 return "USERPROFILE"
1376 case "plan9":
1377 return "home"
1378 default:
1379 return "HOME"
1380 }
1381 }
1382
1383 func tempEnvName() string {
1384 switch runtime.GOOS {
1385 case "windows":
1386 return "TMP"
1387 case "plan9":
1388 return "TMPDIR" // actually plan 9 doesn't have one at all but this is fine
1389 default:
1390 return "TMPDIR"
1391 }
1392 }