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