github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/internal/cmdtest/test_cmd.go (about)

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