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