github.com/klaytn/klaytn@v1.10.2/cmd/utils/testcmd.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2017 The go-ethereum Authors 3 // This file is part of go-ethereum. 4 // 5 // go-ethereum is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU 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 // go-ethereum 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 General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from cmd/cmdtest/test_cmd.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package utils 22 23 import ( 24 "bufio" 25 "bytes" 26 "fmt" 27 "io" 28 "io/ioutil" 29 "os" 30 "os/exec" 31 "regexp" 32 "strings" 33 "sync" 34 "testing" 35 "text/template" 36 "time" 37 38 "github.com/docker/docker/pkg/reexec" 39 ) 40 41 func NewTestCmd(t *testing.T, data interface{}) *TestCmd { 42 return &TestCmd{T: t, Data: data} 43 } 44 45 type TestCmd struct { 46 // For total convenience, all testing methods are available. 47 *testing.T 48 49 Func template.FuncMap 50 Data interface{} 51 Cleanup func() 52 53 cmd *exec.Cmd 54 stdout *bufio.Reader 55 stdin io.WriteCloser 56 stderr *testlogger 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. "klay-test" in cmd/utils/nodecmd/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 // klay.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.cmd.Wait() 190 } 191 192 func (tt *TestCmd) Interrupt() { 193 tt.cmd.Process.Signal(os.Interrupt) 194 } 195 196 // StderrText returns any stderr output written so far. 197 // The returned text holds all log lines after ExpectExit has 198 // returned. 199 func (tt *TestCmd) StderrText() string { 200 tt.stderr.mu.Lock() 201 defer tt.stderr.mu.Unlock() 202 return tt.stderr.buf.String() 203 } 204 205 func (tt *TestCmd) CloseStdin() { 206 tt.stdin.Close() 207 } 208 209 func (tt *TestCmd) Kill() { 210 tt.cmd.Process.Kill() 211 if tt.Cleanup != nil { 212 tt.Cleanup() 213 } 214 } 215 216 func (tt *TestCmd) withKillTimeout(fn func()) { 217 timeout := time.AfterFunc(10*time.Second, func() { 218 tt.Log("killing the child process (timeout)") 219 tt.Kill() 220 }) 221 defer timeout.Stop() 222 fn() 223 } 224 225 // testlogger logs all written lines via t.Log and also 226 // collects them for later inspection. 227 type testlogger struct { 228 t *testing.T 229 mu sync.Mutex 230 buf bytes.Buffer 231 } 232 233 func (tl *testlogger) Write(b []byte) (n int, err error) { 234 lines := bytes.Split(b, []byte("\n")) 235 for _, line := range lines { 236 if len(line) > 0 { 237 tl.t.Logf("(stderr) %s", line) 238 } 239 } 240 tl.mu.Lock() 241 tl.buf.Write(b) 242 tl.mu.Unlock() 243 return len(b), err 244 } 245 246 // runeTee collects text read through it into buf. 247 type runeTee struct { 248 in interface { 249 io.Reader 250 io.ByteReader 251 io.RuneReader 252 } 253 buf bytes.Buffer 254 } 255 256 func (rtee *runeTee) Read(b []byte) (n int, err error) { 257 n, err = rtee.in.Read(b) 258 rtee.buf.Write(b[:n]) 259 return n, err 260 } 261 262 func (rtee *runeTee) ReadRune() (r rune, size int, err error) { 263 r, size, err = rtee.in.ReadRune() 264 if err == nil { 265 rtee.buf.WriteRune(r) 266 } 267 return r, size, err 268 } 269 270 func (rtee *runeTee) ReadByte() (b byte, err error) { 271 b, err = rtee.in.ReadByte() 272 if err == nil { 273 rtee.buf.WriteByte(b) 274 } 275 return b, err 276 }