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