github.com/theQRL/go-zond@v0.1.1/internal/cmdtest/test_cmd.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package cmdtest 18 19 import ( 20 "bufio" 21 "bytes" 22 "fmt" 23 "io" 24 "os" 25 "os/exec" 26 "regexp" 27 "strings" 28 "sync" 29 "sync/atomic" 30 "syscall" 31 "testing" 32 "text/template" 33 "time" 34 35 "github.com/docker/docker/pkg/reexec" 36 ) 37 38 func NewTestCmd(t *testing.T, data interface{}) *TestCmd { 39 return &TestCmd{T: t, Data: data} 40 } 41 42 type TestCmd struct { 43 // For total convenience, all testing methods are available. 44 *testing.T 45 46 Func template.FuncMap 47 Data interface{} 48 Cleanup func() 49 50 cmd *exec.Cmd 51 stdout *bufio.Reader 52 stdin io.WriteCloser 53 stderr *testlogger 54 // Err will contain the process exit error or interrupt signal error 55 Err error 56 } 57 58 var id atomic.Int32 59 60 // Run exec's the current binary using name as argv[0] which will trigger the 61 // reexec init function for that name (e.g. "geth-test" in cmd/geth/run_test.go) 62 func (tt *TestCmd) Run(name string, args ...string) { 63 id.Add(1) 64 tt.stderr = &testlogger{t: tt.T, name: fmt.Sprintf("%d", id.Load())} 65 tt.cmd = &exec.Cmd{ 66 Path: reexec.Self(), 67 Args: append([]string{name}, args...), 68 Stderr: tt.stderr, 69 } 70 stdout, err := tt.cmd.StdoutPipe() 71 if err != nil { 72 tt.Fatal(err) 73 } 74 tt.stdout = bufio.NewReader(stdout) 75 if tt.stdin, err = tt.cmd.StdinPipe(); err != nil { 76 tt.Fatal(err) 77 } 78 if err := tt.cmd.Start(); err != nil { 79 tt.Fatal(err) 80 } 81 } 82 83 // InputLine writes the given text to the child's stdin. 84 // This method can also be called from an expect template, e.g.: 85 // 86 // geth.expect(`Passphrase: {{.InputLine "password"}}`) 87 func (tt *TestCmd) InputLine(s string) string { 88 io.WriteString(tt.stdin, s+"\n") 89 return "" 90 } 91 92 func (tt *TestCmd) SetTemplateFunc(name string, fn interface{}) { 93 if tt.Func == nil { 94 tt.Func = make(map[string]interface{}) 95 } 96 tt.Func[name] = fn 97 } 98 99 // Expect runs its argument as a template, then expects the 100 // child process to output the result of the template within 5s. 101 // 102 // If the template starts with a newline, the newline is removed 103 // before matching. 104 func (tt *TestCmd) Expect(tplsource string) { 105 // Generate the expected output by running the template. 106 tpl := template.Must(template.New("").Funcs(tt.Func).Parse(tplsource)) 107 wantbuf := new(bytes.Buffer) 108 if err := tpl.Execute(wantbuf, tt.Data); err != nil { 109 panic(err) 110 } 111 // Trim exactly one newline at the beginning. This makes tests look 112 // much nicer because all expect strings are at column 0. 113 want := bytes.TrimPrefix(wantbuf.Bytes(), []byte("\n")) 114 if err := tt.matchExactOutput(want); err != nil { 115 tt.Fatal(err) 116 } 117 tt.Logf("Matched stdout text:\n%s", want) 118 } 119 120 // Output reads all output from stdout, and returns the data. 121 func (tt *TestCmd) Output() []byte { 122 var buf []byte 123 tt.withKillTimeout(func() { buf, _ = io.ReadAll(tt.stdout) }) 124 return buf 125 } 126 127 func (tt *TestCmd) matchExactOutput(want []byte) error { 128 buf := make([]byte, len(want)) 129 n := 0 130 tt.withKillTimeout(func() { n, _ = io.ReadFull(tt.stdout, buf) }) 131 buf = buf[:n] 132 if n < len(want) || !bytes.Equal(buf, want) { 133 // Grab any additional buffered output in case of mismatch 134 // because it might help with debugging. 135 buf = append(buf, make([]byte, tt.stdout.Buffered())...) 136 tt.stdout.Read(buf[n:]) 137 // Find the mismatch position. 138 for i := 0; i < n; i++ { 139 if want[i] != buf[i] { 140 return fmt.Errorf("output mismatch at ā:\n---------------- (stdout text)\n%sā%s\n---------------- (expected text)\n%s", 141 buf[:i], buf[i:n], want) 142 } 143 } 144 if n < len(want) { 145 return fmt.Errorf("not enough output, got until ā:\n---------------- (stdout text)\n%s\n---------------- (expected text)\n%sā%s", 146 buf, want[:n], want[n:]) 147 } 148 } 149 return nil 150 } 151 152 // ExpectRegexp expects the child process to output text matching the 153 // given regular expression within 5s. 154 // 155 // Note that an arbitrary amount of output may be consumed by the 156 // regular expression. This usually means that expect cannot be used 157 // after ExpectRegexp. 158 func (tt *TestCmd) ExpectRegexp(regex string) (*regexp.Regexp, []string) { 159 regex = strings.TrimPrefix(regex, "\n") 160 var ( 161 re = regexp.MustCompile(regex) 162 rtee = &runeTee{in: tt.stdout} 163 matches []int 164 ) 165 tt.withKillTimeout(func() { matches = re.FindReaderSubmatchIndex(rtee) }) 166 output := rtee.buf.Bytes() 167 if matches == nil { 168 tt.Fatalf("Output did not match:\n---------------- (stdout text)\n%s\n---------------- (regular expression)\n%s", 169 output, regex) 170 return re, nil 171 } 172 tt.Logf("Matched stdout text:\n%s", output) 173 var submatches []string 174 for i := 0; i < len(matches); i += 2 { 175 submatch := string(output[matches[i]:matches[i+1]]) 176 submatches = append(submatches, submatch) 177 } 178 return re, submatches 179 } 180 181 // ExpectExit expects the child process to exit within 5s without 182 // printing any additional text on stdout. 183 func (tt *TestCmd) ExpectExit() { 184 var output []byte 185 tt.withKillTimeout(func() { 186 output, _ = io.ReadAll(tt.stdout) 187 }) 188 tt.WaitExit() 189 if tt.Cleanup != nil { 190 tt.Cleanup() 191 } 192 if len(output) > 0 { 193 tt.Errorf("Unmatched stdout text:\n%s", output) 194 } 195 } 196 197 func (tt *TestCmd) WaitExit() { 198 tt.Err = tt.cmd.Wait() 199 } 200 201 func (tt *TestCmd) Interrupt() { 202 tt.Err = tt.cmd.Process.Signal(os.Interrupt) 203 } 204 205 // ExitStatus exposes the process' OS exit code 206 // It will only return a valid value after the process has finished. 207 func (tt *TestCmd) ExitStatus() int { 208 if tt.Err != nil { 209 exitErr := tt.Err.(*exec.ExitError) 210 if exitErr != nil { 211 if status, ok := exitErr.Sys().(syscall.WaitStatus); ok { 212 return status.ExitStatus() 213 } 214 } 215 } 216 return 0 217 } 218 219 // StderrText returns any stderr output written so far. 220 // The returned text holds all log lines after ExpectExit has 221 // returned. 222 func (tt *TestCmd) StderrText() string { 223 tt.stderr.mu.Lock() 224 defer tt.stderr.mu.Unlock() 225 return tt.stderr.buf.String() 226 } 227 228 func (tt *TestCmd) CloseStdin() { 229 tt.stdin.Close() 230 } 231 232 func (tt *TestCmd) Kill() { 233 tt.cmd.Process.Kill() 234 if tt.Cleanup != nil { 235 tt.Cleanup() 236 } 237 } 238 239 func (tt *TestCmd) withKillTimeout(fn func()) { 240 timeout := time.AfterFunc(30*time.Second, func() { 241 tt.Log("killing the child process (timeout)") 242 tt.Kill() 243 }) 244 defer timeout.Stop() 245 fn() 246 } 247 248 // testlogger logs all written lines via t.Log and also 249 // collects them for later inspection. 250 type testlogger struct { 251 t *testing.T 252 mu sync.Mutex 253 buf bytes.Buffer 254 name string 255 } 256 257 func (tl *testlogger) Write(b []byte) (n int, err error) { 258 lines := bytes.Split(b, []byte("\n")) 259 for _, line := range lines { 260 if len(line) > 0 { 261 tl.t.Logf("(stderr:%v) %s", tl.name, line) 262 } 263 } 264 tl.mu.Lock() 265 tl.buf.Write(b) 266 tl.mu.Unlock() 267 return len(b), err 268 } 269 270 // runeTee collects text read through it into buf. 271 type runeTee struct { 272 in interface { 273 io.Reader 274 io.ByteReader 275 io.RuneReader 276 } 277 buf bytes.Buffer 278 } 279 280 func (rtee *runeTee) Read(b []byte) (n int, err error) { 281 n, err = rtee.in.Read(b) 282 rtee.buf.Write(b[:n]) 283 return n, err 284 } 285 286 func (rtee *runeTee) ReadRune() (r rune, size int, err error) { 287 r, size, err = rtee.in.ReadRune() 288 if err == nil { 289 rtee.buf.WriteRune(r) 290 } 291 return r, size, err 292 } 293 294 func (rtee *runeTee) ReadByte() (b byte, err error) { 295 b, err = rtee.in.ReadByte() 296 if err == nil { 297 rtee.buf.WriteByte(b) 298 } 299 return b, err 300 }