Debian Codegraph @

testscript/testscript_test.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 package testscript
6
7 import (
8 "bytes"
9 "errors"
10 "flag"
11 "fmt"
12 "os"
13 "os/exec"
14 "os/signal"
15 "path/filepath"
16 "reflect"
17 "regexp"
18 "strconv"
19 "strings"
20 "testing"
21 "time"
22 )
23
24 func printArgs() {
25 fmt.Printf("%q\n", os.Args)
26 }
27
28 func fprintArgs() {
29 s := strings.Join(os.Args[2:], " ")
30 switch os.Args[1] {
31 case "stdout":
32 fmt.Println(s)
33 case "stderr":
34 fmt.Fprintln(os.Stderr, s)
35 }
36 }
37
38 func exitWithStatus() {
39 n, _ := strconv.Atoi(os.Args[1])
40 os.Exit(n)
41 }
42
43 func signalCatcher() {
44 // Note: won't work under Windows.
45 c := make(chan os.Signal, 1)
46 signal.Notify(c, os.Interrupt)
47 // Create a file so that the test can know that
48 // we will catch the signal.
49 if err := os.WriteFile("catchsignal", nil, 0o666); err != nil {
50 fmt.Println(err)
51 os.Exit(1)
52 }
53 <-c
54 fmt.Println("caught interrupt")
55 }
56
57 func terminalPrompt() {
58 tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
59 if err != nil {
60 fmt.Println(err)
61 os.Exit(1)
62 }
63 tty.WriteString("The magic words are: ")
64 var words string
65 fmt.Fscanln(tty, &words)
66 if words != "SQUEAMISHOSSIFRAGE" {
67 fmt.Println(words)
68 os.Exit(42)
69 }
70 }
71
72 func TestMain(m *testing.M) {
73 timeSince = func(t time.Time) time.Duration {
74 return 0
75 }
76
77 showVerboseEnv = false
78 Main(m, map[string]func(){
79 "printargs": printArgs,
80 "fprintargs": fprintArgs,
81 "status": exitWithStatus,
82 "signalcatcher": signalCatcher,
83 "terminalprompt": terminalPrompt,
84 })
85 }
86
87 func TestCRLFInput(t *testing.T) {
88 td := t.TempDir()
89 tf := filepath.Join(td, "script.txt")
90 contents := []byte("exists output.txt\r\n-- output.txt --\r\noutput contents")
91 if err := os.WriteFile(tf, contents, 0o644); err != nil {
92 t.Fatalf("failed to write to %v: %v", tf, err)
93 }
94 t.Run("_", func(t *testing.T) {
95 Run(t, Params{Dir: td})
96 })
97 }
98
99 func TestEnv(t *testing.T) {
100 e := &Env{
101 Vars: []string{
102 "HOME=/no-home",
103 "PATH=/usr/bin",
104 "PATH=/usr/bin:/usr/local/bin",
105 "INVALID",
106 },
107 }
108
109 if got, want := e.Getenv("HOME"), "/no-home"; got != want {
110 t.Errorf("e.Getenv(\"HOME\") == %q, want %q", got, want)
111 }
112
113 e.Setenv("HOME", "/home/user")
114 if got, want := e.Getenv("HOME"), "/home/user"; got != want {
115 t.Errorf(`e.Getenv("HOME") == %q, want %q`, got, want)
116 }
117
118 if got, want := e.Getenv("PATH"), "/usr/bin:/usr/local/bin"; got != want {
119 t.Errorf(`e.Getenv("PATH") == %q, want %q`, got, want)
120 }
121
122 if got, want := e.Getenv("INVALID"), ""; got != want {
123 t.Errorf(`e.Getenv("INVALID") == %q, want %q`, got, want)
124 }
125
126 for _, key := range []string{
127 "",
128 "=",
129 "key=invalid",
130 } {
131 var panicValue any
132 func() {
133 defer func() {
134 panicValue = recover()
135 }()
136 e.Setenv(key, "")
137 }()
138 if panicValue == nil {
139 t.Errorf("e.Setenv(%q) did not panic, want panic", key)
140 }
141 }
142 }
143
144 func TestSetupFailure(t *testing.T) {
145 dir := t.TempDir()
146 if err := os.WriteFile(filepath.Join(dir, "foo.txt"), nil, 0o666); err != nil {
147 t.Fatal(err)
148 }
149 ft := &fakeT{}
150 func() {
151 defer catchAbort()
152 RunT(ft, Params{
153 Dir: dir,
154 Setup: func(*Env) error {
155 return fmt.Errorf("some failure")
156 },
157 })
158 }()
159 if !ft.failed {
160 t.Fatal("test should have failed because of setup failure")
161 }
162
163 want := regexp.MustCompile(`\nFAIL: .*: some failure\n$`)
164 if got := ft.log.String(); !want.MatchString(got) {
165 t.Fatalf("expected msg to match `%v`; got:\n%q", want, got)
166 }
167 }
168
169 func TestScripts(t *testing.T) {
170 // TODO set temp directory.
171 testDeferCount := 0
172 Run(t, Params{
173 UpdateScripts: os.Getenv("TESTSCRIPT_UPDATE") != "",
174 Dir: "testdata",
175 Cmds: map[string]func(ts *TestScript, neg bool, args []string){
176 "setSpecialVal": setSpecialVal,
177 "ensureSpecialVal": ensureSpecialVal,
178 "register": func(ts *TestScript, neg bool, args []string) {
179 // register <name> <text> dynamically defines a command
180 // that writes <text> to stdout, for the rest of the test.
181 if len(args) != 2 {
182 ts.Fatalf("usage: register <name> <text>")
183 }
184 text := args[1]
185 ts.SetCmd(args[0], func(ts *TestScript, neg bool, args []string) {
186 fmt.Fprintln(ts.Stdout(), text)
187 })
188 },
189 "interrupt": interrupt,
190 "waitfile": waitFile,
191 "testdefer": func(ts *TestScript, neg bool, args []string) {
192 testDeferCount++
193 n := testDeferCount
194 ts.Defer(func() {
195 if testDeferCount != n {
196 t.Errorf("defers not run in reverse order; got %d want %d", testDeferCount, n)
197 }
198 testDeferCount--
199 })
200 },
201 "setup-filenames": func(ts *TestScript, neg bool, want []string) {
202 got := ts.Value("setupFilenames")
203 if !reflect.DeepEqual(want, got) {
204 ts.Fatalf("setup did not see expected files; got %q want %q", got, want)
205 }
206 },
207 "test-values": func(ts *TestScript, neg bool, args []string) {
208 if ts.Value("somekey") != 1234 {
209 ts.Fatalf("test-values did not see expected value")
210 }
211 if ts.Value("t").(T) != ts.t {
212 ts.Fatalf("test-values did not see expected t")
213 }
214 if _, ok := ts.Value("t").(testing.TB); !ok {
215 ts.Fatalf("test-values t does not implement testing.TB")
216 }
217 },
218 "testreadfile": func(ts *TestScript, neg bool, args []string) {
219 if len(args) != 1 {
220 ts.Fatalf("testreadfile <filename>")
221 }
222 got := ts.ReadFile(args[0])
223 want := args[0] + "\n"
224 if got != want {
225 ts.Fatalf("reading %q; got %q want %q", args[0], got, want)
226 }
227 },
228 "testscript": func(ts *TestScript, neg bool, args []string) {
229 // Run testscript in testscript. Oooh! Meta!
230 fset := flag.NewFlagSet("testscript", flag.ContinueOnError)
231 fUpdate := fset.Bool("update", false, "update scripts when cmp fails")
232 fExplicitExec := fset.Bool("explicit-exec", false, "require explicit use of exec for commands")
233 fUniqueNames := fset.Bool("unique-names", false, "require unique names in txtar archive")
234 fVerbose := fset.Bool("v", false, "be verbose with output")
235 fContinue := fset.Bool("continue", false, "continue on error")
236 fFiles := fset.Bool("files", false, "specify files rather than a directory")
237 if err := fset.Parse(args); err != nil {
238 ts.Fatalf("failed to parse args for testscript: %v", err)
239 }
240 if fset.NArg() != 1 && !*fFiles {
241 ts.Fatalf("testscript [-v] [-continue] [-update] [-explicit-exec] [-files] <dir>|<file>...")
242 }
243 var files []string
244 var dir string
245 if *fFiles {
246 for _, f := range fset.Args() {
247 files = append(files, ts.MkAbs(f))
248 }
249 } else {
250 dir = ts.MkAbs(fset.Arg(0))
251 }
252 t := &fakeT{verbose: *fVerbose}
253 func() {
254 defer catchAbort()
255 RunT(t, Params{
256 Dir: dir,
257 Files: files,
258 UpdateScripts: *fUpdate,
259 RequireExplicitExec: *fExplicitExec,
260 RequireUniqueNames: *fUniqueNames,
261 Cmds: map[string]func(ts *TestScript, neg bool, args []string){
262 "some-param-cmd": func(ts *TestScript, neg bool, args []string) {
263 },
264 "echoandexit": echoandexit,
265 },
266 ContinueOnError: *fContinue,
267 })
268 }()
269 stdout := t.log.String()
270 stdout = strings.ReplaceAll(stdout, ts.workdir, "$WORK")
271 fmt.Fprint(ts.Stdout(), stdout)
272 if neg {
273 if !t.failed {
274 ts.Fatalf("testscript unexpectedly succeeded")
275 }
276 return
277 }
278 if t.failed {
279 ts.Fatalf("testscript unexpectedly failed with errors: %q", &t.log)
280 }
281 },
282 "echoandexit": echoandexit,
283 "mkChdir": func(ts *TestScript, neg bool, args []string) {
284 if neg {
285 ts.Fatalf("unsupported: ! mkChdir")
286 }
287 if len(args) != 1 {
288 ts.Fatalf("usage: mkChdir dir")
289 }
290
291 dir := args[0]
292 if !filepath.IsAbs(dir) {
293 dir = ts.MkAbs(dir)
294 }
295
296 if err := os.MkdirAll(dir, 0o777); err != nil {
297 ts.Fatalf("cannot create dir: %v", err)
298 }
299
300 if err := ts.Chdir(dir); err != nil {
301 ts.Fatalf("cannot chdir: %v", err)
302 }
303 },
304 },
305 Setup: func(env *Env) error {
306 infos, err := os.ReadDir(env.WorkDir)
307 if err != nil {
308 return fmt.Errorf("cannot read workdir: %v", err)
309 }
310 var setupFilenames []string
311 for _, info := range infos {
312 setupFilenames = append(setupFilenames, info.Name())
313 }
314 env.Values["setupFilenames"] = setupFilenames
315 env.Values["somekey"] = 1234
316 env.Values["t"] = env.T()
317 env.Vars = append(env.Vars,
318 "GONOSUMDB=*",
319 )
320 return nil
321 },
322 })
323 if testDeferCount != 0 {
324 t.Fatalf("defer mismatch; got %d want 0", testDeferCount)
325 }
326 // TODO check that the temp directory has been removed.
327 }
328
329 func echoandexit(ts *TestScript, neg bool, args []string) {
330 // Takes at least one argument
331 //
332 // args[0] - int that indicates the exit code of the command
333 // args[1] - the string to echo to stdout if non-empty
334 // args[2] - the string to echo to stderr if non-empty
335 if len(args) == 0 || len(args) > 3 {
336 ts.Fatalf("echoandexit takes at least one and at most three arguments")
337 }
338 if neg {
339 ts.Fatalf("neg means nothing for echoandexit")
340 }
341 exitCode, err := strconv.ParseInt(args[0], 10, 64)
342 if err != nil {
343 ts.Fatalf("failed to parse exit code from %q: %v", args[0], err)
344 }
345 if len(args) > 1 && args[1] != "" {
346 fmt.Fprint(ts.Stdout(), args[1])
347 }
348 if len(args) > 2 && args[2] != "" {
349 fmt.Fprint(ts.Stderr(), args[2])
350 }
351 if exitCode != 0 {
352 ts.Fatalf("told to exit with code %d", exitCode)
353 }
354 }
355
356 // TestTestwork tests that using the flag -testwork will make sure the work dir isn't removed
357 // after the test is done. It uses an empty testscript file that doesn't do anything.
358 func TestTestwork(t *testing.T) {
359 out, err := exec.Command("go", "test", ".", "-testwork", "-v", "-run", "TestScripts/^nothing$").CombinedOutput()
360 if err != nil {
361 t.Fatal(err)
362 }
363
364 re := regexp.MustCompile(`\s+WORK=(\S+)`)
365 match := re.FindAllStringSubmatch(string(out), -1)
366
367 // Ensure that there is only one line with one match
368 if len(match) != 1 || len(match[0]) != 2 {
369 t.Fatalf("failed to extract WORK directory")
370 }
371
372 var fi os.FileInfo
373 if fi, err = os.Stat(match[0][1]); err != nil {
374 t.Fatalf("failed to stat expected work directory %v: %v", match[0][1], err)
375 }
376
377 if !fi.IsDir() {
378 t.Fatalf("expected persisted workdir is not a directory: %v", match[0][1])
379 }
380 }
381
382 // TestWorkdirRoot tests that a non zero value in Params.WorkdirRoot is honoured
383 func TestWorkdirRoot(t *testing.T) {
384 td := t.TempDir()
385 params := Params{
386 Dir: filepath.Join("testdata", "nothing"),
387 WorkdirRoot: td,
388 }
389 // Run as a sub-test so that this call blocks until the sub-tests created by
390 // calling Run (which themselves call t.Parallel) complete.
391 t.Run("run tests", func(t *testing.T) {
392 Run(t, params)
393 })
394 // Verify that we have a single go-test-script-* named directory
395 files, err := filepath.Glob(filepath.Join(td, "script-nothing", "README.md"))
396 if err != nil {
397 t.Fatal(err)
398 }
399 if len(files) != 1 {
400 t.Fatalf("unexpected files found for kept files; got %q", files)
401 }
402 }
403
404 // TestBadDir verifies that invoking testscript with a directory that either
405 // does not exist or that contains no *.txt scripts fails the test
406 func TestBadDir(t *testing.T) {
407 ft := new(fakeT)
408 func() {
409 defer catchAbort()
410 RunT(ft, Params{
411 Dir: "thiswillnevermatch",
412 })
413 }()
414 want := regexp.MustCompile(`no txtar nor txt scripts found in dir thiswillnevermatch`)
415 if got := ft.log.String(); !want.MatchString(got) {
416 t.Fatalf("expected msg to match `%v`; got:\n%v", want, got)
417 }
418 }
419
420 // catchAbort catches the panic raised by fakeT.FailNow.
421 func catchAbort() {
422 if err := recover(); err != nil && err != errAbort {
423 panic(err)
424 }
425 }
426
427 func TestUNIX2DOS(t *testing.T) {
428 for data, want := range map[string]string{
429 "": "", // Preserve empty files.
430 "\n": "\r\n", // Convert LF to CRLF in a file containing a single empty line.
431 "\r\n": "\r\n", // Preserve CRLF in a single line file.
432 "a": "a\r\n", // Append CRLF to a single line file with no line terminator.
433 "a\n": "a\r\n", // Convert LF to CRLF in a file containing a single non-empty line.
434 "a\r\n": "a\r\n", // Preserve CRLF in a file containing a single non-empty line.
435 "a\nb\n": "a\r\nb\r\n", // Convert LF to CRLF in multiline UNIX file.
436 "a\r\nb\n": "a\r\nb\r\n", // Convert LF to CRLF in a file containing a mix of UNIX and DOS lines.
437 "a\nb\r\n": "a\r\nb\r\n", // Convert LF to CRLF in a file containing a mix of UNIX and DOS lines.
438 } {
439 if got, err := unix2DOS([]byte(data)); err != nil || !bytes.Equal(got, []byte(want)) {
440 t.Errorf("unix2DOS(%q) == %q, %v, want %q, nil", data, got, err, want)
441 }
442 }
443 }
444
445 func setSpecialVal(ts *TestScript, neg bool, args []string) {
446 ts.Setenv("SPECIALVAL", "42")
447 }
448
449 func ensureSpecialVal(ts *TestScript, neg bool, args []string) {
450 want := "42"
451 if got := ts.Getenv("SPECIALVAL"); got != want {
452 ts.Fatalf("expected SPECIALVAL to be %q; got %q", want, got)
453 }
454 }
455
456 // interrupt interrupts the current background command.
457 // Note that this will not work under Windows.
458 func interrupt(ts *TestScript, neg bool, args []string) {
459 if neg {
460 ts.Fatalf("interrupt does not support neg")
461 }
462 if len(args) > 0 {
463 ts.Fatalf("unexpected args found")
464 }
465 bg := ts.BackgroundCmds()
466 if got, want := len(bg), 1; got != want {
467 ts.Fatalf("unexpected background cmd count; got %d want %d", got, want)
468 }
469 bg[0].Process.Signal(os.Interrupt)
470 }
471
472 func waitFile(ts *TestScript, neg bool, args []string) {
473 if neg {
474 ts.Fatalf("waitfile does not support neg")
475 }
476 if len(args) != 1 {
477 ts.Fatalf("usage: waitfile file")
478 }
479 path := ts.MkAbs(args[0])
480 for range 100 {
481 _, err := os.Stat(path)
482 if err == nil {
483 return
484 }
485 if !os.IsNotExist(err) {
486 ts.Fatalf("unexpected stat error: %v", err)
487 }
488 time.Sleep(10 * time.Millisecond)
489 }
490 ts.Fatalf("timed out waiting for %q to be created", path)
491 }
492
493 type fakeT struct {
494 log strings.Builder
495 verbose bool
496 failed bool
497 }
498
499 var errAbort = errors.New("abort test")
500
501 func (t *fakeT) Skip(args ...any) {
502 panic(errAbort)
503 }
504
505 func (t *fakeT) Fatal(args ...any) {
506 t.Log(args...)
507 t.FailNow()
508 }
509
510 func (t *fakeT) Parallel() {}
511
512 func (t *fakeT) Log(args ...any) {
513 fmt.Fprint(&t.log, args...)
514 }
515
516 func (t *fakeT) FailNow() {
517 t.failed = true
518 panic(errAbort)
519 }
520
521 func (t *fakeT) Run(name string, f func(T)) {
522 fmt.Fprintf(&t.log, "** RUN %s **\n", name)
523 defer catchAbort()
524 f(&subT{
525 fakeT: t,
526 })
527 }
528
529 func (t *fakeT) Verbose() bool {
530 return t.verbose
531 }
532
533 type subT struct {
534 *fakeT
535 failed bool
536 }
537
538 func (t *subT) Run(name string, f func(T)) {
539 panic("multiple test levels not supported")
540 }
541
542 func (t *subT) FailNow() {
543 t.failed = true
544 t.fakeT.FailNow()
545 }