github.com/tuotoo/go-ethereum@v1.7.4-0.20171121184211-049797d40a24/console/console_test.go (about)

     1  // Copyright 2015 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 console
    18  
    19  import (
    20  	"bytes"
    21  	"errors"
    22  	"fmt"
    23  	"io/ioutil"
    24  	"os"
    25  	"strings"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/eth"
    32  	"github.com/ethereum/go-ethereum/internal/jsre"
    33  	"github.com/ethereum/go-ethereum/node"
    34  )
    35  
    36  const (
    37  	testInstance = "console-tester"
    38  	testAddress  = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
    39  )
    40  
    41  // hookedPrompter implements UserPrompter to simulate use input via channels.
    42  type hookedPrompter struct {
    43  	scheduler chan string
    44  }
    45  
    46  func (p *hookedPrompter) PromptInput(prompt string) (string, error) {
    47  	// Send the prompt to the tester
    48  	select {
    49  	case p.scheduler <- prompt:
    50  	case <-time.After(time.Second):
    51  		return "", errors.New("prompt timeout")
    52  	}
    53  	// Retrieve the response and feed to the console
    54  	select {
    55  	case input := <-p.scheduler:
    56  		return input, nil
    57  	case <-time.After(time.Second):
    58  		return "", errors.New("input timeout")
    59  	}
    60  }
    61  
    62  func (p *hookedPrompter) PromptPassword(prompt string) (string, error) {
    63  	return "", errors.New("not implemented")
    64  }
    65  func (p *hookedPrompter) PromptConfirm(prompt string) (bool, error) {
    66  	return false, errors.New("not implemented")
    67  }
    68  func (p *hookedPrompter) SetHistory(history []string)              {}
    69  func (p *hookedPrompter) AppendHistory(command string)             {}
    70  func (p *hookedPrompter) SetWordCompleter(completer WordCompleter) {}
    71  
    72  // tester is a console test environment for the console tests to operate on.
    73  type tester struct {
    74  	workspace string
    75  	stack     *node.Node
    76  	ethereum  *eth.Ethereum
    77  	console   *Console
    78  	input     *hookedPrompter
    79  	output    *bytes.Buffer
    80  }
    81  
    82  // newTester creates a test environment based on which the console can operate.
    83  // Please ensure you call Close() on the returned tester to avoid leaks.
    84  func newTester(t *testing.T, confOverride func(*eth.Config)) *tester {
    85  	// Create a temporary storage for the node keys and initialize it
    86  	workspace, err := ioutil.TempDir("", "console-tester-")
    87  	if err != nil {
    88  		t.Fatalf("failed to create temporary keystore: %v", err)
    89  	}
    90  
    91  	// Create a networkless protocol stack and start an Ethereum service within
    92  	stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance})
    93  	if err != nil {
    94  		t.Fatalf("failed to create node: %v", err)
    95  	}
    96  	ethConf := &eth.Config{
    97  		Genesis:   core.DeveloperGenesisBlock(15, common.Address{}),
    98  		Etherbase: common.HexToAddress(testAddress),
    99  		PowTest:   true,
   100  	}
   101  	if confOverride != nil {
   102  		confOverride(ethConf)
   103  	}
   104  	if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
   105  		t.Fatalf("failed to register Ethereum protocol: %v", err)
   106  	}
   107  	// Start the node and assemble the JavaScript console around it
   108  	if err = stack.Start(); err != nil {
   109  		t.Fatalf("failed to start test stack: %v", err)
   110  	}
   111  	client, err := stack.Attach()
   112  	if err != nil {
   113  		t.Fatalf("failed to attach to node: %v", err)
   114  	}
   115  	prompter := &hookedPrompter{scheduler: make(chan string)}
   116  	printer := new(bytes.Buffer)
   117  
   118  	console, err := New(Config{
   119  		DataDir:  stack.DataDir(),
   120  		DocRoot:  "testdata",
   121  		Client:   client,
   122  		Prompter: prompter,
   123  		Printer:  printer,
   124  		Preload:  []string{"preload.js"},
   125  	})
   126  	if err != nil {
   127  		t.Fatalf("failed to create JavaScript console: %v", err)
   128  	}
   129  	// Create the final tester and return
   130  	var ethereum *eth.Ethereum
   131  	stack.Service(&ethereum)
   132  
   133  	return &tester{
   134  		workspace: workspace,
   135  		stack:     stack,
   136  		ethereum:  ethereum,
   137  		console:   console,
   138  		input:     prompter,
   139  		output:    printer,
   140  	}
   141  }
   142  
   143  // Close cleans up any temporary data folders and held resources.
   144  func (env *tester) Close(t *testing.T) {
   145  	if err := env.console.Stop(false); err != nil {
   146  		t.Errorf("failed to stop embedded console: %v", err)
   147  	}
   148  	if err := env.stack.Stop(); err != nil {
   149  		t.Errorf("failed to stop embedded node: %v", err)
   150  	}
   151  	os.RemoveAll(env.workspace)
   152  }
   153  
   154  // Tests that the node lists the correct welcome message, notably that it contains
   155  // the instance name, coinbase account, block number, data directory and supported
   156  // console modules.
   157  func TestWelcome(t *testing.T) {
   158  	tester := newTester(t, nil)
   159  	defer tester.Close(t)
   160  
   161  	tester.console.Welcome()
   162  
   163  	output := string(tester.output.Bytes())
   164  	if want := "Welcome"; !strings.Contains(output, want) {
   165  		t.Fatalf("console output missing welcome message: have\n%s\nwant also %s", output, want)
   166  	}
   167  	if want := fmt.Sprintf("instance: %s", testInstance); !strings.Contains(output, want) {
   168  		t.Fatalf("console output missing instance: have\n%s\nwant also %s", output, want)
   169  	}
   170  	if want := fmt.Sprintf("coinbase: %s", testAddress); !strings.Contains(output, want) {
   171  		t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want)
   172  	}
   173  	if want := "at block: 0"; !strings.Contains(output, want) {
   174  		t.Fatalf("console output missing sync status: have\n%s\nwant also %s", output, want)
   175  	}
   176  	if want := fmt.Sprintf("datadir: %s", tester.workspace); !strings.Contains(output, want) {
   177  		t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want)
   178  	}
   179  }
   180  
   181  // Tests that JavaScript statement evaluation works as intended.
   182  func TestEvaluate(t *testing.T) {
   183  	tester := newTester(t, nil)
   184  	defer tester.Close(t)
   185  
   186  	tester.console.Evaluate("2 + 2")
   187  	if output := string(tester.output.Bytes()); !strings.Contains(output, "4") {
   188  		t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
   189  	}
   190  }
   191  
   192  // Tests that the console can be used in interactive mode.
   193  func TestInteractive(t *testing.T) {
   194  	// Create a tester and run an interactive console in the background
   195  	tester := newTester(t, nil)
   196  	defer tester.Close(t)
   197  
   198  	go tester.console.Interactive()
   199  
   200  	// Wait for a promt and send a statement back
   201  	select {
   202  	case <-tester.input.scheduler:
   203  	case <-time.After(time.Second):
   204  		t.Fatalf("initial prompt timeout")
   205  	}
   206  	select {
   207  	case tester.input.scheduler <- "2+2":
   208  	case <-time.After(time.Second):
   209  		t.Fatalf("input feedback timeout")
   210  	}
   211  	// Wait for the second promt and ensure first statement was evaluated
   212  	select {
   213  	case <-tester.input.scheduler:
   214  	case <-time.After(time.Second):
   215  		t.Fatalf("secondary prompt timeout")
   216  	}
   217  	if output := string(tester.output.Bytes()); !strings.Contains(output, "4") {
   218  		t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
   219  	}
   220  }
   221  
   222  // Tests that preloaded JavaScript files have been executed before user is given
   223  // input.
   224  func TestPreload(t *testing.T) {
   225  	tester := newTester(t, nil)
   226  	defer tester.Close(t)
   227  
   228  	tester.console.Evaluate("preloaded")
   229  	if output := string(tester.output.Bytes()); !strings.Contains(output, "some-preloaded-string") {
   230  		t.Fatalf("preloaded variable missing: have %s, want %s", output, "some-preloaded-string")
   231  	}
   232  }
   233  
   234  // Tests that JavaScript scripts can be executes from the configured asset path.
   235  func TestExecute(t *testing.T) {
   236  	tester := newTester(t, nil)
   237  	defer tester.Close(t)
   238  
   239  	tester.console.Execute("exec.js")
   240  
   241  	tester.console.Evaluate("execed")
   242  	if output := string(tester.output.Bytes()); !strings.Contains(output, "some-executed-string") {
   243  		t.Fatalf("execed variable missing: have %s, want %s", output, "some-executed-string")
   244  	}
   245  }
   246  
   247  // Tests that the JavaScript objects returned by statement executions are properly
   248  // pretty printed instead of just displaing "[object]".
   249  func TestPrettyPrint(t *testing.T) {
   250  	tester := newTester(t, nil)
   251  	defer tester.Close(t)
   252  
   253  	tester.console.Evaluate("obj = {int: 1, string: 'two', list: [3, 3, 3], obj: {null: null, func: function(){}}}")
   254  
   255  	// Define some specially formatted fields
   256  	var (
   257  		one   = jsre.NumberColor("1")
   258  		two   = jsre.StringColor("\"two\"")
   259  		three = jsre.NumberColor("3")
   260  		null  = jsre.SpecialColor("null")
   261  		fun   = jsre.FunctionColor("function()")
   262  	)
   263  	// Assemble the actual output we're after and verify
   264  	want := `{
   265    int: ` + one + `,
   266    list: [` + three + `, ` + three + `, ` + three + `],
   267    obj: {
   268      null: ` + null + `,
   269      func: ` + fun + `
   270    },
   271    string: ` + two + `
   272  }
   273  `
   274  	if output := string(tester.output.Bytes()); output != want {
   275  		t.Fatalf("pretty print mismatch: have %s, want %s", output, want)
   276  	}
   277  }
   278  
   279  // Tests that the JavaScript exceptions are properly formatted and colored.
   280  func TestPrettyError(t *testing.T) {
   281  	tester := newTester(t, nil)
   282  	defer tester.Close(t)
   283  	tester.console.Evaluate("throw 'hello'")
   284  
   285  	want := jsre.ErrorColor("hello") + "\n"
   286  	if output := string(tester.output.Bytes()); output != want {
   287  		t.Fatalf("pretty error mismatch: have %s, want %s", output, want)
   288  	}
   289  }
   290  
   291  // Tests that tests if the number of indents for JS input is calculated correct.
   292  func TestIndenting(t *testing.T) {
   293  	testCases := []struct {
   294  		input               string
   295  		expectedIndentCount int
   296  	}{
   297  		{`var a = 1;`, 0},
   298  		{`"some string"`, 0},
   299  		{`"some string with (parentesis`, 0},
   300  		{`"some string with newline
   301  		("`, 0},
   302  		{`function v(a,b) {}`, 0},
   303  		{`function f(a,b) { var str = "asd("; };`, 0},
   304  		{`function f(a) {`, 1},
   305  		{`function f(a, function(b) {`, 2},
   306  		{`function f(a, function(b) {
   307  		     var str = "a)}";
   308  		  });`, 0},
   309  		{`function f(a,b) {
   310  		   var str = "a{b(" + a, ", " + b;
   311  		   }`, 0},
   312  		{`var str = "\"{"`, 0},
   313  		{`var str = "'("`, 0},
   314  		{`var str = "\\{"`, 0},
   315  		{`var str = "\\\\{"`, 0},
   316  		{`var str = 'a"{`, 0},
   317  		{`var obj = {`, 1},
   318  		{`var obj = { {a:1`, 2},
   319  		{`var obj = { {a:1}`, 1},
   320  		{`var obj = { {a:1}, b:2}`, 0},
   321  		{`var obj = {}`, 0},
   322  		{`var obj = {
   323  			a: 1, b: 2
   324  		}`, 0},
   325  		{`var test = }`, -1},
   326  		{`var str = "a\""; var obj = {`, 1},
   327  	}
   328  
   329  	for i, tt := range testCases {
   330  		counted := countIndents(tt.input)
   331  		if counted != tt.expectedIndentCount {
   332  			t.Errorf("test %d: invalid indenting: have %d, want %d", i, counted, tt.expectedIndentCount)
   333  		}
   334  	}
   335  }