github.com/Elemental-core/elementalcore@v0.0.0-20191206075037-63891242267a/internal/cmdtest/test_cmd.go (about)

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