github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/cmd/gath/run_test.go (about)

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