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