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