/
script_test.go
1448 lines (1312 loc) · 38.4 KB
/
script_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Script-driven tests.
// See testdata/script/README for an overview.
package main_test
import (
"bytes"
"context"
"errors"
"fmt"
"go/build"
"internal/testenv"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"cmd/go/internal/cfg"
"cmd/go/internal/imports"
"cmd/go/internal/par"
"cmd/go/internal/robustio"
"cmd/go/internal/txtar"
"cmd/go/internal/work"
"cmd/internal/objabi"
"cmd/internal/sys"
)
// TestScript runs the tests in testdata/script/*.txt.
func TestScript(t *testing.T) {
testenv.MustHaveGoBuild(t)
testenv.SkipIfShortAndSlow(t)
files, err := filepath.Glob("testdata/script/*.txt")
if err != nil {
t.Fatal(err)
}
for _, file := range files {
file := file
name := strings.TrimSuffix(filepath.Base(file), ".txt")
t.Run(name, func(t *testing.T) {
t.Parallel()
ts := &testScript{t: t, name: name, file: file}
ts.setup()
if !*testWork {
defer removeAll(ts.workdir)
}
ts.run()
})
}
}
// A testScript holds execution state for a single test script.
type testScript struct {
t *testing.T
workdir string // temporary work dir ($WORK)
log bytes.Buffer // test execution log (printed at end of test)
mark int // offset of next log truncation
cd string // current directory during test execution; initially $WORK/gopath/src
name string // short name of test ("foo")
file string // full file name ("testdata/script/foo.txt")
lineno int // line number currently executing
line string // line currently executing
env []string // environment list (for os/exec)
envMap map[string]string // environment mapping (matches env)
stdout string // standard output from last 'go' command; for 'stdout' command
stderr string // standard error from last 'go' command; for 'stderr' command
stopped bool // test wants to stop early
start time.Time // time phase started
background []*backgroundCmd // backgrounded 'exec' and 'go' commands
}
type backgroundCmd struct {
want simpleStatus
args []string
cancel context.CancelFunc
done <-chan struct{}
err error
stdout, stderr strings.Builder
}
type simpleStatus string
const (
success simpleStatus = ""
failure simpleStatus = "!"
successOrFailure simpleStatus = "?"
)
var extraEnvKeys = []string{
"SYSTEMROOT", // must be preserved on Windows to find DLLs; golang.org/issue/25210
"WINDIR", // must be preserved on Windows to be able to run PowerShell command; golang.org/issue/30711
"LD_LIBRARY_PATH", // must be preserved on Unix systems to find shared libraries
"CC", // don't lose user settings when invoking cgo
"GO_TESTING_GOTOOLS", // for gccgo testing
"GCCGO", // for gccgo testing
"GCCGOTOOLDIR", // for gccgo testing
}
// setup sets up the test execution temporary directory and environment.
func (ts *testScript) setup() {
StartProxy()
ts.workdir = filepath.Join(testTmpDir, "script-"+ts.name)
ts.check(os.MkdirAll(filepath.Join(ts.workdir, "tmp"), 0777))
ts.check(os.MkdirAll(filepath.Join(ts.workdir, "gopath/src"), 0777))
ts.cd = filepath.Join(ts.workdir, "gopath/src")
ts.env = []string{
"WORK=" + ts.workdir, // must be first for ts.abbrev
"PATH=" + testBin + string(filepath.ListSeparator) + os.Getenv("PATH"),
homeEnvName() + "=/no-home",
"CCACHE_DISABLE=1", // ccache breaks with non-existent HOME
"GOARCH=" + runtime.GOARCH,
"GOCACHE=" + testGOCACHE,
"GODEBUG=" + os.Getenv("GODEBUG"),
"GOEXE=" + cfg.ExeSuffix,
"GOEXPSTRING=" + objabi.Expstring()[2:],
"GOOS=" + runtime.GOOS,
"GOPATH=" + filepath.Join(ts.workdir, "gopath"),
"GOPROXY=" + proxyURL,
"GOPRIVATE=",
"GOROOT=" + testGOROOT,
"GOROOT_FINAL=" + os.Getenv("GOROOT_FINAL"), // causes spurious rebuilds and breaks the "stale" built-in if not propagated
"TESTGO_GOROOT=" + testGOROOT,
"GOSUMDB=" + testSumDBVerifierKey,
"GONOPROXY=",
"GONOSUMDB=",
"GOVCS=*:all",
"PWD=" + ts.cd,
tempEnvName() + "=" + filepath.Join(ts.workdir, "tmp"),
"devnull=" + os.DevNull,
"goversion=" + goVersion(ts),
":=" + string(os.PathListSeparator),
}
if !testenv.HasExternalNetwork() {
ts.env = append(ts.env, "TESTGONETWORK=panic", "TESTGOVCS=panic")
}
if runtime.GOOS == "plan9" {
ts.env = append(ts.env, "path="+testBin+string(filepath.ListSeparator)+os.Getenv("path"))
}
for _, key := range extraEnvKeys {
if val := os.Getenv(key); val != "" {
ts.env = append(ts.env, key+"="+val)
}
}
ts.envMap = make(map[string]string)
for _, kv := range ts.env {
if i := strings.Index(kv, "="); i >= 0 {
ts.envMap[kv[:i]] = kv[i+1:]
}
}
}
// goVersion returns the current Go version.
func goVersion(ts *testScript) string {
tags := build.Default.ReleaseTags
version := tags[len(tags)-1]
if !regexp.MustCompile(`^go([1-9][0-9]*)\.(0|[1-9][0-9]*)$`).MatchString(version) {
ts.fatalf("invalid go version %q", version)
}
return version[2:]
}
var execCache par.Cache
// run runs the test script.
func (ts *testScript) run() {
// Truncate log at end of last phase marker,
// discarding details of successful phase.
rewind := func() {
if !testing.Verbose() {
ts.log.Truncate(ts.mark)
}
}
// Insert elapsed time for phase at end of phase marker
markTime := func() {
if ts.mark > 0 && !ts.start.IsZero() {
afterMark := append([]byte{}, ts.log.Bytes()[ts.mark:]...)
ts.log.Truncate(ts.mark - 1) // cut \n and afterMark
fmt.Fprintf(&ts.log, " (%.3fs)\n", time.Since(ts.start).Seconds())
ts.log.Write(afterMark)
}
ts.start = time.Time{}
}
defer func() {
// On a normal exit from the test loop, background processes are cleaned up
// before we print PASS. If we return early (e.g., due to a test failure),
// don't print anything about the processes that were still running.
for _, bg := range ts.background {
bg.cancel()
}
for _, bg := range ts.background {
<-bg.done
}
ts.background = nil
markTime()
// Flush testScript log to testing.T log.
ts.t.Log("\n" + ts.abbrev(ts.log.String()))
}()
// Unpack archive.
a, err := txtar.ParseFile(ts.file)
ts.check(err)
for _, f := range a.Files {
name := ts.mkabs(ts.expand(f.Name, false))
ts.check(os.MkdirAll(filepath.Dir(name), 0777))
ts.check(os.WriteFile(name, f.Data, 0666))
}
// With -v or -testwork, start log with full environment.
if *testWork || testing.Verbose() {
// Display environment.
ts.cmdEnv(success, nil)
fmt.Fprintf(&ts.log, "\n")
ts.mark = ts.log.Len()
}
// Run script.
// See testdata/script/README for documentation of script form.
script := string(a.Comment)
Script:
for script != "" {
// Extract next line.
ts.lineno++
var line string
if i := strings.Index(script, "\n"); i >= 0 {
line, script = script[:i], script[i+1:]
} else {
line, script = script, ""
}
// # is a comment indicating the start of new phase.
if strings.HasPrefix(line, "#") {
// If there was a previous phase, it succeeded,
// so rewind the log to delete its details (unless -v is in use).
// If nothing has happened at all since the mark,
// rewinding is a no-op and adding elapsed time
// for doing nothing is meaningless, so don't.
if ts.log.Len() > ts.mark {
rewind()
markTime()
}
// Print phase heading and mark start of phase output.
fmt.Fprintf(&ts.log, "%s\n", line)
ts.mark = ts.log.Len()
ts.start = time.Now()
continue
}
// Parse input line. Ignore blanks entirely.
parsed := ts.parse(line)
if parsed.name == "" {
if parsed.want != "" || len(parsed.conds) > 0 {
ts.fatalf("missing command")
}
continue
}
// Echo command to log.
fmt.Fprintf(&ts.log, "> %s\n", line)
for _, cond := range parsed.conds {
// Known conds are: $GOOS, $GOARCH, runtime.Compiler, and 'short' (for testing.Short).
//
// NOTE: If you make changes here, update testdata/script/README too!
//
ok := false
switch cond.tag {
case runtime.GOOS, runtime.GOARCH, runtime.Compiler:
ok = true
case "short":
ok = testing.Short()
case "cgo":
ok = canCgo
case "msan":
ok = canMSan
case "race":
ok = canRace
case "net":
ok = testenv.HasExternalNetwork()
case "link":
ok = testenv.HasLink()
case "root":
ok = os.Geteuid() == 0
case "symlink":
ok = testenv.HasSymlink()
case "case-sensitive":
ok = isCaseSensitive(ts.t)
default:
if strings.HasPrefix(cond.tag, "exec:") {
prog := cond.tag[len("exec:"):]
ok = execCache.Do(prog, func() interface{} {
if runtime.GOOS == "plan9" && prog == "git" {
// The Git command is usually not the real Git on Plan 9.
// See https://golang.org/issues/29640.
return false
}
_, err := exec.LookPath(prog)
return err == nil
}).(bool)
break
}
if strings.HasPrefix(cond.tag, "GODEBUG:") {
value := strings.TrimPrefix(cond.tag, "GODEBUG:")
parts := strings.Split(os.Getenv("GODEBUG"), ",")
for _, p := range parts {
if strings.TrimSpace(p) == value {
ok = true
break
}
}
break
}
if strings.HasPrefix(cond.tag, "buildmode:") {
value := strings.TrimPrefix(cond.tag, "buildmode:")
ok = sys.BuildModeSupported(runtime.Compiler, value, runtime.GOOS, runtime.GOARCH)
break
}
if !imports.KnownArch[cond.tag] && !imports.KnownOS[cond.tag] && cond.tag != "gc" && cond.tag != "gccgo" {
ts.fatalf("unknown condition %q", cond.tag)
}
}
if ok != cond.want {
// Don't run rest of line.
continue Script
}
}
// Run command.
cmd := scriptCmds[parsed.name]
if cmd == nil {
ts.fatalf("unknown command %q", parsed.name)
}
cmd(ts, parsed.want, parsed.args)
// Command can ask script to stop early.
if ts.stopped {
// Break instead of returning, so that we check the status of any
// background processes and print PASS.
break
}
}
for _, bg := range ts.background {
bg.cancel()
}
ts.cmdWait(success, nil)
// Final phase ended.
rewind()
markTime()
if !ts.stopped {
fmt.Fprintf(&ts.log, "PASS\n")
}
}
var (
onceCaseSensitive sync.Once
caseSensitive bool
)
func isCaseSensitive(t *testing.T) bool {
onceCaseSensitive.Do(func() {
tmpdir, err := os.MkdirTemp("", "case-sensitive")
if err != nil {
t.Fatal("failed to create directory to determine case-sensitivity:", err)
}
defer os.RemoveAll(tmpdir)
fcap := filepath.Join(tmpdir, "FILE")
if err := os.WriteFile(fcap, []byte{}, 0644); err != nil {
t.Fatal("error writing file to determine case-sensitivity:", err)
}
flow := filepath.Join(tmpdir, "file")
_, err = os.ReadFile(flow)
switch {
case err == nil:
caseSensitive = false
return
case os.IsNotExist(err):
caseSensitive = true
return
default:
t.Fatal("unexpected error reading file when determining case-sensitivity:", err)
}
})
return caseSensitive
}
// scriptCmds are the script command implementations.
// Keep list and the implementations below sorted by name.
//
// NOTE: If you make changes here, update testdata/script/README too!
//
var scriptCmds = map[string]func(*testScript, simpleStatus, []string){
"addcrlf": (*testScript).cmdAddcrlf,
"cc": (*testScript).cmdCc,
"cd": (*testScript).cmdCd,
"chmod": (*testScript).cmdChmod,
"cmp": (*testScript).cmdCmp,
"cmpenv": (*testScript).cmdCmpenv,
"cp": (*testScript).cmdCp,
"env": (*testScript).cmdEnv,
"exec": (*testScript).cmdExec,
"exists": (*testScript).cmdExists,
"go": (*testScript).cmdGo,
"grep": (*testScript).cmdGrep,
"mkdir": (*testScript).cmdMkdir,
"rm": (*testScript).cmdRm,
"skip": (*testScript).cmdSkip,
"stale": (*testScript).cmdStale,
"stderr": (*testScript).cmdStderr,
"stdout": (*testScript).cmdStdout,
"stop": (*testScript).cmdStop,
"symlink": (*testScript).cmdSymlink,
"wait": (*testScript).cmdWait,
}
// When expanding shell variables for these commands, we apply regexp quoting to
// expanded strings within the first argument.
var regexpCmd = map[string]bool{
"grep": true,
"stderr": true,
"stdout": true,
}
// addcrlf adds CRLF line endings to the named files.
func (ts *testScript) cmdAddcrlf(want simpleStatus, args []string) {
if len(args) == 0 {
ts.fatalf("usage: addcrlf file...")
}
for _, file := range args {
file = ts.mkabs(file)
data, err := os.ReadFile(file)
ts.check(err)
ts.check(os.WriteFile(file, bytes.ReplaceAll(data, []byte("\n"), []byte("\r\n")), 0666))
}
}
// cc runs the C compiler along with platform specific options.
func (ts *testScript) cmdCc(want simpleStatus, args []string) {
if len(args) < 1 || (len(args) == 1 && args[0] == "&") {
ts.fatalf("usage: cc args... [&]")
}
var b work.Builder
b.Init()
ts.cmdExec(want, append(b.GccCmd(".", ""), args...))
robustio.RemoveAll(b.WorkDir)
}
// cd changes to a different directory.
func (ts *testScript) cmdCd(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v cd", want)
}
if len(args) != 1 {
ts.fatalf("usage: cd dir")
}
dir := args[0]
if !filepath.IsAbs(dir) {
dir = filepath.Join(ts.cd, dir)
}
info, err := os.Stat(dir)
if os.IsNotExist(err) {
ts.fatalf("directory %s does not exist", dir)
}
ts.check(err)
if !info.IsDir() {
ts.fatalf("%s is not a directory", dir)
}
ts.cd = dir
ts.envMap["PWD"] = dir
fmt.Fprintf(&ts.log, "%s\n", ts.cd)
}
// chmod changes permissions for a file or directory.
func (ts *testScript) cmdChmod(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v chmod", want)
}
if len(args) < 2 {
ts.fatalf("usage: chmod perm paths...")
}
perm, err := strconv.ParseUint(args[0], 0, 32)
if err != nil || perm&uint64(fs.ModePerm) != perm {
ts.fatalf("invalid mode: %s", args[0])
}
for _, arg := range args[1:] {
path := arg
if !filepath.IsAbs(path) {
path = filepath.Join(ts.cd, arg)
}
err := os.Chmod(path, fs.FileMode(perm))
ts.check(err)
}
}
// cmp compares two files.
func (ts *testScript) cmdCmp(want simpleStatus, args []string) {
if want != success {
// It would be strange to say "this file can have any content except this precise byte sequence".
ts.fatalf("unsupported: %v cmp", want)
}
quiet := false
if len(args) > 0 && args[0] == "-q" {
quiet = true
args = args[1:]
}
if len(args) != 2 {
ts.fatalf("usage: cmp file1 file2")
}
ts.doCmdCmp(args, false, quiet)
}
// cmpenv compares two files with environment variable substitution.
func (ts *testScript) cmdCmpenv(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v cmpenv", want)
}
quiet := false
if len(args) > 0 && args[0] == "-q" {
quiet = true
args = args[1:]
}
if len(args) != 2 {
ts.fatalf("usage: cmpenv file1 file2")
}
ts.doCmdCmp(args, true, quiet)
}
func (ts *testScript) doCmdCmp(args []string, env, quiet bool) {
name1, name2 := args[0], args[1]
var text1, text2 string
if name1 == "stdout" {
text1 = ts.stdout
} else if name1 == "stderr" {
text1 = ts.stderr
} else {
data, err := os.ReadFile(ts.mkabs(name1))
ts.check(err)
text1 = string(data)
}
data, err := os.ReadFile(ts.mkabs(name2))
ts.check(err)
text2 = string(data)
if env {
text1 = ts.expand(text1, false)
text2 = ts.expand(text2, false)
}
if text1 == text2 {
return
}
if !quiet {
fmt.Fprintf(&ts.log, "[diff -%s +%s]\n%s\n", name1, name2, diff(text1, text2))
}
ts.fatalf("%s and %s differ", name1, name2)
}
// cp copies files, maybe eventually directories.
func (ts *testScript) cmdCp(want simpleStatus, args []string) {
if len(args) < 2 {
ts.fatalf("usage: cp src... dst")
}
dst := ts.mkabs(args[len(args)-1])
info, err := os.Stat(dst)
dstDir := err == nil && info.IsDir()
if len(args) > 2 && !dstDir {
ts.fatalf("cp: destination %s is not a directory", dst)
}
for _, arg := range args[:len(args)-1] {
var (
src string
data []byte
mode fs.FileMode
)
switch arg {
case "stdout":
src = arg
data = []byte(ts.stdout)
mode = 0666
case "stderr":
src = arg
data = []byte(ts.stderr)
mode = 0666
default:
src = ts.mkabs(arg)
info, err := os.Stat(src)
ts.check(err)
mode = info.Mode() & 0777
data, err = os.ReadFile(src)
ts.check(err)
}
targ := dst
if dstDir {
targ = filepath.Join(dst, filepath.Base(src))
}
err := os.WriteFile(targ, data, mode)
switch want {
case failure:
if err == nil {
ts.fatalf("unexpected command success")
}
case success:
ts.check(err)
}
}
}
// env displays or adds to the environment.
func (ts *testScript) cmdEnv(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v env", want)
}
conv := func(s string) string { return s }
if len(args) > 0 && args[0] == "-r" {
conv = regexp.QuoteMeta
args = args[1:]
}
var out strings.Builder
if len(args) == 0 {
printed := make(map[string]bool) // env list can have duplicates; only print effective value (from envMap) once
for _, kv := range ts.env {
k := kv[:strings.Index(kv, "=")]
if !printed[k] {
fmt.Fprintf(&out, "%s=%s\n", k, ts.envMap[k])
}
}
} else {
for _, env := range args {
i := strings.Index(env, "=")
if i < 0 {
// Display value instead of setting it.
fmt.Fprintf(&out, "%s=%s\n", env, ts.envMap[env])
continue
}
key, val := env[:i], conv(env[i+1:])
ts.env = append(ts.env, key+"="+val)
ts.envMap[key] = val
}
}
if out.Len() > 0 || len(args) > 0 {
ts.stdout = out.String()
ts.log.WriteString(out.String())
}
}
// exec runs the given command.
func (ts *testScript) cmdExec(want simpleStatus, args []string) {
if len(args) < 1 || (len(args) == 1 && args[0] == "&") {
ts.fatalf("usage: exec program [args...] [&]")
}
background := false
if len(args) > 0 && args[len(args)-1] == "&" {
background = true
args = args[:len(args)-1]
}
bg, err := ts.startBackground(want, args[0], args[1:]...)
if err != nil {
ts.fatalf("unexpected error starting command: %v", err)
}
if background {
ts.stdout, ts.stderr = "", ""
ts.background = append(ts.background, bg)
return
}
<-bg.done
ts.stdout = bg.stdout.String()
ts.stderr = bg.stderr.String()
if ts.stdout != "" {
fmt.Fprintf(&ts.log, "[stdout]\n%s", ts.stdout)
}
if ts.stderr != "" {
fmt.Fprintf(&ts.log, "[stderr]\n%s", ts.stderr)
}
if bg.err != nil {
fmt.Fprintf(&ts.log, "[%v]\n", bg.err)
}
ts.checkCmd(bg)
}
// exists checks that the list of files exists.
func (ts *testScript) cmdExists(want simpleStatus, args []string) {
if want == successOrFailure {
ts.fatalf("unsupported: %v exists", want)
}
var readonly, exec bool
loop:
for len(args) > 0 {
switch args[0] {
case "-readonly":
readonly = true
args = args[1:]
case "-exec":
exec = true
args = args[1:]
default:
break loop
}
}
if len(args) == 0 {
ts.fatalf("usage: exists [-readonly] [-exec] file...")
}
for _, file := range args {
file = ts.mkabs(file)
info, err := os.Stat(file)
if err == nil && want == failure {
what := "file"
if info.IsDir() {
what = "directory"
}
ts.fatalf("%s %s unexpectedly exists", what, file)
}
if err != nil && want == success {
ts.fatalf("%s does not exist", file)
}
if err == nil && want == success && readonly && info.Mode()&0222 != 0 {
ts.fatalf("%s exists but is writable", file)
}
if err == nil && want == success && exec && runtime.GOOS != "windows" && info.Mode()&0111 == 0 {
ts.fatalf("%s exists but is not executable", file)
}
}
}
// go runs the go command.
func (ts *testScript) cmdGo(want simpleStatus, args []string) {
ts.cmdExec(want, append([]string{testGo}, args...))
}
// mkdir creates directories.
func (ts *testScript) cmdMkdir(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v mkdir", want)
}
if len(args) < 1 {
ts.fatalf("usage: mkdir dir...")
}
for _, arg := range args {
ts.check(os.MkdirAll(ts.mkabs(arg), 0777))
}
}
// rm removes files or directories.
func (ts *testScript) cmdRm(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v rm", want)
}
if len(args) < 1 {
ts.fatalf("usage: rm file...")
}
for _, arg := range args {
file := ts.mkabs(arg)
removeAll(file) // does chmod and then attempts rm
ts.check(robustio.RemoveAll(file)) // report error
}
}
// skip marks the test skipped.
func (ts *testScript) cmdSkip(want simpleStatus, args []string) {
if len(args) > 1 {
ts.fatalf("usage: skip [msg]")
}
if want != success {
ts.fatalf("unsupported: %v skip", want)
}
// Before we mark the test as skipped, shut down any background processes and
// make sure they have returned the correct status.
for _, bg := range ts.background {
bg.cancel()
}
ts.cmdWait(success, nil)
if len(args) == 1 {
ts.t.Skip(args[0])
}
ts.t.Skip()
}
// stale checks that the named build targets are stale.
func (ts *testScript) cmdStale(want simpleStatus, args []string) {
if len(args) == 0 {
ts.fatalf("usage: stale target...")
}
tmpl := "{{if .Error}}{{.ImportPath}}: {{.Error.Err}}{{else}}"
switch want {
case failure:
tmpl += "{{if .Stale}}{{.ImportPath}} is unexpectedly stale{{end}}"
case success:
tmpl += "{{if not .Stale}}{{.ImportPath}} is unexpectedly NOT stale{{end}}"
default:
ts.fatalf("unsupported: %v stale", want)
}
tmpl += "{{end}}"
goArgs := append([]string{"list", "-e", "-f=" + tmpl}, args...)
stdout, stderr, err := ts.exec(testGo, goArgs...)
if err != nil {
ts.fatalf("go list: %v\n%s%s", err, stdout, stderr)
}
if stdout != "" {
ts.fatalf("%s", stdout)
}
}
// stdout checks that the last go command standard output matches a regexp.
func (ts *testScript) cmdStdout(want simpleStatus, args []string) {
scriptMatch(ts, want, args, ts.stdout, "stdout")
}
// stderr checks that the last go command standard output matches a regexp.
func (ts *testScript) cmdStderr(want simpleStatus, args []string) {
scriptMatch(ts, want, args, ts.stderr, "stderr")
}
// grep checks that file content matches a regexp.
// Like stdout/stderr and unlike Unix grep, it accepts Go regexp syntax.
func (ts *testScript) cmdGrep(want simpleStatus, args []string) {
scriptMatch(ts, want, args, "", "grep")
}
// scriptMatch implements both stdout and stderr.
func scriptMatch(ts *testScript, want simpleStatus, args []string, text, name string) {
if want == successOrFailure {
ts.fatalf("unsupported: %v %s", want, name)
}
n := 0
if len(args) >= 1 && strings.HasPrefix(args[0], "-count=") {
if want == failure {
ts.fatalf("cannot use -count= with negated match")
}
var err error
n, err = strconv.Atoi(args[0][len("-count="):])
if err != nil {
ts.fatalf("bad -count=: %v", err)
}
if n < 1 {
ts.fatalf("bad -count=: must be at least 1")
}
args = args[1:]
}
quiet := false
if len(args) >= 1 && args[0] == "-q" {
quiet = true
args = args[1:]
}
extraUsage := ""
wantArgs := 1
if name == "grep" {
extraUsage = " file"
wantArgs = 2
}
if len(args) != wantArgs {
ts.fatalf("usage: %s [-count=N] 'pattern'%s", name, extraUsage)
}
pattern := `(?m)` + args[0]
re, err := regexp.Compile(pattern)
if err != nil {
ts.fatalf("regexp.Compile(%q): %v", pattern, err)
}
isGrep := name == "grep"
if isGrep {
name = args[1] // for error messages
data, err := os.ReadFile(ts.mkabs(args[1]))
ts.check(err)
text = string(data)
}
// Matching against workdir would be misleading.
text = strings.ReplaceAll(text, ts.workdir, "$WORK")
switch want {
case failure:
if re.MatchString(text) {
if isGrep && !quiet {
fmt.Fprintf(&ts.log, "[%s]\n%s\n", name, text)
}
ts.fatalf("unexpected match for %#q found in %s: %s", pattern, name, re.FindString(text))
}
case success:
if !re.MatchString(text) {
if isGrep && !quiet {
fmt.Fprintf(&ts.log, "[%s]\n%s\n", name, text)
}
ts.fatalf("no match for %#q found in %s", pattern, name)
}
if n > 0 {
count := len(re.FindAllString(text, -1))
if count != n {
if isGrep && !quiet {
fmt.Fprintf(&ts.log, "[%s]\n%s\n", name, text)
}
ts.fatalf("have %d matches for %#q, want %d", count, pattern, n)
}
}
}
}
// stop stops execution of the test (marking it passed).
func (ts *testScript) cmdStop(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v stop", want)
}
if len(args) > 1 {
ts.fatalf("usage: stop [msg]")
}
if len(args) == 1 {
fmt.Fprintf(&ts.log, "stop: %s\n", args[0])
} else {
fmt.Fprintf(&ts.log, "stop\n")
}
ts.stopped = true
}
// symlink creates a symbolic link.
func (ts *testScript) cmdSymlink(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v symlink", want)
}
if len(args) != 3 || args[1] != "->" {
ts.fatalf("usage: symlink file -> target")
}
// Note that the link target args[2] is not interpreted with mkabs:
// it will be interpreted relative to the directory file is in.
ts.check(os.Symlink(args[2], ts.mkabs(args[0])))
}
// wait waits for background commands to exit, setting stderr and stdout to their result.
func (ts *testScript) cmdWait(want simpleStatus, args []string) {
if want != success {
ts.fatalf("unsupported: %v wait", want)
}
if len(args) > 0 {
ts.fatalf("usage: wait")
}
var stdouts, stderrs []string
for _, bg := range ts.background {
<-bg.done
args := append([]string{filepath.Base(bg.args[0])}, bg.args[1:]...)
fmt.Fprintf(&ts.log, "[background] %s: %v\n", strings.Join(args, " "), bg.err)
cmdStdout := bg.stdout.String()
if cmdStdout != "" {
fmt.Fprintf(&ts.log, "[stdout]\n%s", cmdStdout)
stdouts = append(stdouts, cmdStdout)
}
cmdStderr := bg.stderr.String()
if cmdStderr != "" {
fmt.Fprintf(&ts.log, "[stderr]\n%s", cmdStderr)
stderrs = append(stderrs, cmdStderr)
}
ts.checkCmd(bg)
}
ts.stdout = strings.Join(stdouts, "")
ts.stderr = strings.Join(stderrs, "")
ts.background = nil
}
// Helpers for command implementations.