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