1
2
3
4
5
6 package scripttest
7
8 import (
9 "bufio"
10 "cmd/go/internal/cfg"
11 "cmd/go/internal/script"
12 "errors"
13 "io"
14 "strings"
15 "testing"
16 )
17
18
19
20
21
22
23 func DefaultCmds() map[string]script.Cmd {
24 cmds := script.DefaultCmds()
25 cmds["skip"] = Skip()
26 return cmds
27 }
28
29
30
31
32
33
34
35
36
37
38
39
40
41 func DefaultConds() map[string]script.Cond {
42 conds := script.DefaultConds()
43 conds["exec"] = CachedExec()
44 conds["short"] = script.BoolCondition("testing.Short()", testing.Short())
45 conds["verbose"] = script.BoolCondition("testing.Verbose()", testing.Verbose())
46 return conds
47 }
48
49
50
51 func Run(t testing.TB, e *script.Engine, s *script.State, filename string, testScript io.Reader) {
52 t.Helper()
53 err := func() (err error) {
54 log := new(strings.Builder)
55 log.WriteString("\n")
56
57
58
59 t.Helper()
60 defer func() {
61 t.Helper()
62
63 if closeErr := s.CloseAndWait(log); err == nil {
64 err = closeErr
65 }
66
67 if log.Len() > 0 {
68 t.Log(strings.TrimSuffix(log.String(), "\n"))
69 }
70 }()
71
72 if testing.Verbose() {
73
74 wait, err := script.Env().Run(s)
75 if err != nil {
76 t.Fatal(err)
77 }
78 if wait != nil {
79 stdout, stderr, err := wait(s)
80 if err != nil {
81 t.Fatalf("env: %v\n%s", err, stderr)
82 }
83 if len(stdout) > 0 {
84 s.Logf("%s\n", stdout)
85 }
86 }
87 }
88
89 return e.Execute(s, filename, bufio.NewReader(testScript), log)
90 }()
91
92 if skip := (skipError{}); errors.As(err, &skip) {
93 if skip.msg == "" {
94 t.Skip("SKIP")
95 } else {
96 t.Skipf("SKIP: %v", skip.msg)
97 }
98 }
99 if err != nil {
100 t.Errorf("FAIL: %v", err)
101 }
102 }
103
104
105 func Skip() script.Cmd {
106 return script.Command(
107 script.CmdUsage{
108 Summary: "skip the current test",
109 Args: "[msg]",
110 },
111 func(_ *script.State, args ...string) (script.WaitFunc, error) {
112 if len(args) > 1 {
113 return nil, script.ErrUsage
114 }
115 if len(args) == 0 {
116 return nil, skipError{""}
117 }
118 return nil, skipError{args[0]}
119 })
120 }
121
122 type skipError struct {
123 msg string
124 }
125
126 func (s skipError) Error() string {
127 if s.msg == "" {
128 return "skip"
129 }
130 return s.msg
131 }
132
133
134
135
136 func CachedExec() script.Cond {
137 return script.CachedCondition(
138 "<suffix> names an executable in the test binary's PATH",
139 func(name string) (bool, error) {
140 _, err := cfg.LookPath(name)
141 return err == nil, nil
142 })
143 }
144
View as plain text