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