github.com/klaytn/klaytn@v1.12.1/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  	"os"
    29  	"os/exec"
    30  	"regexp"
    31  	"strings"
    32  	"sync"
    33  	"testing"
    34  	"text/template"
    35  	"time"
    36  
    37  	"github.com/docker/docker/pkg/reexec"
    38  )
    39  
    40  func NewTestCmd(t *testing.T, data interface{}) *TestCmd {
    41  	return &TestCmd{T: t, Data: data}
    42  }
    43  
    44  type TestCmd struct {
    45  	// For total convenience, all testing methods are available.
    46  	*testing.T
    47  
    48  	Func    template.FuncMap
    49  	Data    interface{}
    50  	Cleanup func()
    51  
    52  	cmd    *exec.Cmd
    53  	stdout *bufio.Reader
    54  	stdin  io.WriteCloser
    55  	stderr *testlogger
    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. "klay-test" in cmd/utils/nodecmd/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  //	klay.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, _ = io.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.cmd.Wait()
   189  }
   190  
   191  func (tt *TestCmd) Interrupt() {
   192  	tt.cmd.Process.Signal(os.Interrupt)
   193  }
   194  
   195  // StderrText returns any stderr output written so far.
   196  // The returned text holds all log lines after ExpectExit has
   197  // returned.
   198  func (tt *TestCmd) StderrText() string {
   199  	tt.stderr.mu.Lock()
   200  	defer tt.stderr.mu.Unlock()
   201  	return tt.stderr.buf.String()
   202  }
   203  
   204  func (tt *TestCmd) CloseStdin() {
   205  	tt.stdin.Close()
   206  }
   207  
   208  func (tt *TestCmd) Kill() {
   209  	tt.cmd.Process.Kill()
   210  	if tt.Cleanup != nil {
   211  		tt.Cleanup()
   212  	}
   213  }
   214  
   215  func (tt *TestCmd) withKillTimeout(fn func()) {
   216  	timeout := time.AfterFunc(10*time.Second, func() {
   217  		tt.Log("killing the child process (timeout)")
   218  		tt.Kill()
   219  	})
   220  	defer timeout.Stop()
   221  	fn()
   222  }
   223  
   224  // testlogger logs all written lines via t.Log and also
   225  // collects them for later inspection.
   226  type testlogger struct {
   227  	t   *testing.T
   228  	mu  sync.Mutex
   229  	buf bytes.Buffer
   230  }
   231  
   232  func (tl *testlogger) Write(b []byte) (n int, err error) {
   233  	lines := bytes.Split(b, []byte("\n"))
   234  	for _, line := range lines {
   235  		if len(line) > 0 {
   236  			tl.t.Logf("(stderr) %s", line)
   237  		}
   238  	}
   239  	tl.mu.Lock()
   240  	tl.buf.Write(b)
   241  	tl.mu.Unlock()
   242  	return len(b), err
   243  }
   244  
   245  // runeTee collects text read through it into buf.
   246  type runeTee struct {
   247  	in interface {
   248  		io.Reader
   249  		io.ByteReader
   250  		io.RuneReader
   251  	}
   252  	buf bytes.Buffer
   253  }
   254  
   255  func (rtee *runeTee) Read(b []byte) (n int, err error) {
   256  	n, err = rtee.in.Read(b)
   257  	rtee.buf.Write(b[:n])
   258  	return n, err
   259  }
   260  
   261  func (rtee *runeTee) ReadRune() (r rune, size int, err error) {
   262  	r, size, err = rtee.in.ReadRune()
   263  	if err == nil {
   264  		rtee.buf.WriteRune(r)
   265  	}
   266  	return r, size, err
   267  }
   268  
   269  func (rtee *runeTee) ReadByte() (b byte, err error) {
   270  	b, err = rtee.in.ReadByte()
   271  	if err == nil {
   272  		rtee.buf.WriteByte(b)
   273  	}
   274  	return b, err
   275  }